Skip to content

Stream B: worker dispatch + manifest-ready callback (#557 PR-1) - #562

Merged
neuromechanist merged 10 commits into
feature/issue-559-epic-central-manifestfrom
feature/issue-557-stream-b-worker
May 19, 2026
Merged

neuromechanist merged 10 commits into
feature/issue-559-epic-central-manifestfrom
feature/issue-557-stream-b-worker

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

PR-1 Stream B of epic #559 — adds the worker-side of #557's centralization. Behind feature flag `MANIFEST_VIA_CENTRAL_WORKFLOW` (default false). Old `generateManifest()` path kept as fallback.

  • `triggerManifestGeneration()` mirrors `triggerArchiveGeneration()` but targets `nemarOrg/nemar-cli` (central) instead of the dataset repo. Includes `skip_canary` flag for private/sandbox repos (per Stream A's late contract addition).
  • `POST /webhooks/manifest-ready` validates HMAC callback token, HEAD-checks S3 artifacts, inserts `dataset_versions` row.
  • `POST /webhooks/manifest-failed` records workflow failures in `manifest_jobs`.
  • Migration 0025 adds `manifest_jobs` table for state tracking.
  • EZID + Zenodo publish-version-doi handlers dispatch instead of generating inline when flag is on; inline `dataset_versions` INSERT moves into the callback so the row only appears once the manifest is on S3.
  • Adds `getNemarOrgAuth` / `getNemarOrgToken` to github-auth for the central repo's App installation (epic Epic: migrate GITHUB_ADMIN_PAT to a GitHub App installation token #432 plumbing reused).
  • Adds `headVersionArtifact` to s3.ts (HEAD-only sibling of `getManifest` for callback verification).
  • Adds portable `constantTimeEqual` so the HMAC verifier works in both Workers runtime and Bun's test harness.

Ops sequence (USER, before flipping flag)

  1. `wrangler secret put MANIFEST_CALLBACK_SECRET` on Worker (prod + dev, both accounts)
  2. Mirror the same value to `MANIFEST_CALLBACK_SECRET` secret on `nemarOrg/nemar-cli` (for Stream A's central workflow)
  3. Apply migration 0025 to D1: `npx cfman wrangler --account neuromechanist d1 migrations apply nemar-db -c backend/wrangler.toml` (also for SCCN account and dev D1)
  4. Flip `MANIFEST_VIA_CENTRAL_WORKFLOW=true` in wrangler.toml for the target env

Test plan

  • `bun test test/manifest-callback-token.test.ts` (12 tests: round-trip, tamper detection, length/prefix guards)
  • `bun test test/manifest-jobs-migration.test.ts` (13 structural assertions on 0025)
  • `bun run typecheck` clean (root + backend)
  • `bun x biome check` clean on modified files
  • E2E in epic-level testing once Stream A is live (epic Epic: Centralize manifest generation (PR-1 of #557) #559)

Closes part of #557.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review findings (epic leader)

Three reviewers ran (code-reviewer, pr-test-analyzer, silent-failure-hunter). Summary:

Critical (block merge)

  1. headVersionArtifact 403 → false — backend/src/services/s3.ts:484-489. Same root cause as PR Stream C: summary.json route + 5-dataset backfill (#558) #561's loadSummary 403 issue, manifests as the worker recording the workflow as failed even though the S3 upload succeeded; DOI is public, manifest is on S3, but dataset_versions row never inserted. Throw on 403 with explicit credentials message.
  2. verifyManifestCallbackToken swallows crypto errors → 401 — backend/src/services/github.ts:2256-2259. If crypto.subtle.importKey throws (malformed secret), every callback returns 401 "Invalid token" with no indication the real cause is a broken MANIFEST_CALLBACK_SECRET. Remove the try/catch or re-throw with context so Hono returns 500.
  3. nemar.org sync fires at dispatch time under centralFlow — backend/src/routes/webhooks.ts:554-566 (EZID) and ~819-833 (Zenodo). Under flag-on, DOI is minted and sync fires via executionCtx.waitUntil, but dataset_versions row + manifest.json + summary.json don't exist yet. Sync reads no manifest, emits incomplete nemar.org record, never re-syncs. Move sync into /webhooks/manifest-ready handler after the row insert succeeds.
  4. dataset_versions INSERT failure does NOT block manifest_jobs → ready — backend/src/routes/webhooks.ts:1030-1060. dbError is set but code falls through to flip status. Retry finds status != 'dispatched' and rejects. Callback becomes unreplayable + row never written. Return 500 before flipping status.
  5. skip_canary always false from worker — triggerManifestGeneration signature accepts skipCanary but neither call site passes it. Private/sandbox repos will fail raw.githubusercontent.com HEAD canary on the central path. At minimum pass true always (published datasets are public at DOI-mint time), OR thread from dataset.visibility / sandbox flag.

Test gaps (critical)

  • validateManifestCallbackBody zero coverage — exported pure function, no external deps, mirrors validateEnrichmentRef which has its own test file. Add a dedicated test (4-6 assertions: accepts valid, rejects missing/empty fields, rejects non-object).
  • isCentralManifestWorkflowEnabled coercion table zero coverage — exported pure function. A mis-deploy with MANIFEST_VIA_CENTRAL_WORKFLOW="True" or "1" silently stays on legacy. Add a parameterized test for the literal-"true" gate.

Important

  • /webhooks/manifest-failed missing workflow_run_url silently accepted, only mentioned mid-line in console.error. Add an explicit console.warn before the UPDATE when null.
  • Double-dispatch race on publisher retry — UNIQUE constraint is on (dataset_id, version, nonce) not (dataset_id, version). Each retry generates a new nonce, both workflows race, both can succeed. dataset_versions INSERT is OR IGNORE so no DB collision, but the operator sees two manifest_jobs rows. At minimum add a console.warn when superseding an older dispatched row for the same (dataset_id, version).
  • API_BASE_URL fallback is dead code — typed non-optional in bindings.ts, set in both wranglers. Remove || "https://api.nemar.org".
  • One-shot replay semantics not unit-tested — UNIQUE constraint test exists in migration test but runtime consequence (second callback with same nonce → 401) is not verified. Add a comment in the migration test header that this is deferred to E2E.
  • headVersionArtifact 403/5xx branches — should follow describeS3 real-S3 conditional pattern (see test/s3-deletion.test.ts:74).

Strengths

  • HMAC implementation is correct (SHA-256, nonce in signed material, no === on digests)
  • constantTimeEqual is portable + tested (XOR-accumulate fallback for Bun; timingSafeEqual fast path for Workers)
  • One-shot semantics correctly enforced at D1 layer via status gate (INSERT before dispatch)
  • getNemarOrgAuth/getNemarOrgToken mirrors getDatasetsAuth/getDatasetsToken correctly
  • triggerManifestGeneration correctly targets nemarOrg/nemar-cli (central), not the dataset repo
  • Migration 0025 has no DROP, uses IF NOT EXISTS, has UNIQUE + both indexes
  • Empty/missing token distinguished from wrong token (different 401 messages)
  • INSERT-before-dispatch ordering prevents fast-callback-against-missing-row race
  • MANIFEST_CALLBACK_SECRET unset is caught early → 500
  • Canonical S3 key derived from dataset_id/version (not from caller's manifest_url) → prevents SSRF

Fix agent spawning shortly.

@neuromechanist
neuromechanist marked this pull request as ready for review May 19, 2026 04:06
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review findings: resolution status

Addressed all critical + important findings from the epic-leader review. Four atomic commits on top of the prior tree.

Critical (block merge) — all fixed

  1. headVersionArtifact 403 → false — Fixed in 40780ae. Now throws with explicit headVersionArtifact 403: likely IAM credentials/permissions error for <key>. Check AWS_ACCESS_KEY_ID on the Worker. The manifest-ready handler's HEAD try/catch surfaces this in console.error and returns 502 with the distinguishing message.

  2. verifyManifestCallbackToken swallows crypto errors → 401 — Fixed in 40780ae. Removed the try/catch around signManifestCallbackToken. Added inline comment: "Crypto failures here mean MANIFEST_CALLBACK_SECRET is malformed; surface as 500 (via Hono's default error handler) not 401, so operators can distinguish 'broken secret on worker' from 'wrong token from caller'."

  3. nemar.org sync fires at dispatch time under centralFlow — Fixed in cfb133a. Both EZID and Zenodo handlers now wrap their syncToNemarAfterVersionDoi block in if (!centralFlow). The /webhooks/manifest-ready handler does a SELECT id, dataset_id, name, github_repo, concept_doi FROM datasets WHERE dataset_id = ? after the row insert and fires sync via executionCtx.waitUntil with the documented shouldSyncToNemarAfterVersionDoi gates (no_credentials / openneuro / sandbox skipped same as inline path). Non-fatal scheduling try/catch.

  4. dataset_versions INSERT failure does NOT block manifest_jobs → ready — Fixed in cfb133a. The DB INSERT block now returns c.json({ error: "Failed to insert dataset_versions row", db_error: dbError }, 500) before the status flip. The central workflow sees 500 and engages its retry path.

  5. skip_canary not threaded — Fixed in cfb133a. Both call sites now pass skipCanary: true with the contract-addendum comment justifying it (canary is duplicative; publish webhook is the authoritative caller; twin of skipGitBackedVerification on the inline path).

Test gaps (critical) — all fixed

  1. validateManifestCallbackBody unit tests — f464a67 added test/manifest-callback-body-validation.test.ts (20 tests: valid manifest-ready / manifest-failed bodies, missing each required field, non-object inputs, wrong types, explicit-null fields, plus canary_skipped round-trip).

  2. isCentralManifestWorkflowEnabled table test — f464a67 added test/manifest-flag-toggle.test.ts (test.each coercion table: literal "true" enables; True/TRUE/1/yes/on/false/empty/undefined/null/boolean true/whitespace-padded do NOT enable).

Important — all fixed

  1. /webhooks/manifest-failed workflow_run_url=null logging — Fixed in cfb133a. Explicit console.warn before the UPDATE when runUrl === null: "workflow_run_url=null; operator follow-up will need to grep recent Actions runs manually".

  2. API_BASE_URL fallback dead code — Fixed in cfb133a. Removed || "https://api.nemar.org".

  3. One-shot replay test gap comment — Fixed in f464a67. Header of test/manifest-jobs-migration.test.ts now notes runtime replay semantics are deferred to E2E (Epic: Centralize manifest generation (PR-1 of #557) #559 acceptance).

  4. Double-dispatch race warn — Fixed in cfb133a. After the INSERT, dispatchCentralManifestJob selects COUNT(*) for older dispatched rows with a different nonce and logs [manifest-dispatch] superseding N older dispatched job(s) for <id>@<version>; possible publisher retry. Best-effort; never blocks dispatch.

  5. manifest-jobs-migration.test.ts:60 weak assertion — Fixed in f464a67. The test now asserts status TEXT NOT NULL DEFAULT 'dispatched' (the column constraint) AND the dispatched | ready | failed enum comment verbatim — a regression that drops the comment or default would fail here.

Contract addendum (Stream A handoff)

Stream A landed canary_skipped: boolean in the callback body. Reflected in:

  • ManifestCallbackBody interface (optional canary_skipped?: boolean, with comment)
  • manifest-ready handler logs it in the success line: canary_skipped=true|false|(unset)
  • validateManifestCallbackBody already passes through (3 new tests pin the contract: true, false, absent — all accepted)
  • State doc updated (.context/epic_central_manifest_state.md)
  • Not persisted: no column on manifest_jobs in migration 0025; per epic-leader guidance, log-only

Verification

  • Focused tests: 86 pass / 0 fail / 108 expect() calls across 6 files (callback-token, callback-body-validation, flag-toggle, jobs-migration, sync-trigger, ezid-doi-validation).
  • bun run typecheck: clean.
  • bunx biome check on changed files: clean (only pre-existing published.doi! non-null assertion warning, unchanged by my edits).

Open questions / follow-ups for the epic-level review

  • The supersession warn check runs an extra SELECT COUNT(*) per dispatch. Negligible at our cardinality (one dispatch per publish), but if epic-leader prefers we drop it once the workflow stabilizes, it's a one-line removal.
  • The manifest-ready handler now does a SELECT * FROM datasets for sync scheduling. Could be cached or inlined into the original manifest_jobs SELECT in a follow-up if hot.

…anifest' into feature/issue-557-stream-b-worker

# Conflicts:
#	backend/src/services/s3.ts
@neuromechanist
neuromechanist merged commit b1624f1 into feature/issue-559-epic-central-manifest May 19, 2026
1 check failed
@neuromechanist
neuromechanist deleted the feature/issue-557-stream-b-worker branch May 19, 2026 04:15

This branch had an error being deployed

1 failed deployment
npm — 76059a3a Deployed May 19, 2026 by neuromechanist via publish #1028
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