Skip to content

Phase A3: Job records and the results and records buckets - #2035

Merged
neuromechanist merged 12 commits into
feature/issue-2005-epic-compute-corefrom
feature/issue-2008-phase3-job-records-and-the-results-and
Nov 4, 2026
Merged

neuromechanist merged 12 commits into
feature/issue-2005-epic-compute-corefrom
feature/issue-2008-phase3-job-records-and-the-results-and

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Phase A3 of the compute program (#2008), part of epic #2005. It adds the job index, the two private R2 buckets and the one function that makes a job and its hold. Nothing submits to Tapis yet.

What changed

  • Migration 0115_compute_jobs.sql: compute_jobs (one index row per job, account id and fixed words only, no foreign key, no identity column; every state, source, kind and pool is an enumerated CHECK that a test compares with shared/compute-state.ts; failure_code, failure_detail, cancel_reason and partition are checked by shape so a later epic's word needs no rebuild; state = 'failed' if and only if a failure code is set; a partial unique index on (account_id, idempotency_key), a partial index over the live states and one on (account_id, created_at)) and compute_gateway_users (the ACCESS pseudonym, gw_ and 20 base32 characters, never rotated and never removed). launch_spec_digest is not added: that is phase A5's migration 0116.
  • backend/src/services/compute-jobs.ts: createJob makes the job and its hold in ONE batch (the ledger's hold with the person's live-job limit as a guard read inside the same statement, then the pseudonym's INSERT OR IGNORE, then the job INSERT, the last two gated on EXISTS of the hold row), so a refused hold leaves no job, no ledger entry, no pseudonym and no object in either bucket. It validates before any hold exists, returns the existing job for a replayed (account, key) and refuses the same key for another request, and writes the records after the commit.
  • backend/src/services/compute-records.ts: the records layout (records/<id>/identity.json, spec.json, submitted/..., bundle-manifest.json, result-manifest.json, provenance.json, result.json; logs/<id>/...; incoming/<id>/...), writeIdentitySnapshot, writeSpec, presignIncomingUploads, finalizeBundle, finalizeSubmittedFiles, presignBundleRead and readRecordObject (owner-only, reasoned, audited before any byte is read). spec_digest is the SHA-256 of the exact bytes of records/<id>/spec.json, made once before the INSERT and written after the commit.
  • backend/src/services/compute-s3.ts: the aws4fetch signer against R2's S3 interface (path style, region auto): computeS3, presignPut, presignGet, copyObject. The endpoint is globalThis.NEMAR_COMPUTE_S3_URL when set, else the COMPUTE_R2_S3_ENDPOINT secret; S3_ENDPOINT_URL is never read. A key is encoded segment by segment and judged by the contract's COMPUTE_PATH_RE, not by assertValidS3Key, so a..b.csv and 100%.txt round-trip. An expiry above seven days is refused.
  • backend/wrangler-sccn.toml and types/bindings.ts: COMPUTE_RECORDS and COMPUTE_RESULTS in [[r2_buckets]] and [[env.dev.r2_buckets]] with the four existing bucket names, both *_BUCKET_NAME variables in [vars] and [env.dev.vars], and the three Worker secret names in the comment block (no value, no endpoint). The two switches are not added.
  • compute-ledger.ts: the part of placeHold that names why a hold was refused is now the exported holdRefusalReason, so createJob can ask after its own batch refused without taking a second hold. No behaviour change.
  • Tests: the four files of the issue plus compute-s3.test.ts, a verifying S3 stand-in over the same Miniflare R2 buckets (helpers/compute-s3-standin.ts), a harness, seeding helpers and a D1 wrapper whose statements take a round trip on both sides. A test of A2's migration that listed every compute_% trigger is scoped to its own three tables. ADR 0118 gets an amendment and implementation-notes.md a section 8.

Gates

  • bun test backend/test/compute-jobs-migration.test.ts backend/test/compute-jobs.test.ts backend/test/compute-records.test.ts backend/test/compute-buckets-config.test.ts: 272 pass, 0 fail (4 files, 2533 expect calls); with compute-s3.test.ts 325 pass, 0 fail
  • bun run migrations:d1-check: All migrations applied on real D1. Catalog matches bun:sqlite (186 objects, 53 tables). OK. (117 migrations, 0115 included, run once after the round 1 migration edits)
  • bun run typecheck: passes
  • bunx biome check src shared backend/src: only the 5 known baseline errors in untouched zenodo.ts and doi-orcid-discovery.ts, none in a changed file
  • full bun test: not run, by the owner's rule that it runs only at epic to dev. Targeted neighbours instead (21 files, 1262 tests, 0 failures): the six A2 ledger and policy suites, the suites that read wrangler-sccn.toml (S3 override fence, Neurobagel scan, switch pins, email and retention vars), migrations.test.ts, datasets-column-budget.test.ts, the compute contract and state tests and the A3 files.

Every test was proved to fail by mutating the line it guards, one perturbation at a time, including the three in the issue: removing the EXISTS term of the job INSERT (the refused-hold cases then see a job), writing the records before the batch (they then see an object, and the ordering test sees no committed job), and taking the bundle key from the caller. The others: the live-job limit read before the batch instead of inside the hold's statement (caught only once the race tests took a round trip on both sides of each statement), an ungated pseudonym insert, a replay that ignores the digest, a replay that does not finish the records, the audit row after the bucket was touched, an audit failure that does not refuse, a reason minimum of 3, an audit row not gated on the owner role, no archive size check, no decoding layer in the traversal check, one layer only, the partner cap, finalizeBundle copying before the job is read, copying again on a replay, overwriting an existing destination, no key encoding in the signer, an assertValidS3Key-like predicate, the checksum header not signed, a 200 error body ignored, the expiry cap, S3_ENDPOINT_URL honoured, the global ignored, and eleven mutations of the migration and the toml.

Round 1 fixes

  • Migration 0115 (unmerged, edited in place): id is TEXT PRIMARY KEY NOT NULL (SQLite let a NULL id in and the CHECK passed on NULL), the pseudonym table's key is INT NOT NULL PRIMARY KEY (not a rowid alias, so a NULL account is refused and not numbered), the header claim about NULL is now true and says which columns are NOT NULL and why, and a BEFORE INSERT trigger compute_gateway_users_keeps_first ignores an insert whose account or pseudonym is already stored, so INSERT OR REPLACE and REPLACE INTO (which delete without firing the delete trigger on D1) are a no-op. The header says what the three triggers do and do not cover, and a catalog test says the jobs have none and the pseudonyms exactly three.
  • Partner jobs: createJob takes { source: "partner", holdBody }, the exact text sent, reads the nine small fields of a hold from it (strict schema, at most 8 KiB, the partition tables and the owner's ceilings apply), skips the specification schema, launchSpecFits and the bundle checks, and spec_digest is the SHA-256 of those exact bytes, which are also spec.json. About 110 non-test lines, consistent with Phase D4: Partner reservation and report contract #2025 (the body there is { app_id, app_version, kind, partition, nodes, cores, memory_mb, gpus, minutes }). A person's or pipeline's job is unchanged.
  • An idempotency key with no account is refused as an argument error (the unique index treats NULL accounts as distinct).
  • Paths versus keys: presignIncomingUploads, finalizeSubmittedFiles and an owner's read of a submitted file now ask well-formed text and the 1,024-byte limit of both keys a path becomes (incoming/ and records/.../submitted/) before signing, and answer invalid_spec naming files.<i>.path (or invalid_record); submittedPathProblem itself is not tightened, so a bundle manifest path keeps the 512-character rule. submittedPathProblem now decodes leniently, per run of valid escapes, so one stray % no longer switches the encoded-traversal check off.
  • One copy is at most 5 GiB: a job, an upload address and a finalize refuse a larger archive or file as bundle_too_large whatever the owner's limits say.
  • Types: ComputeJobRow.state is ComputeState, UPLOAD_STATES is readonly ComputeState[], and the private duplicate of RECORDS_WRITTEN_SQL is gone.
  • New tests, each proved by mutation: the three finalize guards of the partner form (the 500 cap with zero listings and zero copies, a destination of another size, a different manifest already recorded, for a partner and for a bundle), the conditional write, anchored patterns for the Tapis owner, client, application id and version and the key, the hold-body cases, and a fence that scans the product for any assignment to the NEMAR_COMPUTE_S3_URL global. The docblock, ADR amendment item 2, the notes and the test header now say the copy waits for the job's row, which exists only if its hold does; the arithmetic is "about 39,470 outputs".
  • Mutation survivors: forcing the incoming-key check off in filePathProblem survives because the records key is the longer prefix and its check implies the incoming one (kept on purpose, with a comment); and forcing the presign archive's outer clamp off survived because checkFiles clamps again, so I dropped the outer clamp.

Decisions and deviations, for the reviewer

  • The gateway pseudonym is a stored random value, not an HKDF derivation from ENCRYPTION_KEY. The issue says both (the migration bullet says random and stored because a derivation changes if the key rotates; the compute-jobs.ts bullet says derive it), and the design page says random and stored, so I followed the design and the migration bullet. ADR 0118 amendment item 4 records it.
  • The outputs request body cap: I did not bound maxFiles (it is a contract the launcher's repository also holds); outputsBodyLimitBytes(maxFiles) derives the cap from the owner's maxFiles (at least 1 MiB, at most 64 MiB, 8 KiB + maxFiles x 1,700 bytes between). The launcher's own 1 MiB cap is the tighter bound today, so a job with more than about 8,000 ordinary outputs still fails too_many_outputs at the launcher until its cap is raised, which is the launcher's change. Nothing calls the helper yet; Phase A5: Job lifecycle, webhooks, settlement and results #2010's route will.
  • A partner's per-file upload is bounded at 500 files whatever the owner's bundle limit, because each file is one CopyObject and a Worker invocation may make at most 1,000 subrequests. The cap shadows the owner's bundleLimits.maxFiles with the same refusal word (bundle_too_many_files), so the partner contract and the design's section 6 must say 500. The file sizes are read from one listing before anything is copied.
  • Beyond the issue: createJob also refuses bundle_too_large before the hold (the owner's limit, never more than the 5 GiB one copy takes), throws idempotency_conflict for a key reused for another request, and answers compute_disabled when the records binding is absent; a partner batch job is marked written by finalizeSubmittedFiles, not by createJob; presignIncomingUploads takes an optional now that only a test sets. recordsWritten: true means spec.json and identity.json landed, not that the job is ready to submit: that is job.records_written_at.
  • The x-amz-checksum-sha256 header is signed with an INCOMING PUT when the caller declares a digest (the issue body); it is deferred only for output PUTs (Phase A5: Job lifecycle, webhooks, settlement and results #2010). Real R2's acceptance of the signed header on a presigned PUT is unverified (the stand-in enforces what S3 documents, and a real R2 may not enforce it or may refuse it); if real R2 refuses it, the fix is to drop sha256Hex in presignIncomingUploads. The size read back through the binding is the bound finalizeBundle relies on.
  • The amendment items about the outputs, bundle and complete routes (a second outputs request with no outputs, idempotent complete, the job token's validity, declared.json) belong to Phase A5: Job lifecycle, webhooks, settlement and results #2010 and are not built here. The state uploading is not written: every edge after created is phase A5's.
  • Not done: the design page's section 9 update and the owner-action entries (the README already lists the buckets, the lock and lifecycle rules and the token). The pipelines' own caps (daily count, live count per pool) are the dispatch phase's, as extra guards on the hold.

Not run, would check

  • The full bun test (epic to dev CI): this change adds a migration, bindings and a toml block that many suites read, so one full run is the way to see an unforeseen reader.
  • Real R2: the checksum header on a presigned PUT, CopyObject, path canonicalisation and an expiry of seven days have only been exercised against Miniflare and the verifying stand-in; one real presigned PUT and one copy in the dev bucket would settle them. The create-only conditional write (onlyIf: { etagDoesNotMatch: "*" }) is tested on Miniflare with a bucket whose head always answers nothing (a stale view): a different specification is refused as a conflict and the stored bytes stay, and an existing identity snapshot is kept; whether real R2 honours etagDoesNotMatch: "*" on a put is not proved, and the lock is the real guard.
  • Bucket lock and lifecycle rules (Miniflare does not enforce them).

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR2035

Version: 0.10.28-PR2035.4b15c04
Commit: 4b15c04


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review triage, driver, 2026-11-04. Round 1 was a two-reviewer Sonnet panel (contract and types; tests, errors and maintainability); this phase has no Opus checkpoint. Every accepted finding is fixed on this branch and was re-verified against its test; about 50 mutations of the new guards were killed.

Deferred or open, with the reason:

  • Real R2 behaviour (the signed checksum header on a presigned PUT, CopyObject, the conditional create, canonicalisation, the 7-day expiry, bucket lock and lifecycle rules): Miniflare does not enforce them; a dev-bucket check is an owner action. If real R2 refuses the signed header, the fix is to drop sha256Hex.
  • The output checksum header, the outputs request and complete routes, declared.json, and the job token's validity: phase A5 (amendment comments on Phase A3: Job records and the results and records buckets #2008 and Phase A5: Job lifecycle, webhooks, settlement and results #2010).
  • Replay of an account-less partner job: there is no key until the partner table of phase D exists; createJob now refuses a key without an account instead of ignoring it.
  • The 500-file cap on a partner's per-file upload (a Worker invocation makes at most 1,000 subrequests) shadows the owner's bundleLimits.maxFiles with the same refusal code: the partner contract and design section 6 must say 500.
  • The launcher's own 1 MiB request cap is tighter than the Worker's derived outputs body limit: reconciled in phase A5 together with the launcher.

@neuromechanist
neuromechanist merged commit c2bb527 into feature/issue-2005-epic-compute-core Nov 4, 2026
19 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-2008-phase3-job-records-and-the-results-and branch November 4, 2026 19:34

This branch was previously deployed

1 inactive deployment
npm — 4b15c042 Deployed Nov 4, 2026 by neuromechanist via publish #4158
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant