Skip to content

Phase A5: Job lifecycle, webhooks, settlement and results #2010

Closed

Description

@neuromechanist

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

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, and outputs_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's RESULT_REFUSAL_DETAILS).
  • services/compute-lifecycle.ts: submitComputeJob(env, jobId) refuses compute_disabled (the one place the switch is read), requires records_written_at, first calls searchJobsByTag("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 in NEMAR_LAUNCH_SPEC carrying job_token (HMAC as the webhook token, domain tag compute-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 from LAUNCHER_ENV, and a JOB_NEW_STATUS subscription to <API_BASE_URL>/webhooks/tapis/<jobId>/<token> (token: HMAC under domain tag compute-webhook over the job id and webhook_nonce, no clock inside it); one conditional UPDATE binds tapis_uuid and moves created to submitted. A 4xx rejection fails the job tapis_submit_failed and releases the hold; an unavailable Tapis leaves it created for the next tick; a created row older than the policy deadline with no Tapis job fails submit_timeout. applyTapisJob(env, job, tapisRecord) is the one transition function for webhook, cron and cancel: compute the target with stateFromTapisStatus, check canTransitionCompute, write with WHERE id = ? AND state = <from>; a self-edge refreshes tapis_status, tapis_synced_at and times only. On Tapis FINISHED it runs verifyResults first (outputs_completed_at set; launcher/manifest.json and launcher/provenance.json in the results bucket and valid against Phase A1: Compute contract and ADR 0118 #2006's launch contract; spec_digest equal to the job's; every output in declared.json present with the exact size by binding HEAD; sha256 compared only where R2 returns it, else recorded as unverified) and ends finished or failed with result_verification_failed; a FINISHED job whose launcher never completed fails result_upload_failed. On terminal it takes the failure code from launcher/result.json in the results bucket over failureCodeFromTapisCondition, sets retention_until from policy, and settles with Phase A2: Allocation ledger and owner policy #2007's settleProvisional using suMilliFor over the Tapis record's resources and remoteStarted to remoteEnded (a job that never started is released in full; a platform failure refunds, by Phase A1: Compute contract and ADR 0118 #2006's isPlatformFailure(code, detail): result_upload_failed refunds, except when failure_detail holds 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 whose settled_provisional_at is 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: copies result.json, provenance.json, the manifest (as result-manifest.json) and launcher.log from jobs/<id>/launcher/ through the bindings into records/<id>/ and logs/<id>/, writes logs/<id>/tapisjob.out from Phase A4: Tapis client and stand-in #2009's downloadOutput (capped at 5 MiB), then sets result_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 by tapis_synced_at for rotation, per-row try and catch recording only a fixed word and the error class, one log line per tick; it submits created rows, retries copyResultRecords, reads each live job back, marks a live row unreported when its last good read is older than 24 hours, and clears webhook_nonce one day after a job is terminal. sweepComputeCancellations(env) cancels at Tapis every live row with cancel_requested_at set, retried each tick. Wire both into the 30-minute tick's production-only block of scheduled() in backend/src/index.ts, each as ctx.waitUntil(name(env)...), none in DEV_CRON_ALLOWLIST, each also self-fenced with isExactProduction; add them to cron-sweep-wiring.test.ts as tick-prod-only.
  • routes/callbacks/tapis.ts registered in routes/webhooks/index.ts: POST /tapis/:jobId/:token. Bounded body (16 KiB) through readBoundedJsonObject; token verified in constant time and the job's webhook_nonce must 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, applyTapisJob runs, and the answer is { ok: true } whether or not anything changed. Pin it in test/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, .../outputs and .../outputs/complete. Token job_token in header X-Compute-Job-Token, never the URL, checked in constant time against the nonce; uniform refusals, 1 MiB bodies. bundle answers { url, expires_at }, a 10-minute presigned GET from Phase A3: Job records and the results and records buckets #2008's presignBundleRead of that job's own records/<id>/submitted/bundle.tar.gz and 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 as assertValidS3Key does, too many files (too_many_outputs) and a file or total over RESULT_MAX_FILE_BYTES or maxJobBytes (results_too_large), then claims the bytes in ONE conditional UPDATE of results_bytes whose WHERE holds both the person's share (the account's other unexpired totals within maxStoredBytesPerPerson) and the platform total (all unexpired totals within maxStoredBytesTotal), both results_quota_exceeded; no account, no person share but the platform total still applies. It writes declared.json through the binding and answers { uploads, expires_at }: PUT URLs valid 1 hour for jobs/<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 as failure_detail (conditional UPDATE), still presigns the launcher files, and the job ends result_upload_failed with no refund. complete HEADs every declared object (missing or short is 409 results_incomplete, retryable) and sets outputs_completed_at once. Pin all three in compute-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.ts exporting computeRoutes, mounted api.route("/compute", computeRoutes), authMiddleware: POST /compute/jobs/:id/cancel and POST /compute/jobs/:id/links (job owner only; renew answers results_expired once a binding HEAD finds the objects gone); POST /admin/compute/jobs/:id/cancel and POST /admin/compute/jobs/:id/advance (one read-back and applyTapisJob, the way a job advances in development where no compute cron runs); CLI nemar admin compute jobs cancel <id> and jobs advance <id> in src/commands/admin-compute-jobs.ts (which Phase A7: Tenant reconcile, observer and reporting #2012 extends). Write a backend/test/compute-route-inventory.test.ts for the new router.

Tests (write these first)

  1. 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), advance through 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.
  2. 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.
  3. Verification: a missing output, a size mismatch and a spec_digest mismatch each end failed with result_verification_failed; a FINISHED job whose launcher never called complete ends result_upload_failed.
  4. 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 stale RUNNING hint after FINISHED changes nothing.
  5. Cron wiring and self-fence: the tick calls are inside the production-only block; each function does nothing outside production when called directly.
  6. 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; bundle signs only that job's bundle.tar.gz for 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 set failure_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); complete with a missing or short object answers results_incomplete; replays change nothing; no token or presigned URL reaches a log.
  7. copyResultRecords writes the records and tapisjob.out, completes after a mid-copy failure and never overwrites. Settlement: a result_upload_failed job refunds its charge, but one with a refusal failure_detail is 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.ts
  • bun 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

  1. added
    feature
    on Nov 4, 2026
  2. changed the title [-]Phase A5: Job lifecycle, webhooks, settlement and ACCESS attribution[/-] [+]Phase A5: Job lifecycle, webhooks, settlement and results[/+] on Nov 4, 2026
  3. neuromechanist commented on Nov 4, 2026

    @neuromechanist
    ContributorAuthor

    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.

    • Two digests. spec_digest (job row, set by A3) is the SHA-256 of records/<id>/spec.json. launch_spec_digest (new, this phase) is the SHA-256 hex of the exact bytes of the NEMAR_LAUNCH_SPEC value the Worker put in the Tapis submit request; the launcher hashes the raw environment bytes before parsing and records it as launch_spec_digest in launcher/provenance.json (the provenance key is renamed from spec_digest in the A1 contract). Wherever this issue says spec_digest of provenance, read launch_spec_digest.
    • Migration 0116 adds compute_jobs.launch_spec_digest (NULL until submit; CHECK 64 lowercase hex characters).
    • Submit order: write launch_spec_digest in a conditional UPDATE on a created row 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).
    • verifyResults compares: provenance.launch_spec_digest with the job's; job_id in result.json, manifest.json and provenance.json with the job's id; provenance.bundle_digest with the specification's bundle.sha256 (null when there is no bundle); provenance.image.digest with the job's image digest. Any mismatch ends the job failed with result_verification_failed. Test 3 reads "a launch_spec_digest mismatch".
    • The lifecycle test's launcher stand-in must hash the value the Tapis stand-in received, never copy the Worker's digest, or the check proves nothing.
    • Name a key for declared.json (for example jobs/<id>/declared.json), written through the binding outside the prefixes the launcher can presign.
    • Add the refusal word results_incomplete to shared/compute-state.ts (the list and COMPUTE_REFUSAL_STATUS) rather than declaring it elsewhere.
    • Opus checkpoint, add this question: the launch specification and job_token sit 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 forged launcher/result.json (for example dataset_fetch_failed, which refunds). Options: submit NEMAR-run jobs under a NEMAR-owned Tapis owner, cross-check result.json's exit_number against the exit code Tapis reports from tapisjob.exitcode, or both. Choosing the Tapis owner is the repository owner's decision: escalate it, do not decide it in the phase.
  4. neuromechanist commented on Nov 4, 2026

    @neuromechanist
    ContributorAuthor

    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:

    • Build the launch specification with dataTagForVersion (A1b): each dataset version is the data-plane tag (latest or vN.N.N); a null result refuses the job at submit, never at the launcher. image.sif is the digest-named basename and the Tapis application sets NEMAR_SIF_ROOT as a fixed variable.
    • Take the failure code AND the detail from launcher/result.json and 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 under runtime_error; submitter-caused details are charged even under code_fetch_failed and dataset_fetch_failed.
    • Run the job_id, launch_spec_digest and exit-number checks on result.json for FAILED jobs too (that is where the failure code comes from); a FAILED job whose result.json code is null takes Tapis's reported condition. Cross-check result.json.exit_number against 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.
    • Do not re-issue upload addresses after complete (a token holder could otherwise overwrite objects with same-size content before verification).
    • Opus checkpoint, added questions: the launcher now refuses to run when its output directory is not empty and verifies a PID namespace before running user code; confirm A5's failed handling when the launcher exits before writing result.json (it should not happen any more, but a SIGKILL still can).
  5. neuromechanist commented on Nov 4, 2026

    @neuromechanist
    ContributorAuthor

    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_final and already_refunded returned on a retry mean the step already happened: treat them as success, not as errors.
    • would_go_negative on a final settlement can never clear later: treat it as terminal and flag the job (mismatch).
    • A final figure ABOVE the hold is written as an adjust, not as an overrun entry: the overrun flag on the job must also be set when the final figure exceeds the hold.
    • Refund a platform failure through refundJob only (it is once per job); an admin's job refund must never go through a pool-level adjust. After a refund, settleFinal refuses (A2 adds the code refunded): a late Expanse figure for a refunded job is an observation, not a new charge; record it as a mismatch instead.
    • The final-settlement step always records the key, even when the final figure equals the provisional charge (A2 allows a zero-delta job-scoped adjust for exactly that), so a retry can tell the step is done.
  6. neuromechanist commented on Nov 4, 2026

    @neuromechanist
    ContributorAuthor

    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:

    1. NEMAR owns every Tapis job. There is a single NEMAR tenant and NEMAR handles everything: the Tapis owner of EVERY job (CLI, web, partner, pipeline) is a NEMAR service identity (a parameter of the Tapis client, set from configuration, never a person); a person's account exists only in NEMAR's job row (and tags). No person has Tapis access, so nobody but NEMAR and the site's operators can read a Tapis job record: the token-exposure question is closed by ownership (keep the result.json exit-number cross-check against Tapis's exit code as defence in depth, since it is cheap).
    2. No automatic refunds. Consumed SU stay consumed, whoever caused the failure. Settlement charges what the Tapis record (then Expanse's accounting) says was used; a job that never started on the scheduler is RELEASED in full (that is not a refund: nothing was consumed). A5 never calls refundJob. isPlatformFailure(code, detail) stays as an INFORMATION flag: set platform_failure on 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).
    3. The people budget 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.
  7. neuromechanist commented on Nov 4, 2026

    @neuromechanist
    ContributorAuthor

    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.

    • The Tapis owner of 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).
    • Outcome unknown: unavailable and invalid_response from submitJob, cancelJob and subscribeWebhook mean 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.
    • Read-through calls (a status poll made on behalf of a request) pass maxAttempts: 1 and a short timeoutMs: 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.
    • A webhook subscription cannot be deduplicated (getJob drops subscriptions and there is no list call): advancing a job from a webhook must be idempotent.
    • listType=ALL_JOBS lists 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.
    • The launch specification (with the per-job token) travels only in the environment variable. After the A4 fixes the client sets archiveFilter.includeLaunchFiles: false on every job and refuses output paths named tapisjob.env or tapisjob.sh; the Tapis application definition (phase C5) still sets its own archive setting as the second layer.
    • From the launcher's review (nemar-process#7): limits.max_total_bytes bounds 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.
  8. neuromechanist commented on Nov 5, 2026

    @neuromechanist
    ContributorAuthor

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurehpc

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions