Repository navigation
Runner queue: claim, heartbeat, complete, leases, settlement (DM-07) - #2154
Merged
neuromechanist merged 13 commits intoNov 14, 2026
Merged
Conversation
…nto feature/pc-dm07-runner-queue
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR2154Version: 🤖 Updated on each push. |
…nto feature/pc-dm07-runner-queue
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Card DM-07 (portable compute): the runner queue, claim, heartbeat, complete, leases, deadlines and the terminal settlement of
accounting = 'none'jobs. Needs the Opus review (claim atomicity, lease semantics, at-most-once acceptance, terminal settlement ofnonejobs).The claim statement, literally
CLAIM_RUNNER_JOB_SQL(backend/src/services/compute-runner-queue.ts), one conditional UPDATE per job,meta.changes = 1is the winner test.SET:
runner_claimed_at = datetime('now'),runner_id = ?1,runner_backend = ?2(the registration's),lease_id = ?3,lease_expires_at = datetime('now', '+600 seconds'),claim_attempts = claim_attempts + 1,webhook_nonce = COALESCE(webhook_nonce, ?4).WHERE
id = (SELECT j.id ... ORDER BY j.created_at ASC, j.id ASC LIMIT 1)AND the same terms again on the outer row, so the statement is atomic by itself, ANDEXISTS (SELECT 1 FROM compute_runners r JOIN users u ON u.id = r.registered_by WHERE r.id = ?1 AND r.revoked_at IS NULL AND u.role = 'owner' AND u.status = 'approved' AND u.deleted_at IS NULL).The terms (alias
a):a.executor = 'runner' AND a.accounting = 'none' AND a.state = 'created' AND a.runner_claimed_at IS NULL AND a.records_written_at IS NOT NULL AND a.cancel_requested_at IS NULL AND a.claim_attempts < ?5 AND a.pool = ?6 AND a.cores_per_node <= ?7 AND COALESCE(a.memory_mb, 0) <= ?8 AND a.gpus <= ?9 AND EXISTS (SELECT 1 FROM compute_pipeline_stamps s JOIN datasets d ON d.dataset_id = s.dataset_id WHERE s.job_id = a.id AND <PIPELINE_ELIGIBLE_SQL>).The dataset is found through the job's stamp (a runner job has no dataset column and a Zarr recipe stages no dataset); a job whose stamp is not linked yet is simply not claimed that round.
Each winner is found by its own random lease id, its launch specification is built with the Tapis path's
buildLaunch, andlaunch_spec_digestis written byLAUNCH_DIGEST_UNDER_LEASE_SQL(guard: job, lease, runner,state = 'created',cancel_requested_at IS NULL); a winner whose digest write changes no row (a revoke or a cancel got in) is not answered.Statements added or changed
Added in
compute-runner-queue.ts:CLAIM_RUNNER_JOB_SQL,CLAIMED_BY_LEASE_SQL,LAUNCH_DIGEST_UNDER_LEASE_SQL,RELEASE_CLAIM_SQL,HEARTBEAT_STARTED_SQL(created to running, cancel guard),HEARTBEAT_UPLOADING_SQL(running to archiving, cancel guard),HEARTBEAT_RENEW_SQL,RECORD_USAGE_SQL(once, under the lease),CANCELLED_ROWS_SQL,RELEASE_EXPIRED_CLAIMS_SQL,EXHAUSTED_ROWS_SQL,UNREPORT_EXPIRED_SQL(cancel guard),UNREPORTED_ROWS_SQL,DEADLINE_ROWS_SQL,REPLAY_ROWS_SQL,RUNNER_UNCOPIED_SQL,RUNNER_CANCEL_PENDING_FAILED_SQL,RUNNER_COPY_ABANDONED_SQL.Added in
compute-lifecycle.ts:NONE_SETTLED_STAMP_SQL,CANCEL_WAITING_RUNNER_SQL,END_CANCELLED_STAMP_SQL,endWaitingRunnerJob.Changed in
compute-lifecycle.ts:commitTerminalis exported and, forjob.accounting === 'none', buildsNONE_SETTLED_STAMP_SQLinstead of the ledger statements andSETTLED_STAMP_SQL(every other row's batch is unchanged);buildLaunchis exported and also returns the image reference, digest and SIF name;afterTerminal,recordsRetentionYears,launcherDocumentLimitare exported;requestComputeCancelends a waiting runner job in one batch and leaves a claimed one with its recorded intent.Changed in
compute-jobs.ts:writeRecordsis exported (the replay uses it).Changed in
compute-job-callbacks.ts:authorizealso requiresX-Compute-Leaseequal to the row'slease_idforexecutor = 'runner', both present and matchingLEASE_ID_RE; a missing, malformed or NULL value is the existing single refusal (job_not_found).Changed in
compute-status.ts,compute-admin.ts(contract wordsCOMPUTE_RUNNER_ATTENTION_WORDS),admin-compute.ts(the two attention lines with their hints),index.ts(the tick),compute-runners.ts(routesPOST /claim,/heartbeat,/complete).Decisions the card left open
A started job whose lease expires goes
unreportedKEEPING its lease id (so a partitioned runner can still land outputs under the same lease); a heartbeat renews anunreportedjob's lease, so a live runner is not given up on.The sweep order is replay, cancels, release and exhaustion, unreport, settle
unreported, deadline, copy; one budget ofRUNNER_SWEEP_BATCHrows is shared by the steps.A job that is unclaimed with its claims used up (a revoke gave the last claim back) fails
claims_exhaustedinstead of waiting for ever.A claimed job whose specification can never be built ends
failedlaunch_failedinvalid_spec; one that cannot be built for want of configuration is given back.The waiting-job cancel ends its pipeline stamp in the same batch (state
failed, wordjob_cancelled, exactly what the stamp sync writes), so no change tosyncPipelineStampswas needed.RUNNER_MIN_VERSION = "0.1.0"lives in the queue module because the contract file is out of this card's scope.The
runner_lostdetails are not in theComputeFailureDetailtype (DM-04's), so the queue casts them in one place.Gates
bun run typecheck,bun run lint,bunx biome checkon the touched files: clean (the warnings printed are olderanyand!uses in files this PR does not otherwise change).bun test backend/test/compute-runner-queue.test.ts backend/test/cron-sweep-wiring.test.ts backend/test/compute-route-inventory.test.ts backend/test/compute-e2e.test.ts: 287 pass, 0 fail.bun test backend/test/compute-lifecycle*.test.ts backend/test/compute-sweep.test.ts: 236 pass, 0 fail.All
backend/test/compute-*files: 1870 pass, 2 skip, 0 fail (run before the last two test cases were added; that file alone is 61 pass).Races: 50 rounds on bun:sqlite with round-trip latency and 50 rounds on Miniflare's D1, two runners each, one waiting job per round: 100 rounds, exactly one winner in every one,
claim_attempts1.Mutations (each run alone, then reverted, tree clean): 26 one-line mutations of the claim, lease, sweep, settlement, cancel, usage, copy and attention statements, every one killed by a named case (the cases name their mutation); the two first survivors (the usage guard and the lease compare of
complete) got cases of their own.Not run: the full
bun test, would check: the epic gate, because it takes about 80 minutes and is the manager's.Other
One existing DM-06 case changed: "the cancel sweep selects no runner row" now claims the job by SQL first, because a waiting runner job's cancel now ends in SQL (this card's rule) and only a claimed one keeps the intent.
UNCOPIED_TERMINAL_SQLstill selects Tapis rows (DM-06 pins it), so the runner copy has its own list,RUNNER_UNCOPIED_SQL, called by the sweep.Overlap with the epic D PR #2116 (files both touch):
backend/src/index.ts,backend/src/services/compute-jobs.ts,backend/src/services/compute-lifecycle.ts,backend/src/services/compute-status.ts,backend/test/compute-route-inventory.test.ts,backend/test/compute-status-route.test.ts.A waiting row whose specification can no longer be rebuilt to the recorded digest (the image or the dataset's commit changed) is left alone by the replay and stays waiting until cancelled.
Card DM-07.
Review round 1 (added)
Merged
origin/feature/portable-compute-epic(DM-06b) before the final gates; the merge was clean. DM-06b changed the Zarr spec, so the records replay now rebuilds a Zarr specification from the same source check the dispatch uses (a call to GitHub and the serving index, in the slow phase), and accepts it only when its digest is the recorded one.Fixes, by finding:
launchConfiguredis asked before any claim UPDATE (secret, API base address, records bucket); every give-back (RELEASE_CLAIM_SQL) now restores the counter (claim_attempts = MAX(claim_attempts - 1, 0)). Tests: no claim statement runs and five polls leaveclaim_attempts0; an unbuildable specification endsfailedlaunch_failedinvalid_specand the next job is still answered.RUNNER_TERMINAL_TRANSITION_SQL(the Tapis statement plusAND lease_id IS ?17, bound to the lease the writer read, used for runner rows only) incommitTerminal;completeRunnerJobwrites the usage AFTER the end and answerslease_lostwhen the row is no longer the body's runner and lease;RECORD_USAGE_SQLhas no state term and keeps the lease and runner terms;COMPLETE_OUTPUTS_SQL,CLAIM_RESULTS_BYTES_SQLandRECORD_REFUSAL_SQLcarry(?n = 0 OR lease_id IS ?m), bound for any job that is not a Tapis job. Race cases (an exact interleaving injected between two real statements of one real database): a completion whose claim was released and taken again (same runner and another), a completion that passed the check before a revoke, outputs-complete, the declared-bytes claim and the launch digest each under a replaced lease; each writes nothing and records nothing.RUNNER_SWEEP_BATCHrows; every examined row is stamped (examined_at) and the steps order by it (rotation); a step whose batch was full is counted (saturated, in the log line); a waiting row whose records never landed and could not be replayed for 60 minutes endsfailedrecords_unavailable(detailrecords_unreadable; the contract allows it and it says what is true), which frees its slot and tuple; a new attention wordrunner_records_unwritten(such a row still there after 120 minutes) is counted in the status and printed by the CLI. Test: 11 unreplayable rows do not stop a cancelled-and-expired job being ended, rotate over two calls, and are ended after the window.job.executor !== "tapis" && !holdsCurrentLease(...); the outputs statements bind the lease for any non-Tapis row too. Conflict sites to watch when Epic: Third-party compute: access, user API, nemar compute, partner contract (#2021) #2116 is merged:JOB_COLUMNSincompute-jobs.ts(keepexecutor,accounting,lease_idand the other runner columns);commitTerminalincompute-lifecycle.tsversus Epic: Third-party compute: access, user API, nemar compute, partner contract (#2021) #2116'scapPartnerCharge(keep theaccounting === "none"branch and therunnerRowstatement choice, or runner jobs are never settled); theCANCEL_PENDING_FAILED_SQLline carryingexecutor = 'tapis'; theATTENTION_COUNTSinsert next topartner_capped_no_final(keep...RUNNER_ATTENTION_COUNTS); the same cancel-sweep statements incompute-jobs.tsand the two status tests.uploadingheartbeat starts acreatedjob (withstarted_at); a claim whose outputs completed is never released (RELEASE_EXPIRED_CLAIMS_SQL) nor failedclaims_exhausted: it is moved tounreported(UNREPORT_EXPIRED_SQLtakes an unstarted claim with outputs) and verified. Tests for both.DEADLINE_ROWS_SQLno longer excludes a recorded cancel: such a job is endedcancelledat the deadline (without a cancel:deadline_exceeded). Test.held(...)), sofree_slots32 on 8 cores and 40 GB gets two 4-core 16 GB jobs and the third waits for room. Test.waitUntil(sweepRunnerLeases(env, db, { defer }), which logs its own line when the slow part ends). Test: a claim is answered while a verification waits on a gated results bucket, and the job is finished after the gate opens.outcome: cancelled(a new word inCOMPUTE_CANCEL_OUTCOMES); a claimed one still answerscancel_requested. Tests for both words.RUNNER_MIN_VERSION,RUNNER_RECORDS_REPLAY_MINUTESandRUNNER_RECORDS_GIVE_UP_MINUTESintoshared/contract/compute-runner.ts, where ADR 0121 says every number lives.executor = 'runner'ofRUNNER_UNCOPIED_SQL, the lease term ofLAUNCH_DIGEST_UNDER_LEASE_SQL, the lease term ofRECORD_USAGE_SQL,claim_attempts < ?1of the release (via thereleasedcount); the claim-statement test now checks every term for both the picked row and the row written.Gates after the merge:
bun run typecheckandbun run lintclean; biome clean on the touched files; the acceptance files 307 pass, 0 fail;compute-lifecycle*andcompute-sweep236 pass, 0 fail; allbackend/test/compute-*1898 pass, 2 skip, 0 fail; contract and CLI tests 218 pass, 0 fail.Mutations after the fixes: the earlier 26 were rerun and killed (the M18 case by removing both terms of the unreport), and 24 new ones (N1 to N24) were run alone and reverted: 21 killed on the first run; the three survivors, N2 (the configuration check), N14 (the release outputs term, which is in two places) and N24 (the exhausted outputs term), got a new case each (N2: one that watches for a claim statement) and are killed.
Not run: the full
bun test, would check: the epic gate.Review round 2 (added)
Fixes, by finding (each has a case that fails without it; the mutation list is below):
handleOutputs, when the declared-bytes claim changes no row and the row's lease is no longer the one the route proved, the request is refusedbad_statewithout recording or presigning. The race case now assertsfailure_detailis null and that the new holder's own outputs call succeeds.RELEASE_CLAIM_COUNTED_SQL) and the loop goes on to the next job, so a poisoned row endsclaims_exhaustedafter three claims and cannot stall the pool; only the Worker-wideunconfiguredgap is given back uncounted. Case: a bucket that always throws for the middle job; the first and third are answered over two calls and the poisoned one ends after three counted claims.REPLAY_ROWS_SQLtakes only rows not examined in the last 5 minutes, so ten unwritten rows with the store down cost one pass of GitHub requests per five minutes, not one per poll), runs LAST in the slow phase (verifications and copies first), each replay under its own bound (RUNNER_REPLAY_BOUND_MS, 8 s) and no replay starts after the phase's allowance (RUNNER_REPLAY_PHASE_MS, 20 s, under the 30 swaitUntilcap). Cases: a second poll within five minutes makes no GitHub request and one five minutes later does; a verification and its copy finish while a replay still waits on a stalled GitHub; a stalled replay holds the phase for the bound only; no replay starts after the allowance.failedrecords_unavailableonly when a replay in the same call finds a real mismatch (a stamp or recipe that is gone, a source that says another commit, a rebuilt specification that is not the recorded one); an unreachable source or a store that is down is not a mismatch.RECORDS_GIVE_UP_ROWS_SQLis gone. Cases for a replay that now succeeds (replayed, not given up on, records written on a live row), an unreachable source (left alone) and a mismatch (ended in the same call).RELEASE_EXPIRED_CLAIMS_SQLskips a claim whose outputs were declared (results_bytes);UNREPORT_EXPIRED_SQLtakes such an unstarted claim (verified if the outputs completed, given up on after 60 minutes like any silent job otherwise), andEXHAUSTED_ROWS_SQLapplies the outputs and declared terms to a claimed row only (an unclaimed row whose claims are used up is still failed). Cases for both.commitTerminalchooses the lease statement withjob.executor !== "tapis", like the launcher routes (source-search case).launchConfiguredincludes the runtime image, so no poll claims a job only to give it back (case: no claim statement runs without an image).completeRunnerJobdecides the plan (and its slow verification) once, commits it, and when that commit loses to a heartbeat that moved the state it commits the same plan once more from the row read anew while the lease is still the call's. Case: anuploadingheartbeat injected between the verification and the commit; the answer isfailedwith the reported reason, notarchiving.Gates:
bun run typecheck,bun run lint, biome on the touched files clean; acceptance files 319 pass, 0 fail;compute-lifecycle*andcompute-sweep236 pass, 0 fail; the queue file is 93 cases (was 80); allbackend/test/compute-*: 1910 pass, 2 skip, 0 fail.Mutations, each run alone and reverted (tree clean): P1 to P16 (stale record, uncounted give-back, stop at first throw, claim outside the try, no throttle, replays first, unbounded replay, no phase allowance, unreachable as mismatch, give up a fresh row, release declared claims (both copies of the term together), exhausted declared term, no second commit, fail-open lease statement, no image check, unreport of declared claims): all killed.