Skip to content

feat: dispatch web approvals to a workflow - #1578

Merged
neuromechanist merged 15 commits into
devfrom
feature/approve-dispatch
Oct 1, 2026
Merged

neuromechanist merged 15 commits into
devfrom
feature/approve-dispatch

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

What

The backend half of web approval: a route that dispatches an approval to an executor instead of running it, a lease so only one run is live at a time, and attribution that names the admin who clicked. The workflow (nemarDatasets/.github) and the website UI are separate PRs. Decision record: ADR 0080.

Why

Approval is not one request. /approve runs sixteen steps, and S3 Object Lock (step 14, after the irreversible publish_doi) works in batches of 100 objects: each call returns hasMore and a continuation token that the caller must send back. The CLI loops. The website sent a single {} and reloaded, so any dataset over 100 files would stop at approving with its DOI public, nothing locked, no catalog sync and no owner email, and an approving row offers no button to continue. The loop is on the caller on purpose (running it in a Worker costs too much), so the website must ask for a run, not perform one.

Route

POST /admin/publish/:id/approve-dispatch, admin only, no body. Works with a web session cookie (the website, which must send a NEMAR Origin) and an API key (no Origin needed).

Result Status error When
dispatched 202 none ({ status: "dispatched", dataset_id, request_id, resume }) claimed and sent
foreign origin 403 origin_not_allowed a cookie request from a non-NEMAR origin, or with none
no active request 404 not_found none exists, or it was published or denied before the claim
blocked 409 not_dispatchable the newest active request is blocked, now or at the claim
run in flight 409 already_in_flight the lease is live (see below)
GitHub refused 502 dispatch_failed GitHub answered non-2xx, or a token could not be minted; claim released
no credential 502 dispatch_unconfigured the Worker has no GitHub credential; retrying will not help; claim released
answer lost 502 dispatch_unconfirmed the call dropped or timed out (10 s); it may have started, so the lease is KEPT

Every error carries a stable code in error and a sentence in message.

  • It acts on the newest active request by the same rule /approve uses (ACTIVE_REQUEST_TAIL_SQL, shared), so the clicker is recorded on the row the run will touch.
  • resume is true when the request is already approving.
  • The claim is one conditional UPDATE, so two simultaneous clicks dispatch once. When it refuses, the route re-reads the row and answers from what the request is now, not always "already running".
  • The dispatch is repository_dispatch[approve-publication] to nemarDatasets/.github with client_payload { dataset_id, request_id, resume, environment }. environment is production only for the production Worker and dev for anything else, including an unset value. No URL and no credential rides in the payload.
  • A dispatch GitHub may have accepted but whose reply was lost keeps the lease: releasing it would let the next click start a second run. Only definite not-sent failures release the claim, and a release clears only a claim this click made.

List route

GET /admin/publish/requests also returns approval_requested_by, approval_dispatched_at and a computed boolean approval_in_flight, from the same SQL expression the claim uses, so a page never offers a button the route would refuse and never hard-codes the lease.

