-- Durable intent before RunTask. The server derives owner_id from its session. CREATE TABLE sandbox_jobs ( job_id uuid PRIMARY KEY, owner_id uuid NOT NULL, client_token varchar(64) NOT NULL UNIQUE, request jsonb NOT NULL, expires_at timestamptz NOT NULL, task_arn text UNIQUE, state text NOT NULL DEFAULT 'reserved' CHECK (state IN ('reserved', 'running', 'stopping', 'stopped', 'reconcile')), slot_released_at timestamptz, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX sandbox_jobs_due ON sandbox_jobs (expires_at) WHERE state <> 'stopped'; -- In a transaction, reserve a separate bounded concurrency slot, then insert intent. -- Parameter placeholders below use psycopg-style named parameters. INSERT INTO sandbox_jobs (job_id, owner_id, client_token, request, expires_at) VALUES (%(job_id)s, %(owner_id)s, %(token)s, %(request)s::jsonb, %(expires_at)s) ON CONFLICT (job_id) DO NOTHING; -- On conflict: SELECT under owner_id and compare the stored request and deadline. -- Never replace intent with a caller's new image, role, subnet or token. -- Claim due jobs in short transactions; invoke AWS after committing the claim. SELECT job_id, task_arn, expires_at FROM sandbox_jobs WHERE state IN ('running', 'reconcile') AND expires_at <= now() ORDER BY expires_at FOR UPDATE SKIP LOCKED LIMIT 50; -- A production worker also needs claim leases, recovery of reserved jobs, -- transactional slot accounting and terminal-state reconciliation.