Repository navigation
Description
Goal
A job row becomes a running, settled, verified Tapis job without anyone watching.
After this phase NEMAR submits to Tapis idempotently, follows the job by webhook hint and a 30-minute backstop, settles its charge provisionally, serves the launcher's job callbacks (bundle, outputs, complete) behind a per-job token, verifies the upload before finished, copies its files and logs into the records, mails the person a link to a page, and cancels on request.
Commit it in three slices (submit and advance, webhook and outputs, results and links) so review can follow. The revocation cascade and the ACCESS reporter are #2013.
Routing
- Readiness: ready
- Implementer: Sonnet
- Opus checkpoint: review before merge. Look at: webhook and job-callback trust (tokens, uniform refusals, read-back before any effect, the bundle route signing only the job's own key), state transitions under concurrent webhook, cron and cancel (conditional writes, idempotency keys, no double settle), that the transition and its settlement are one batch, and that no secret, token, presigned URL or job log line reaches a Worker log.
- Depends on: Phase A2: Allocation ledger and owner policy #2007, Phase A3: Job records and the results and records buckets #2008, Phase A4: Tapis client and stand-in #2009 ; Unblocks: Phase A8: Revocation cascade and ACCESS gateway attribution #2013, Phase A6: First-party pipeline dispatch #2011, Phase A7: Tenant reconcile, observer and reporting #2012
- Repository and base branch: nemarOrg/nemar-cli, epic branch
feature/issue-#2005-epic-compute-core
Scope
In: migration 0116_compute_lifecycle.sql; submit, advance, webhook, the three job callbacks (bundle, outputs, complete), result verification, the records copy, links, cancel, the admin jobs advance command.
Out: the revocation cascade and the ACCESS reporter (#2013), partner reservation and report routes and every user-facing read route (Epic D), the tenant-wide sweep and observer (#2012), pipeline dispatch (#2011), suspension of compute (Epic D).
Design references
Design sections 5 (life of a charge), 6 (what NEMAR does after a report), 7 (states, status updates, results, cancellation and revocation), 9 (attribution to ACCESS). Templates: runRepullAdvanceCron in services/upstream-repull-advance.ts; routes/callbacks/repull-state.ts with bounded-json.ts and services/github/callback-tokens.ts (domain-tagged HMAC under PRESCREEN_CALLBACK_SECRET); mailReleaseStatements in services/ticket-assignment.ts; sendUploadAccessGrantedEmail in services/email.ts.
Changes
- Migration
0116_compute_lifecycle.sql:ALTER TABLE compute_jobs ADD COLUMN results_verified_at TEXT, andoutputs_completed_at TEXT,results_bytes INTEGER(declared bytes, for the quota),result_records_at TEXT,failure_detail TEXT(fixed-word CHECK as in 0115; set only with a refusal word from Phase A1: Compute contract and ADR 0118 #2006'sRESULT_REFUSAL_DETAILS). services/compute-lifecycle.ts:submitComputeJob(env, jobId)refusescompute_disabled(the one place the switch is read), requiresrecords_written_at, first callssearchJobsByTag("nemar_job:<id>")and binds an existing job instead of submitting, else submits with that tag, no archive fields (Tapis keeps its default archive on the execution system), the launch specification inNEMAR_LAUNCH_SPECcarryingjob_token(HMAC as the webhook token, domain tagcompute-job, same nonce, so valid until a day after the job is terminal) and, for a bundle,bundle {sha256, size}with no URL, the recipe or bundle environment fromLAUNCHER_ENV, and aJOB_NEW_STATUSsubscription to<API_BASE_URL>/webhooks/tapis/<jobId>/<token>(token: HMAC under domain tagcompute-webhookover the job id andwebhook_nonce, no clock inside it); one conditional UPDATE bindstapis_uuidand movescreatedtosubmitted. A 4xx rejection fails the jobtapis_submit_failedand releases the hold; an unavailable Tapis leaves itcreatedfor the next tick; acreatedrow older than the policy deadline with no Tapis job failssubmit_timeout.applyTapisJob(env, job, tapisRecord)is the one transition function for webhook, cron and cancel: compute the target withstateFromTapisStatus, checkcanTransitionCompute, write withWHERE id = ? AND state = <from>; a self-edge refreshestapis_status,tapis_synced_atand times only. On TapisFINISHEDit runsverifyResultsfirst (outputs_completed_atset;launcher/manifest.jsonandlauncher/provenance.jsonin the results bucket and valid against Phase A1: Compute contract and ADR 0118 #2006's launch contract;spec_digestequal to the job's; every output indeclared.jsonpresent with the exact size by binding HEAD; sha256 compared only where R2 returns it, else recorded as unverified) and endsfinishedorfailedwithresult_verification_failed; aFINISHEDjob whose launcher never completed failsresult_upload_failed. On terminal it takes the failure code fromlauncher/result.jsonin the results bucket overfailureCodeFromTapisCondition, setsretention_untilfrom policy, and settles with Phase A2: Allocation ledger and owner policy #2007'ssettleProvisionalusingsuMilliForover the Tapis record's resources andremoteStartedtoremoteEnded(a job that never started is released in full; a platform failure refunds, by Phase A1: Compute contract and ADR 0118 #2006'sisPlatformFailure(code, detail):result_upload_failedrefunds, except whenfailure_detailholds a refusal word, which is user-caused and is charged). The state UPDATE and the ledger insert are ONE batch guarded on the new state; a retry repairs a terminal row whosesettled_provisional_atis NULL. Leave a single named hook where the record first shows a Slurm id, which Phase A8: Revocation cascade and ACCESS gateway attribution #2013 fills.copyResultRecords(env, job), after the terminal commit: copiesresult.json,provenance.json, the manifest (asresult-manifest.json) andlauncher.logfromjobs/<id>/launcher/through the bindings intorecords/<id>/andlogs/<id>/, writeslogs/<id>/tapisjob.outfrom Phase A4: Tapis client and stand-in #2009'sdownloadOutput(capped at 5 MiB), then setsresult_records_at; the tick retries rows with it NULL, never overwriting.services/compute-advance.ts:runComputeAdvanceCron(env)(exact production only; no switch read, so live jobs are never stranded; a database read of live rows first so an unconfigured Worker with no jobs does nothing), 10 rows per tick ordered bytapis_synced_atfor rotation, per-row try and catch recording only a fixed word and the error class, one log line per tick; it submitscreatedrows, retriescopyResultRecords, reads each live job back, marks a live rowunreportedwhen its last good read is older than 24 hours, and clearswebhook_nonceone day after a job is terminal.sweepComputeCancellations(env)cancels at Tapis every live row withcancel_requested_atset, retried each tick. Wire both into the 30-minute tick's production-only block ofscheduled()inbackend/src/index.ts, each asctx.waitUntil(name(env)...), none inDEV_CRON_ALLOWLIST, each also self-fenced withisExactProduction; add them tocron-sweep-wiring.test.tsastick-prod-only.routes/callbacks/tapis.tsregistered inroutes/webhooks/index.ts:POST /tapis/:jobId/:token. Bounded body (16 KiB) throughreadBoundedJsonObject; token verified in constant time and the job'swebhook_noncemust be non-null; every refusal returns the same status and body; on success the body is ignored (a hint), the job is read back from Tapis,applyTapisJobruns, and the answer is{ ok: true }whether or not anything changed. Pin it intest/webhooks-route-inventory.unit.test.ts.routes/callbacks/compute-job-callbacks.ts, beside the webhook callbacks, no session, all three routes in this one file:POST /compute/jobs/:id/bundle,.../outputsand.../outputs/complete. Tokenjob_tokenin headerX-Compute-Job-Token, never the URL, checked in constant time against the nonce; uniform refusals, 1 MiB bodies.bundleanswers{ url, expires_at }, a 10-minute presigned GET from Phase A3: Job records and the results and records buckets #2008'spresignBundleReadof that job's ownrecords/<id>/submitted/bundle.tar.gzand nothing else (the one presigned read of a record besides the owner's lookup; queue time does not matter); a job without a bundle answers the uniform refusal.outputs(job not terminal; a terminal job answers its stored outcome) takes{ outputs: [{ path, size, sha256 }], launcher: [{ name, size }] }(Phase A1: Compute contract and ADR 0118 #2006's schema), refuses bad paths asassertValidS3Keydoes, too many files (too_many_outputs) and a file or total overRESULT_MAX_FILE_BYTESormaxJobBytes(results_too_large), then claims the bytes in ONE conditional UPDATE ofresults_byteswhose WHERE holds both the person's share (the account's other unexpired totals withinmaxStoredBytesPerPerson) and the platform total (all unexpired totals withinmaxStoredBytesTotal), bothresults_quota_exceeded; no account, no person share but the platform total still applies. It writesdeclared.jsonthrough the binding and answers{ uploads, expires_at }: PUT URLs valid 1 hour forjobs/<id>/outputs/<path>and the four launcher files; a replay re-presigns. A refusal (too_many_outputs,results_too_large,results_quota_exceeded) records itself asfailure_detail(conditional UPDATE), still presigns the launcher files, and the job endsresult_upload_failedwith no refund.completeHEADs every declared object (missing or short is 409results_incomplete, retryable) and setsoutputs_completed_atonce. Pin all three incompute-route-inventory.test.ts.services/compute-results.ts:mintResultLinks(7-day presigned GETs through Phase A3: Job records and the results and records buckets #2008's signer of the declared outputs, count bounded; bearer links, never logged),sendComputeResultsReadyEmail(links to<APP_BASE_URL>/compute/jobs/<id>, never to a file, in try and catch, skipped for service accounts and pipeline jobs).routes/compute.tsexportingcomputeRoutes, mountedapi.route("/compute", computeRoutes),authMiddleware:POST /compute/jobs/:id/cancelandPOST /compute/jobs/:id/links(job owner only; renew answersresults_expiredonce a binding HEAD finds the objects gone);POST /admin/compute/jobs/:id/cancelandPOST /admin/compute/jobs/:id/advance(one read-back andapplyTapisJob, the way a job advances in development where no compute cron runs); CLInemar admin compute jobs cancel <id>andjobs advance <id>insrc/commands/admin-compute-jobs.ts(which Phase A7: Tenant reconcile, observer and reporting #2012 extends). Write abackend/test/compute-route-inventory.test.tsfor the new router.
Tests (write these first)
backend/test/compute-lifecycle.test.ts: full path against the Tapis stand-in, the S3-API stand-in over Miniflare R2 and real D1, the test playing the launcher through the outputs routes: hold, submit (no archive fields),advancethrough every status, outputs uploaded and completed, finished with a verified manifest, charge settled, records copied, a platform failure refunded. A submit retried after a lost response finds the job by tag and submits once. Mutation: skip the tag search; the test must see two submits.- Concurrency: webhook, cron tick and cancel applied together leave one final state and one charge entry; replaying each changes nothing. Mutation: drop the
state = <from>term. - Verification: a missing output, a size mismatch and a
spec_digestmismatch each endfailedwithresult_verification_failed; aFINISHEDjob whose launcher never calledcompleteendsresult_upload_failed. backend/test/compute-webhook.test.ts: wrong token, other job's token, cleared nonce, oversize and non-JSON bodies all return identical status and body; a staleRUNNINGhint afterFINISHEDchanges nothing.- Cron wiring and self-fence: the tick calls are inside the production-only block; each function does nothing outside production when called directly.
backend/test/compute-job-callbacks.test.ts: a wrong token, another job's token, a cleared nonce, no header and a token in the URL refuse identically on all three routes;bundlesigns only that job'sbundle.tar.gzfor 10 minutes and never a key taken from the request (mutation: sign a caller-supplied path); too many files, an over-cap file or job, an over-quota person and an over-total platform each refuse with their code, presign launcher files only and setfailure_detail; two jobs racing for the last bytes of a person or of the platform, one wins (mutation: read the quota in a separate query before the UPDATE);completewith a missing or short object answersresults_incomplete; replays change nothing; no token or presigned URL reaches a log.copyResultRecordswrites the records andtapisjob.out, completes after a mid-copy failure and never overwrites. Settlement: aresult_upload_failedjob refunds its charge, but one with a refusalfailure_detailis charged and not refunded (mutation: ignore the detail).
Acceptance criteria
- No job is submitted twice; no job is settled twice; no terminal job is left unsettled.
- Tapis receives no storage credential or archive system; every terminal job has its launcher files and logs in the records.
- Logs carry job ids and fixed words only; no token, name, path or job output.
- Wiring and inventory tests are updated and pass.
Gates
bun test backend/test/compute-lifecycle.test.ts backend/test/compute-job-callbacks.test.ts backend/test/compute-webhook.test.ts backend/test/compute-route-inventory.test.ts backend/test/cron-sweep-wiring.test.ts backend/test/cron-dev-safety.test.ts test/webhooks-route-inventory.unit.test.tsbun run migrations:d1-check,bun run typecheck,bunx biome check src shared backend/src,bun test
Rules that bite here
- Webhooks are hints; read back first. A token in a URL reaches logs, so it expires with the nonce.
- New crons are production-only and sweep-named exports need wiring entries.
- Nothing the job writes is trusted for accounting; mail links to a page.
- No output URL is issued before the size and quota checks pass.
Escalate to the owner if
- A person's results should be mailed from a different address or page than the one assumed.
- A real job exceeds the 5 GB per-file cap; the owner picks a longer rule or multipart.
When merged
Update design section 7 (state words as shipped), list the new crons in the systems inventory runbook, and record as unverified: presigned multipart UploadPart on R2 (the 5 GB cap stands) and R2's error on a locked delete.
Activity
[-]Phase A5: Job lifecycle, webhooks, settlement and ACCESS attribution[/-][+]Phase A5: Job lifecycle, webhooks, settlement and results[/+]neuromechanist commentedon Nov 4, 2026
Driver amendment, 2026-11-04, from the phase A1 review (PR #2030) and the Opus advisor. This comment is part of the phase brief; where it differs from the body above, this comment wins.
spec_digest(job row, set by A3) is the SHA-256 ofrecords/<id>/spec.json.launch_spec_digest(new, this phase) is the SHA-256 hex of the exact bytes of theNEMAR_LAUNCH_SPECvalue the Worker put in the Tapis submit request; the launcher hashes the raw environment bytes before parsing and records it aslaunch_spec_digestinlauncher/provenance.json(the provenance key is renamed fromspec_digestin the A1 contract). Wherever this issue saysspec_digestof provenance, readlaunch_spec_digest.compute_jobs.launch_spec_digest(NULL until submit; CHECK 64 lowercase hex characters).launch_spec_digestin a conditional UPDATE on acreatedrow BEFORE calling Tapis. On a retry, if the tag search finds the job the stored value stays; if it finds nothing, the digest of the rebuilt text overwrites it before the new submit (limits can change with the policy).verifyResultscompares:provenance.launch_spec_digestwith the job's;job_idinresult.json,manifest.jsonandprovenance.jsonwith the job's id;provenance.bundle_digestwith the specification'sbundle.sha256(null when there is no bundle);provenance.image.digestwith the job's image digest. Any mismatch ends the jobfailedwithresult_verification_failed. Test 3 reads "alaunch_spec_digestmismatch".declared.json(for examplejobs/<id>/declared.json), written through the binding outside the prefixes the launcher can presign.results_incompletetoshared/compute-state.ts(the list andCOMPUTE_REFUSAL_STATUS) rather than declaring it elsewhere.job_tokensit in a Tapis environment variable that the job record exposes, so a person who owns the Tapis job could read the token back and PUT a forgedlauncher/result.json(for exampledataset_fetch_failed, which refunds). Options: submit NEMAR-run jobs under a NEMAR-owned Tapis owner, cross-checkresult.json'sexit_numberagainst the exit code Tapis reports fromtapisjob.exitcode, or both. Choosing the Tapis owner is the repository owner's decision: escalate it, do not decide it in the phase.neuromechanist commentedon Nov 4, 2026
Driver amendment, 2026-11-04, from the review and Opus checkpoint of the launcher (nemarOrg/nemar-process#7). This comment is part of the phase brief; where it differs from the body above, this comment wins. The launcher-side facts it relies on are in nemarOrg/nemar-process#7 and in the nemar-cli follow-up phase A1b (launch-specification and launcher-detail contract).
Lifecycle and verification:
dataTagForVersion(A1b): each datasetversionis the data-plane tag (latestorvN.N.N); a null result refuses the job at submit, never at the launcher.image.sifis the digest-named basename and the Tapis application setsNEMAR_SIF_ROOTas a fixed variable.launcher/result.jsonand store both (the detail column is checked by shape).isPlatformFailure(code, detail)(extended in A1b with the declared launcher details) decides the refund: NEMAR, node and runtime faults are refunded even underruntime_error; submitter-caused details are charged even undercode_fetch_failedanddataset_fetch_failed.job_id,launch_spec_digestand exit-number checks onresult.jsonfor FAILED jobs too (that is where the failure code comes from); a FAILED job whoseresult.jsoncode is null takes Tapis's reported condition. Cross-checkresult.json.exit_numberagainst the exit code Tapis reports.tapisjob.out(the entry's stdout and stderr) is untrusted: user code can print lines that look like the launcher's. Never parse it; copy it as a log only.complete(a token holder could otherwise overwrite objects with same-size content before verification).failedhandling when the launcher exits before writingresult.json(it should not happen any more, but a SIGKILL still can).neuromechanist commentedon Nov 4, 2026
Driver amendment, 2026-11-04, from the review and Opus checkpoint of phase A2 (the allocation ledger, #2032). This comment is part of the phase brief; where it differs from the body above, this comment wins.
Settlement, from the ledger as built in A2:
hold_closed,already_finalandalready_refundedreturned on a retry mean the step already happened: treat them as success, not as errors.would_go_negativeon a final settlement can never clear later: treat it as terminal and flag the job (mismatch).overrunflag on the job must also be set when the final figure exceeds the hold.refundJobonly (it is once per job); an admin's job refund must never go through a pool-level adjust. After a refund,settleFinalrefuses (A2 adds the coderefunded): a late Expanse figure for a refunded job is an observation, not a new charge; record it as amismatchinstead.neuromechanist commentedon Nov 4, 2026
Owner decision, 2026-11-04 (recorded by the driver). This comment is part of the phase brief; where it differs from the body or an earlier comment above, this comment wins.
Three decisions from the repository owner settle the A5 questions:
result.jsonexit-number cross-check against Tapis's exit code as defence in depth, since it is cheap).refundJob.isPlatformFailure(code, detail)stays as an INFORMATION flag: setplatform_failureon the job row and surface it in the admin reports so an admin can compensate a NEMAR-caused failure by a manual grant. Remove "a platform failure refunds" everywhere in this phase's tests and docs; amend ADR 0118 with the decision (it supersedes the refund wording of decision 13: the detail words and the classification remain, as an attribution, not a billing rule).peoplebudget records consumption only (option A). Only the final settlement figure and the owner's own platform adjustments move it; nothing a person or an admin does to a person's pool gives budget back (the interim owner-only rule for account charge corrections stays; make sure no A5 path credits the budget).Model in one line: each approved person gets a grant (the owner's default per-person grant, set in the policy), spends it, and when it is used up an admin grants more by hand (a portal to buy more comes later); the budget is the overall cap on everything people can spend.
neuromechanist commentedon Nov 4, 2026
Driver amendment, 2026-11-04, from the review of phase A4 (#2038). This comment is part of the phase brief; where it differs from the body above, this comment wins.
ownerof every job is the NEMAR service identity read from configuration: never a constant in code and never a person. The brief for the job-submission code must name where it comes from (the same configured identity the Tapis client credential strategy uses; under the password strategy the client refuses an owner that differs from the configured account).unavailableandinvalid_responsefromsubmitJob,cancelJobandsubscribeWebhookmean the effect may have happened (a 2xx answer that fails its schema means the job exists). Search by tag before any re-submit; never re-submit blind. Cancel is idempotent in effect but the client does not retry it.maxAttempts: 1and a shorttimeoutMs: the 15 second ceiling is per request, so defaults allow about 46 seconds for a read and about 60 seconds for a submit whose first send is refused with 401.getJobdropssubscriptionsand there is no list call): advancing a job from a webhook must be idempotent.listType=ALL_JOBSlists the caller's own jobs plus jobs shared with the caller; the safety of a tag search before re-submit assumes a single submitting identity, which the 2026-11-04 owner decision gives.archiveFilter.includeLaunchFiles: falseon every job and refuses output paths namedtapisjob.envortapisjob.sh; the Tapis application definition (phase C5) still sets its own archive setting as the second layer.limits.max_total_bytesbounds the dataset selection, not the outputs; the Worker's per-job results limit is separate. State that in the specification you write, and do not reuse one number for both.neuromechanist commentedon Nov 5, 2026
Merged into the epic branch by #2041 (squash). Round 1 (Opus checkpoint plus two Sonnet reviewers, 21 items) and round 2 (Opus delta; two Important findings fixed: the submit memory clamp to the queue maximum and the cancel-during-submit orphan) converged. Targeted suites pass on the final head; every guard mutated. The migration 0116 is unreleased. Owner items: confirm the queue memory maxima and the rate table's per-node memory with the site (figures come from the public Expanse guide via nemar-process C5 and are unverified); COMPUTE_RUNTIME_IMAGE (one digest-pinned reference) is set by the owner after the first image publish. Open points for A7 (tenant reconcile) are in the PR body. The A2 follow-up (the people budget consumption-only) is a separate PR.