Repository navigation
feat: dispatch web approvals to a workflow - #1578
Merged
Merged
Conversation
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.
3 of 4 tasks
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.
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR1578Version: 🤖 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 was referenced Oct 1, 2026
Persist the S3 Object Lock continuation token so a resumed approval does not restart at page 1
#1580
Open
Merged
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
/approveruns sixteen steps, and S3 Object Lock (step 14, after the irreversiblepublish_doi) works in batches of 100 objects: each call returnshasMoreand 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 atapprovingwith its DOI public, nothing locked, no catalog sync and no owner email, and anapprovingrow 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 NEMAROrigin) and an API key (noOriginneeded).error{ status: "dispatched", dataset_id, request_id, resume })origin_not_allowednot_foundnot_dispatchableblocked, now or at the claimalready_in_flightdispatch_faileddispatch_unconfigureddispatch_unconfirmedEvery error carries a stable code in
errorand a sentence inmessage./approveuses (ACTIVE_REQUEST_TAIL_SQL, shared), so the clicker is recorded on the row the run will touch.resumeis true when the request is alreadyapproving.repository_dispatch[approve-publication]tonemarDatasets/.githubwithclient_payload{ dataset_id, request_id, resume, environment }.environmentisproductiononly for the production Worker anddevfor anything else, including an unset value. No URL and no credential rides in the payload.List route
GET /admin/publish/requestsalso returnsapproval_requested_by,approval_dispatched_atand a computed booleanapproval_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 (
requestedorapproving) and either it was dispatched within 15 minutes, or it isapprovingwithupdated_atwithin 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 inshared/publication-retry.ts. The dispatch claim and the start of every/approveattempt clearlast_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_byfrom the request it acts on, and honors it only while the time-only lease is live, read at the top of/approvebefore that call's own heartbeat bump. While live, that admin is recorded inapproved_by, thedataset_publishedaudit row and thenotify_user_failedaudit row, and the executing account is kept asexecuted_byin 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
/approvecall is recorded under the executing key. The dispatch's ownapproval_dispatchedaudit row still names the clicker.Commits
feat: add approval dispatch columns(migration 0090)feat: add approve-publication dispatchfeat: report approval_in_flight on the request listfeat: add POST /admin/publish/:id/approve-dispatchfeat: record the clicking admin as approverdocs: add ADR 0080 for dispatched web approvaltest: race the dispatch claim through a yielding D1fix: keep the lease when a dispatch answer is lostfix: require a NEMAR origin on the dispatch cookie pathfix: answer a refused claim with what the request is nowfix: let a failed approval run stall after a grace windowfix: honor the web clicker only while their run is livetest: pin the lease edge and release ownershipdocs: correct ADR 0080 and the route commentfix: share the CLI retry delay instead of exporting itDeploy order
dev; the migration applies on deploy. Verify on api-test.approve-publicationworkflow merged tonemarDatasets/.githubmainbefore anything dispatches in production. A dispatch with no workflow does nothing, so the page would show "queued" until the lease lapses.devtomainhere, then the website promotion.Testing
bun run lintandbun run typecheckpass.biome checkoverbackend/reports 8 errors, all in files this PR does not touch (zenodo.ts,doi-orcid-discovery.tsand three tests); the 14 files this PR changes are clean.approval_in_flighton the list route including the 15 minute edge and failed runs; the dispatch route (cookie and key auth, Origin, a double click raced throughyieldingD1, 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.Notes for review
0089_private_site_sessions.sqlis already ondev. Another open PR claiming 0090 would conflict.updated_atis not touched by the claim. It is the orchestrator's progress heartbeat; bumping it would make a failed dispatch on anapprovingrow read as a live run for the whole lease.approvingbehave differently: an owner with no real name walks the row back toblocked; the sandbox, no-repository, dataset-not-found and invalid-repository answers return with the row atapproving, a freshupdated_atand nolast_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./approveis 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.Originis 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 bySameSite=Lax, the host-scoped cookie and the website proxy); that is a router-wide decision for a separate change.