Repository navigation
Phase A5: Job lifecycle, webhooks, settlement and results - #2041
Merged
Conversation
4 tasks
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR2041Version: 🤖 Updated on each push. |
neuromechanist
merged commit Nov 5, 2026
220856d
into
feature/issue-2005-epic-compute-core
17 of 19 checks passed
neuromechanist
deleted the
feature/issue-2010-phase5-job-lifecycle-webhooks-settlement
branch
November 5, 2026 01:27
4 tasks
This was referenced Nov 5, 2026
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.
Summary
Phase A5 of the compute program (epic #2005, issue #2010, ADR 0118 and its amendments). A job row becomes a running, settled, verified Tapis job without anyone watching: NEMAR submits idempotently, follows the job by webhook hint and a 30-minute backstop, settles its charge, serves the launcher's three callbacks behind a per-job token, verifies the upload before
finished, copies the launcher's files and logs into the records, mails the person a link to a page, and cancels on request.The owner decisions of 2026-11-04 are built in: NEMAR owns every Tapis job (the owner is the NEMAR service identity from configuration), no failure is refunded automatically (consumed units stay consumed, a job that never started is released,
isPlatformFailureis an information flag on the row), and thepeoplebudget records consumption only (no path of this phase credits it).This body was rewritten after round 1 of the review (an Opus checkpoint and two Sonnet reviewers). The first section says what round 1 changed; the rest is the original description, corrected where round 1 changed it.
Round 2: what changed (delta review of
1287fdd9)Memory clamped to the queue (the review's first finding,
6db4bda3). The memory a submit carries was the memory the charge pays for, and a wholecomputenode is 262,144 MB, its nominal physical memory. The program's own Tapis execution system (nemar-process,deploy/tapis/systems/exec.json.tmpl) declaresmaxMemoryMB249,208 for theshared,compute,debugandpreemptqueues, 2,048,000 forlarge-sharedand 377,308 for the four GPU queues, so every whole-node CPU job (and adebugorpreemptjob of 122 cores or more that named no memory) would have been refused at submit and endedtapis_submit_failedas a platform failure. The Tapis stand-in models no queue limits, so every test passed. Nowcompute-queues.tsdeclaresQUEUE_MAX_MEMORY_MBonce, in the backend (the contract has no slot for it and its schema, golden vector and checksum are untouched;submitMemoryMbstays as it was), and the submit sends the derived figure clamped to it.compute-queues.test.tspins the figures as literals and, whenNEMAR_PROCESS_DIRnames a nemar-process checkout, compares them with that file'smaxMemoryMBfor every queue (it skips visibly without it; run against the C5 branch it passes). A 128-corecomputejob, a 128-coredebugjob and a whole GPU node (376,832 MB, under 377,308) each submit within their maximum, and a test asserts that for every partition at its largest shape the figure is within its queue. OWNER ITEM: the queue figures come from the public Expanse user guide through C5, are UNVERIFIED, and need confirming with the site.A cancel during an in-flight submit (the review's second finding,
e2de0fcf). While a submitter held the lease with the digest written, a cancel's tag search could run before Tapis had persisted the job, find nothing and end the row and release the hold; if the submitter's answer was then lost,tapis_uuidandorphan_tapis_uuidwere both NULL, the row was terminal and nothing ever searched again, so the Tapis job ran uncharged and uncancelled. NowdriveCancel, in the branch for a row with no Tapis job, returns and leaves the intent when the submitter's lease is younger thanSUBMIT_LEASE_MINUTES; the submitter's bind already turns a pending cancel into an orphan cancel, and once the lease ends the sweep's tag search is authoritative. The reproduction is a test (the Tapis job is hidden from the cancel's search, the submit's answer is dropped, and the Tapis job still ends CANCELLED with the ledger[hold, release]), and the older test that asserted an immediatecancellednow takes a sweep step.Smaller items:
e2de0fcf): the claim writes the submitter's own stamp (to the millisecond) and the release clears the lease only while it is still that stamp, so an attempt that outlives its five minutes cannot clear its successor's lease. A test makes an attempt's lease be taken over mid-flight and asserts the successor's survives.readBoundedJsonObjectwith a 4 KiB cap (LINKS_BODY_MAX_BYTES); an oversize body, declared or not, isinvalid_specwith status 413, and an empty body orContent-Length: 0is still the first page.compute_jobs_examinedserved no query, becauseORDER BY COALESCE(examined_at, '')hid the column from the planner (the plan was a walk of every row that ever had a Tapis job). The three tick queries now order by the bare column (SQLite sorts NULL first, so the order is unchanged) and a test readsEXPLAIN QUERY PLANand pins that the live-row query uses the index. The migration did not change, somigrations:d1-checkwas not run again.Round 1: what changed
Migration
0116_compute_lifecycle.sqlis unreleased and was edited in place: it now adds nine columns (launch_spec_digest,results_verified_at,outputs_completed_at,results_bytes,result_records_at,platform_failure,examined_at,submit_claimed_at,orphan_tapis_uuid) and the indexescompute_jobs_resultsandcompute_jobs_examined.Money and state (items 1 to 6, commit
e1ae47a9):mismatch. A time that runs backwards is zero seconds.examined_at(a row is stamped before its step, whether or not the step succeeds), and the bound rows and thecreatedrows have a quota each.Results, records, links and callbacks (items 7 to 13):
tapisjob.outover 5 MiB is copied as its first 5 MiB and the object records that it was cut (truncatedmetadata); a log that could not be read for any reason but not existing leaves the whole copy owed, so it is never stamped done without it. A4's client gained an additivedownloadOutputPrefix(downloadOutputis unchanged).{ "after": "<output path>" }body,next_afterin the answer, 1,000 at a time.invalid_specnaming the output BEFORE the claim; it used to claim the bytes and answer 500, then 409.COMPUTE_RUNTIME_IMAGEis one digest-pinned reference, validated when read (compute-runtime-image.ts), with the digest and the Singularity file name derived by the contract's functions;GET /admin/compute/statusandnemar admin compute statusreport whether it is set, whether it is valid and its digest, never the reference.cancelandlinksstay blocked, andfullrefuses all.middleware/access-log.ts); the entry point mounts that logger and not Hono's own.Tests (items 14 to 18): the verification checks that had no failing test now have one each (manifest path, size, checksum, one entry more and one fewer; an output's stored SHA-256; a launcher file replaced after
complete;records_unavailablefor a deleted and for a mismatchedspec.jsonand for an unbound records bucket); verification pagination at 999, 1,000, 1,001 and 2,500 outputs; the one-batch claim and the settlement gate through the flow; a source scan that pinstimingSafeEqual(token, expected)and the single gating read ofcomputeEnabled(, each shown to fire on a planted violation; terminal paths with compute off through the webhook and the tick; the exact timeouts asked for (8 and 10 seconds); the 7-day lifetime written out; a route-driven full path (compute-full-path.test.ts: hold, submit, every status by the stand-in's own webhook, the launcher through the real routes and presigned PUTs, verified, settled once, copied, mailed once, linked) and an entry-point race. The fixture header no longer claims that nothing is stood in for:playLauncheris named as the one played step.Types, declared once, docs (items 19 to 21): the plan's failure code and detail are
ComputeFailureCodeandComputeFailureDetail(a closed union plus one branded slot for a launcher word the table does not declare, which stays deliberate);VERIFY_REASONSandrecords_unreadablemoved toshared/compute-state.ts; the route refusal sentences,NO_NONCE, the SQL state lists, the reporting states and the job-token header are each declared once; dead test code is gone; the tick's cost comment is rewritten (two attempts, about 800 subrequests worst case, whether binding calls count is stated as unverified); ADR 0118 carries inline superseded markers on body decisions 4 and 13 and unambiguous references;implementation-notes.mdno longer calls option A "open"; the CLI help forjobs advancesays its submit is refused while compute is off.One item that arrived mid-batch (from the C5 checkpoint): every Tapis submit now carries
memoryMB,maxMinutes,nodeCountandcoresPerNode. Tapis always passes a memory to the scheduler (its default is 100 MB), so a whole-node job that named none would have been charged for a node and limited to 100 MB.submitMemoryMbin the contract derives it from the same rate table the hold is priced with: a wholecomputenode is 128 x 2,048 MB, a wholegpunode 4 x 94,208 MB, a per-core or per-GPU job uses its ownmemory_mbelse its cores' or GPUs' share. The partition table has no per-node memory field, so a whole node's memory is derived from the rate table (the figures are the design's reading of the node sizes, unconfirmed). A test covers every partition in the contract's table. Round 2 clamps this figure to each queue's maximum (see above).implementation-notes.mdused the invented field namearchiveIncludeLaunchFiles; it now names the real one,parameterSet.archiveFilter.includeLaunchFiles.Commits of round 1
e1ae47a9fix release, starvation and submit races;6b7a943fa truncating Tapis output download;82dd30d3copy log prefixes, leave unread logs owed;7252b047page result links;7cc56472refuse unsignable keys and cap launcher files;32ba7193keep the launcher open read-only and redact the hook token;79c49ee1validate the runtime image and report it in status;9406f6a1test every verification check;18795849test listing pagination through verification;ae69506epin the switch, compare and timeout claims;2be30c2eroute-driven full path and entry-point race;d24d0575always send memory in a submit, and type the failure words;7d7b30dcdeclare the shared compute words once;1287fdd9ADR, notes and help. Round 2:e2de0fcfleave a cancel for the sweep while a submit holds the lease (and holder-check the release);6db4bda3clamp a submit's memory to its queue's maximum;9003c6c3bound the links route body;49968d44order the tick by the bareexamined_atcolumn;0fdb4476record the round 1 money and concurrency rules in ADR 0118.What changed (original description, corrected)
0116,compute-lifecycle.ts(submitComputeJob: the one place the compute switch is read, a tag search before any submit, the digest of the exact launch specification bytes written before the call, no archive fields, the memory always sent;applyTapisJob: the one transition function; the terminal transition and its settlement as one batch;copyResultRecords; cancel;advanceComputeJob),compute-verify.ts,compute-advance.ts(runComputeAdvanceCron,sweepComputeCancellations, on the 30-minute tick's production block and in neither allowlist),compute-tokens.ts, gatedsettleStatementsandreleaseStatementsincompute-ledger.ts, the refusal wordresults_incomplete, the bindingCOMPUTE_RUNTIME_IMAGE.POST /webhooks/tapis/:jobId/:token(a hint: the body is ignored, the job is read back from Tapis), and the launcher'sPOST /compute/jobs/:id/bundle,.../outputsand.../outputs/complete, mounted ascomputeRoutesat/compute.mintResultLinksand the results-ready mail,POST /compute/jobs/:id/canceland.../links(owner only),POST /admin/compute/jobs/:id/canceland.../advance,nemar admin compute jobs cancel|advance <id>, the inventory pins.Gates (run on
0fdb4476)bun run typecheck: clean.bunx biome checkon the 8.tsfiles round 2 changed: 0 errors, 2 warnings (the existingnoExplicitAnyincompute-results-routes.test.ts). The known baseline errors indoi-orcid-discovery.tsandzenodo.tsare not touched.compute-queues.test.ts, which needsNEMAR_PROCESS_DIR; run against the C5 branch's checkout it passes (9 pass, 0 skip).admin-computeCLI suites and the ADR index: 622 pass, 0 fail across 9 files. The contract file's schema, golden vector and checksum were not touched in round 2 (nothing undershared/changed).bun run migrations:d1-check: not run in round 2, because the migration did not change; the round 1 run (118 migrations, 188 objects, 53 tables) stands.bun testand CI (the driver decides), and anything against a real tenant or a real R2.Mutation evidence
Each mutation was applied to one place, the test file named run on its own as its own argument, and the file restored (the script aborts unless the old text matches exactly once). The count is the number of tests that failed.
Round 1, the items the review asked for:
>=)truncatedis computed over all outputs, not the remainder/compute/jobs/prefix is allowedEXISTSguard of the settled stamp removed===computeEnabled(is called in the terminal commit (the scan, and the behaviour)REQUEST_READis 40 seconds;TICK_READis 40 secondsmemoryMB; a whole node uses the row's memory; a per-core share is halvedRound 2 (each run on its own test file as its own argument; the count is the failing tests):
compute's maximum set to the node's nominal 262,144driveCancelignores a live leaseORDER BY COALESCE(examined_at, '')restored in the live-row queryNot killed, stated plainly: the entry-point race in
compute-full-path.test.tsdid NOT kill the mutants that dropstate = <from>from the live transition or make the settlement gate always true (the interleaving they need is not one real entry points reach reliably, even with every statement taking a round trip). Those two mutants are killed bycompute-lifecycle.test.ts(1 failure) andcompute-lifecycle-money.test.ts(1 failure), which hand a writer a stale row. What the race adds is that the real entry points keep the invariants under overlap; its header says so.Original run (before round 1), kept:
state = <from>from the terminal UPDATEisPlatformFailurebundlesigns a caller-supplied pathDecisions made inside the issue's freedom
owneristapisConfig(env).username; a service-strategy configuration without it leaves jobscreated.compute_jobs.tapis_owneris not written (it stays the partner column).LAUNCH_DATASET_LIMITS: 1,000,000 files, 1 TiB), as the owner decided; adatasetLimitskey belongs to a later revision of the policy, because the policy schema lives in the frozen contract. They bound the dataset selection and are never the results limit.tapis_submit_failedwith the detailinvalid_specand its hold released. Recipe resolution beforecreateJobis phase A6; the builder stays a pure function of the recorded specification and keeps refusing a recipe-only one.complete, the verification and the quota use listings (1,000 objects a call) rather than one head each; the facts compared are the same (key and size).retention.resultsDays.failure_detailis never cleared and outputs named after a refusal are refused again with the recorded word (beforecomplete) orbad_state(after it).failure_detail. The per-output checksum counters that were computed and never read are deleted rather than recorded: nothing reads a count, and the size-only residual is stated below.advancealso submits acreatedjob (otherwise nothing submits in development), and says so when compute is off.invalid_spec(400), not the uniformjob_not_found, because the caller is the authenticated owner of a job that exists.Deviations from the issue and from round 1's own wording
failure_detail; migration 0115 already has it, so 0116 addsplatform_failureand the round 1 columns instead.assertValidS3Key(the A3 amendment forbids it for output keys).d24d0575holds two topics (the failure-word types and the always-sent memory), because the memory item arrived after the types were written and the two edit the same file.invalid_specsentence is now one, shared (it was two different sentences in the two routes).LAUNCHER_LOG_MAX_BYTES); the records keep the first 5 MiB. A launcher that legitimately writes more than 16 MiB of log would now failresults_too_large; nemar-process should truncate its own log well below that.results_quota_exceeded, the four files still presigned, nodeclared.json); when the platform's results budget is full, nothing is stored for a failing job either.compute-route-inventory.test.tsfirst appeared in the third original commit (a shell chain dropped it from the second).e2de0fcfholds two topics, the cancel-during-lease rule and the holder-checked release, because both change the same lease code incompute-lifecycle.tsand its tests.memory_mbabove its queue's maximum is now sent the maximum and not refused (the hold was priced at what it asked for, so it is charged for memory it is not given). Refusing such a request when the job is created, with a per-queue memory ceiling in the policy, belongs to a later phase.cancel_requestedwith the state stillcreated(it used to end the row at once); the sweep, which runs every 30 minutes, finishes it. A cancel that meets an expired or absent lease is unchanged.Unverified (nothing here was run against a real tenant or a real R2)
archiveFilter.includeLaunchFilesfrom the request, whatremoteResultInfoholds for a failed job, the webhook retry policy, the--gpusspelling, and whether the memory and the other request fields a job asks for are taken as written.QUEUE_MAX_MEMORY_MB): they come from the public Expanse user guide through the Tapis execution system and are marked unverified there; confirming them with the site is an owner item. Whether Tapis or Slurm enforces them as a refusal at submit is also unverified (the stand-in models no queue limits).UploadPart(the 5 GB per-file cap stands), R2's error on a locked delete, and a signed checksum header on a presigned PUT (deferred).redactSecretPaths.Open points for phase A7 (tenant reconcile)
createdrow can pass its deadline just before a tick, sosubmit_timeoutmay land up to a tick later than the policy says.UNSETTLED_TERMINAL_SQLandUNCOPIED_TERMINAL_SQL, still order by age with no rotation: a copy that fails on every attempt holds a slot for three days, and ten or more such rows delay newer copies.ORPHAN_ROWS_SQLorders byexamined_at, which is static for a terminal row (nothing stamps it), so the order of orphan retries does not rotate; andSET_ORPHAN_SQLrecords only one orphan per row.Design page sections that need the matching docs PR (the driver writes it)
uploadingstate is never written by A5), the failure-code paragraph, the refusal table (26 words), "Status updates", "Results" (listings,declared.json, links bounded at 1,000 with a cursor, the verification checks and their reason words, the 5 MiB log copy), "Cancellation" (a running job is charged what it used), and the memory every submit carries.tapisjob.outcopied after the terminal commit, retried three days).COMPUTE_RUNTIME_IMAGE(one digest-pinned reference, reported bystatus), read-only mode and the launcher, and the unverified items above.Answered in round 1
COMPUTE_RUNTIME_IMAGE, one digest-pinned reference (theuriof the image workflow'slaunch_image), validated when read.datasetLimitsis a later policy revision.refundJobandadjustPoolis a separate small PR; this PR does not touch A2 code.