A run is in flight when the request can still run (requested or approving) and either it was dispatched within 15 minutes, or it is approving with updated_at within 15 minutes (so a person's own terminal run blocks a web launch). A run that recorded a failure (last_error) stays in flight for a 60 second grace window and is stalled after it, so the page can offer Resume without waiting out the lease. The grace is not zero because the CLI retries a failed step after 10 seconds, up to five times, and an executor launched in that wait would run beside the retry. A test holds the grace above the CLI's retry delay, which now lives in shared/publication-retry.ts. The dispatch claim and the start of every /approve attempt clear last_error, so a restart or a fresh dispatch is in flight again at once; a dispatch that is not sent puts the error back.

Attribution

The orchestrator reads approval_requested_by from the request it acts on, and honors it only while the time-only lease is live, read at the top of /approve before that call's own heartbeat bump. While live, that admin is recorded in approved_by, the dataset_published audit row and the notify_user_failed audit row, and the executing account is kept as executed_by in the details. Every batch of a long web run, and the retry of a failed step, still resolves to the clicker. A run that lapsed and was resumed by a different admin at a terminal records that admin. A terminal approval is unchanged, byte for byte, and /approve's request and response contract is unchanged.

The cost, stated in the ADR: a web run that sat quiet longer than the lease before its first /approve call is recorded under the executing key. The dispatch's own approval_dispatched audit row still names the clicker.

Commits

  1. feat: add approval dispatch columns (migration 0090)
  2. feat: add approve-publication dispatch
  3. feat: report approval_in_flight on the request list
  4. feat: add POST /admin/publish/:id/approve-dispatch
  5. feat: record the clicking admin as approver
  6. docs: add ADR 0080 for dispatched web approval
  7. test: race the dispatch claim through a yielding D1
  8. fix: keep the lease when a dispatch answer is lost
  9. fix: require a NEMAR origin on the dispatch cookie path
  10. fix: answer a refused claim with what the request is now
  11. fix: let a failed approval run stall after a grace window
  12. fix: honor the web clicker only while their run is live
  13. test: pin the lease edge and release ownership
  14. docs: correct ADR 0080 and the route comment
  15. fix: share the CLI retry delay instead of exporting it

Deploy order

  1. This PR to dev; the migration applies on deploy. Verify on api-test.
  2. The approve-publication workflow merged to nemarDatasets/.github main before anything dispatches in production. A dispatch with no workflow does nothing, so the page would show "queued" until the lease lapses.
  3. dev to main here, then the website promotion.

Testing

  • bun run lint and bun run typecheck pass. biome check over backend/ reports 8 errors, all in files this PR does not touch (zenodo.ts, doi-orcid-discovery.ts and three tests); the 14 files this PR changes are clean.
  • CI's required offline tier, run locally with the same file selection, on the final tree: 437 files, 7789 pass, 26 skip, 0 fail.
  • New suites: migration shape; dispatch payload, failure classification and timeout against stand-in servers; approval_in_flight on the list route including the 15 minute edge and failed runs; the dispatch route (cookie and key auth, Origin, a double click raced through yieldingD1, a request changing between the read and the claim, claim release and its ownership, a dropped connection); attribution including lapsed and long-running leases, chained from the real dispatch route into the real /approve; a restarting run; the D1 wrappers themselves.
  • Every new test was watched failing: each guard was mutated one line at a time and the suite failed for the expected reason each time, then the source was restored and the tree confirmed clean. One mutation survived at first (reading the lease after the heartbeat bump); it exposed a test that seeded the wrong status, which is now pinned and caught.
  • Not exercised end to end against GitHub or api-test: no workflow exists yet to receive the dispatch, and no migration was applied to any remote database.

Notes for review

  • Migration number: 0090, because 0089_private_site_sessions.sql is already on dev. Another open PR claiming 0090 would conflict.
  • updated_at is not touched by the claim. It is the orchestrator's progress heartbeat; bumping it would make a failed dispatch on an approving row read as a live run for the whole lease.
  • Pre-loop refusals do not read as failures. The gates after the request flips to approving behave differently: an owner with no real name walks the row back to blocked; the sandbox, no-repository, dataset-not-found and invalid-repository answers return with the row at approving, a fresh updated_at and no last_error, so the page reads "running" for the lease; only the 426 answer returns before the row is touched. The reason is in the workflow log.
  • A workflow failure the backend cannot see stays invisible (a missing secret, an install failure): /approve is never called, so nothing is written and the lease lapses on its own. Closing that needs a release or callback endpoint, like the pre-screen workflow's callback token. A follow-up, not part of this PR.
  • Origin is enforced on this route's cookie path only. The admin router does not apply it to its routes in general (approve and deny have the same posture today, protected by SameSite=Lax, the host-scoped cookie and the website proxy); that is a router-wide decision for a separate change.

publication_requests gains approval_requested_by (the admin who
clicked Approve on the website) and approval_dispatched_at (the lease a
second click is refused against). Both nullable, no backfill, no FK.

Tested: migration test on the real schema, each guard mutation-checked.
triggerApprovePublication sends repository_dispatch to the central
workflow with dataset_id, request_id, resume and an environment name
(production only for the production Worker; anything else is dev). No
credential or URL rides in the payload.

Tested: stand-in GitHub server reads the real request; four mutations
(event type, credential in payload, environment rule, swallowed error)
each fail the suite.
One SQL predicate (services/approval-dispatch.ts) defines a live
approval run: dispatched within 15 minutes, or approving with a fresh
updated_at, and only while the request can still run. The second clause
makes a terminal-driven approval count. The list route computes it per
row; the dispatch route will claim with the same expression.

Tested: real route on a real schema; six mutations (clause dropped,
status gate dropped, lease 30 and 5, comparison direction, integer not
coerced) each fail the suite.
Claims the newest active request with one conditional UPDATE (refused
while a run is in flight, a terminal run included), records the admin
who clicked, and dispatches approve-publication to the central workflow,
answering 202. A refused dispatch releases the claim and answers 502.
Blocked requests answer 409 not_dispatchable. updated_at is left alone
so a failed dispatch cannot read as a live run.

Tested: real route on a real schema with a stand-in GitHub server,
cookie and key auth, a double click dispatching once, claim release;
eight mutations each fail the suite.
A web-dispatched run is executed by a workflow with its own service key,
so the caller is the bot. The orchestrator now reads approval_requested_by
from the request it acts on and records that admin in approved_by and the
dataset_published and notify_user_failed audit rows, keeping the executing
account as executed_by in the details. A terminal approval is unchanged,
byte for byte.

Tested: real /approve runs, one chained from the real dispatch route; eight
mutations each fail the suite; the golden approve suite stays green.
realD1 runs each statement synchronously, so two requests started together
only interleave by accident of microtask order. yieldingD1 waits a macrotask
before every statement, modeling D1's round trip, and interceptingD1 lands a
write between a route's read and its write. The concurrent-click test now
runs through yieldingD1.

Tested: with the claim replaced by a separate SELECT then an unconditional
UPDATE, the test fails at the [202, 409] assertion (received [202, 202]).
That mutation also fails under the plain shim, so the old test was not
vacuous for it; the wrapper makes the interleaving deliberate.
A dispatch GitHub accepted but whose reply was lost must not release the
claim: the next click would start a second run. Release only on failures
that are definitely not-sent: no credential, a token that cannot be minted,
or GitHub answering non-2xx (DispatchRejectedError). A dropped connection
or a timeout (AbortSignal.timeout, 10s, under the website's 15s) answers
502 dispatch_unconfirmed and keeps the lease. A missing credential answers
502 dispatch_unconfigured with a message that says retrying will not help.

Tested: dropped connection keeps the lease and a second click is a 409;
non-2xx and no credential release; a hung GitHub times out and is not a
rejection. Seven mutations each fail the suite.
The route launches an irreversible publication, and a session cookie rides
along with any cross-site request. A cookie request now needs an allowed
Origin (403 origin_not_allowed); a bearer key, which a terminal and the
workflow use, is not asked for one. Same cookie-only rule as
resolveActingAccount and /auth/orcid/cli-start, applied to this route only.

Tested: foreign origin and missing origin refused with nothing claimed, app
origin accepted, bearer with no Origin accepted, a member's cookie is 403.
Three mutations each fail the suite.
When the conditional UPDATE changes no row, re-read the request: published or
denied is 404 not_found, blocked is 409 not_dispatchable, and only a request
that can still run is 409 already_in_flight. Before, a request approved
between the read and the claim answered 'already running', sending the admin
looking for a run that does not exist.

Tested: a request published, denied or blocked between the read and the
claim, landed through interceptingD1 on the real database; the ordinary
in-flight refusal is unchanged. Three mutations each fail the suite.
A run that failed kept the lease for the whole 15 minutes. It now counts as
in flight for FAILED_RUN_GRACE_SECONDS (60) after it records last_error, then
as stalled, so the page can offer Resume. Not at once: the CLI retries a
failed step after 10 seconds, up to five times, and an executor launched in
that wait would run beside the retry about to start. A test binds the grace to
the CLI's APPROVE_RETRY_DELAY_MS (now exported; behavior unchanged).

The dispatch claim and the orchestrator's request-start UPDATE both clear
last_error, since a new attempt begins; a dispatch that is not sent restores
it. Terminal output is unchanged when no web claim exists.

Tested: failed run inside and past the grace, dispatch of a stalled run,
a restart reading as running at once, the error restored on a not-sent
release, the grace held above the CLI retry delay. Seven mutations each fail
the suite, including grace 0.
approval_requested_by is never cleared, so a run that lapsed and was resumed by
another admin at a terminal was recorded as the original clicker's approval.
The orchestrator now reads the time-only lease at the top of /approve, before
its own heartbeat bump, and names the clicker only while it is live. Every
batch of a long web run (fresh updated_at) and the retry of a failed step
still resolve to the clicker; a run quiet past the lease is recorded under the
calling admin. The failure-aware in-flight predicate is deliberately not used
here, so a failure cannot strip attribution from the retry that finishes it.

Tested: live, lapsed, long-run, failed-step retry, a resume past the grace
window, and a run that died partway; four mutations each fail the suite,
including reading the lease after the bump.
A dispatch or a last sign of life exactly 15 minutes old is still in flight
(>=, not >). SQLite's clock ticks by the second, so each case seeds, checks the
threshold still equals the seeded value, and retries if the second ticked.

A release clears only a claim this click made: another admin's claim, landed
on the real row between this click's claim and its release through
interceptingD1, is not undone by this click's failure.

Tested: three mutations (each >= to >, release without the ownership
condition) fail the suite; the edge tests passed 15 of 15 repeated runs.
Pre-loop refusals are not 'no trace': the real-name gate walks the row back
to blocked with a block_reason; the sandbox, no-repo, dataset-not-found and
invalid-repo answers return after the row flipped to approving with a fresh
updated_at and no last_error, so the page reads running for the lease; only
the 426 path leaves the row untouched. /approve's request and response
contract is unchanged (the orchestrator now reads approval_requested_by).

Records the grace window for a failed run, the lease-gated attribution and its
cost, the unconfirmed-dispatch rule, the cookie Origin check, and the
follow-up that a workflow failure the backend cannot see needs a release or
callback endpoint.
@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1578

Version: 0.10.12-PR1578.960da69
Commit: 960da69


🤖 Updated on each push.

Exporting APPROVE_RETRY_DELAY_MS from lib/api/publish.ts widened a pinned
CLI export surface (api-export-surface) for a value that is not CLI-facing.
It lives in shared/publication-retry.ts now, beside publication-steps.ts, and
both the CLI and the backend lease test import it. CLI behavior is unchanged.

Tested: the export-surface pin is green again; the grace-vs-retry-delay guard
still fails when the delay is raised to 60s.

This branch was previously deployed

1 inactive deployment
npm — 960da69d Deployed Oct 1, 2026 by neuromechanist via publish #3030
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