stock-bot/database/postgres/init/10-durable-backtest-dispatch.sql
2026-10-20 20:11:40 -04:00

43 lines
2.4 KiB
SQL

-- Additive migration. Stop old orchestrators before deploying lease-aware workers.
ALTER TABLE runs ADD COLUMN IF NOT EXISTS request_snapshot JSONB;
ALTER TABLE runs ADD COLUMN IF NOT EXISTS attempt_id UUID;
ALTER TABLE runs ADD COLUMN IF NOT EXISTS attempt_number INTEGER NOT NULL DEFAULT 0;
ALTER TABLE runs ADD COLUMN IF NOT EXISTS lease_expires_at TIMESTAMPTZ;
ALTER TABLE runs ADD COLUMN IF NOT EXISTS cancel_requested BOOLEAN NOT NULL DEFAULT FALSE;
CREATE TABLE IF NOT EXISTS backtest_dispatch (
run_id UUID PRIMARY KEY REFERENCES runs(id) ON DELETE CASCADE,
next_publish_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_published_at TIMESTAMPTZ,
publish_count INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS backtest_dispatch_due ON backtest_dispatch(next_publish_at);
CREATE INDEX IF NOT EXISTS runs_expired_lease ON runs(lease_expires_at)
WHERE status IN ('running', 'paused');
-- Legacy pending runs did not capture a snapshot. Freeze their current definition once.
UPDATE runs r SET request_snapshot = jsonb_build_object(
'mode', 'backtest', 'runId', r.id, 'backtestId', b.id, 'name', b.name,
'strategy', b.strategy, 'symbols', b.symbols,
'startDate', to_char(b.start_date AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
'endDate', to_char(b.end_date AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
'initialCapital', b.initial_capital,
'config', COALESCE(b.config, '{}'::jsonb),
'dataFrequency', COALESCE(b.config->>'dataFrequency', '1d'),
'commission', COALESCE(b.config->'commission', '0.001'::jsonb),
'slippage', COALESCE(b.config->'slippage', '0.0001'::jsonb),
'speed', CASE WHEN r.speed_multiplier IS NULL THEN 'max'
WHEN r.speed_multiplier >= 10 THEN '10x'
WHEN r.speed_multiplier >= 5 THEN '5x'
WHEN r.speed_multiplier >= 2 THEN '2x' ELSE 'realtime' END
) FROM backtests b WHERE b.id = r.backtest_id AND r.status = 'pending'
AND r.request_snapshot IS NULL;
-- There is no safe way to identify the owner of a pre-lease active execution.
UPDATE runs SET status = 'failed', completed_at = NOW(), updated_at = NOW(),
error = 'Legacy execution has no lease; create a new run after deployment'
WHERE status IN ('running', 'paused') AND attempt_id IS NULL;
INSERT INTO backtest_dispatch (run_id)
SELECT id FROM runs WHERE status = 'pending' AND request_snapshot IS NOT NULL
ON CONFLICT (run_id) DO NOTHING;