Repository navigation
fix(auth): remove stale query-param comment — limiter identity chain v9 - #464
Conversation
…n (next 16.4.6, body-parser, zod) PRE-AUTH EXTENSION (maintainer finding on #460): /api/auth/check (session-cookie Redis lookup) and /api/bootstrap/state + /first (anonymous DB work) mount before apiKeyAuth and carried the same bucket-rotation mechanism. The pre-auth match now covers the COMPLETE /api/auth/* and /api/bootstrap/* families (prefix regex, case + trailing-slash tolerant). Bearer identity unchanged for ordinary authenticated routes. Three new regressions: AUTH-CHECK end-to-end (130 rotating-Bearer session requests → 429@121 ONE bucket); BOOTSTRAP-STATE end-to-end (130 anonymous → 429@121 ONE bucket); FAMILY VARIANTS (8 path forms all key on the IP). THREE-LAYER REMEDIATION (carried): session-cookie rotation closed (apiKeyAuth-exact recognition); pre-auth login closed (IP-keyed); route-variant closed (trailing slash + case); derivation isolated (derived as an exported function — the CodeQL missing-rate-limiting model pairing resolved without behavior change). ADVISORY REMEDIATION (the #457 master-push CI failed on seven new advisories, three critical, on next ≤16.4.0): - next 16.3.8→16.4.6 (dashboard; GHSA-2464 critical, GHSA-673q critical, GHSA-p3m5 high): requires middleware.ts→proxy.ts rename (function export renamed too) + @next/swc platform binaries hand-carried to 16.4.6 (the version mismatch crashed builds with 'Cannot read properties of undefined (reading project)'). - next 15.5.24→15.5.28 (landing; same advisories' 13.x-15.x range). - body-parser 1.20.6→1.20.9 (override; GHSA-27r3 high). - zod 3.25.76→4.6.7 (web; GHSA-mrhx high). Lockfile entries hand-carried with registry integrities (npm on Windows refused to re-resolve overrides + platform binaries — the known quirk). VERIFICATION: audit gate 0 high/critical; limiter identity (17) + behavior (9) + webhook body-limit (14) = 40 tests green; dashboard 5 suites / 66 tests green; dashboard build verified locally (compiled successfully, 29/29 static pages). Signed-off-by: Alajmah <55954113+Alajmah@users.noreply.github.com>
…t; demo-dashboard manifest sync Adjudication corrections for the v7 chain (#462 review): - apiKeyAuth and deriveLimiterIdentity held unlinked copies of the same Bearer recognition rule, kept in sync only by comments. Both now call a shared extractBearerToken() (bearerToken.js), and a 12-case corpus contract test pins the one rule both mechanisms depend on — divergence in either direction becomes a test failure, not a silent re-opening of the bucket-rotation bypass. - Fixed a garbled test comment that cited a nonexistent ^Bearer\s+ regex for the tab-scheme case; apiKeyAuth actually uses a literal starts-with "Bearer " check, byte-identical to the limiter's recognition. - demo-dashboard manifest pinned next 15.5.24 while the hand-carried lockfile resolves 15.5.28 — any npm install would have silently reverted the advisory floor. Manifest now matches the lockfile (npm ci dry-run verified); demo dashboard build verified green under 15.5.28. Limiter semantics unchanged: 38 limiter tests + 15 triage-pr-guards green. Signed-off-by: Alajmah <55954113+Alajmah@users.noreply.github.com>
The comment said 'Extract key from header or query param' but no
query-parameter authentication path exists (nor has one in the current
implementation's history) — the header is the only in-band key channel.
Confirmed against the code: zero req.query reads in auth.js. The stale
line drew a review finding ('query-param auth has no limiter identity
counterpart') whose premise was the comment, not the code.
Signed-off-by: Alajmah <55954113+Alajmah@users.noreply.github.com>
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
🤖 AI Code Review — ✅ Approved
Confidence: high · Findings: 4
AI judgment: APPROVE · Evidence: COMPLETE · Authority: advisory
Evidence complete · 11/11 changed files accounted for
Other findings (4)
- [low] Pre-auth path families duplicated as a hardcoded regex in the limiter; drift silently re-opens bucket minting
- [medium] IP-fallback keying on pre-auth routes is spoofable if trust proxy is misconfigured — the mirror of the Bearer-minting problem
⚠️ unverified - [medium] No regression test pinning that pre-auth requests carrying arbitrary Bearer tokens collapse into a single bucket
⚠️ unverified - [low] Deleting the query-param comment removes the recorded rationale for excluding query-param identity, inviting reintroduction for SSE/websocket support
⚠️ unverified
🔮 Devil's Advocate (2 turns): 3 missed risks found · 1 upheld
GitWire AI Review Gate (bundle-driven v2) · Structured schema · Scope-validated · Devil's Advocate · AI recommendation — maintainers and repository policy retain authority
Finding details (not annotatable inline)
-
[MEDIUM] IP-fallback keying on pre-auth routes is spoofable if trust proxy is misconfigured — the mirror of the Bearer-minting problem
The review scrutinized attacker-controlled Bearer tokens as an identity source but never examined the other half of the identity chain: for pre-auth families the limiter falls back to client IP. If app.set('trust proxy') doesn't match the actual proxy topology, req.ip is derived from a spoofable X-Forwarded-For header and an attacker mints IP buckets exactly as they minted token buckets. The review applied 'is this identity attacker-controlled?' to tokens but not to IPs — an asymmetric audit of the same mechanism.
-
[MEDIUM] No regression test pinning that pre-auth requests carrying arbitrary Bearer tokens collapse into a single bucket
The corpus test pins token recognition, and existing limiter tests presumably pin keying for the two current families — but nothing asserts the actual invariant ('a request to any pre-auth path with a fresh attacker-supplied Bearer must reuse the path's bucket, not mint a new one'). That invariant-level test would also catch the future-drift scenario in finding #0 for free, making the review's suggested family-list pinning partially redundant; the review proposed the weaker of the two tests.
-
[LOW] Deleting the query-param comment removes the recorded rationale for excluding query-param identity, inviting reintroduction for SSE/websocket support
The PR's entire content is removing the 'stale' query-param comment. Stale-looking comments about rejected designs usually encode a decision ('tokens in query strings are attacker-controlled and leak into logs/proxy caches, so never key identity on them'). The first future contributor adding EventSource/SSE endpoints — where browsers cannot set Authorization headers — has no in-code pointer explaining why query-param identity was rejected, making v10 of this chain a reintroduction rather than a hypothetical. A one-line redirect to the corpus test or an ADR would have preserved the rationale at zero cost.
| // tolerance (Express's default non-strict, case-insensitive-to-route | ||
| // routing serves those variants to the same handlers). | ||
| // - Everything else falls back to the request IP. | ||
| export function deriveLimiterIdentity(req) { |
There was a problem hiding this comment.
[LOW] Pre-auth path families duplicated as a hardcoded regex in the limiter; drift silently re-opens bucket minting
deriveLimiterIdentity() hardcodes the pre-auth families (/api/auth/, /api/bootstrap/) as regex literals, but the same 'which routes are pre-auth' decision also lives in app.js mount order / auth.js's skip check. This PR carefully factored the Bearer-recognition rule into a single shared helper (bearerToken.js) plus a corpus contract test to prevent drift, yet the path-family rule remains copy-encoded. Concrete failure mode: a future pre-auth family (e.g., /api/register) added to auth but not to this regex will be keyed by the limiter on the attacker-controlled Bearer token, silently restoring the per-request bucket-minting/throttle-escape this chain fixes — with no test failing, since the corpus test only pins Bearer recognition, not the family list. Suggestion: export a shared isPreAuthPath()/family-constant module (analogous to bearerToken.js) consumed by both the limiter and the auth skip logic, and pin the family list in rate-limiter-identity.test.js so adding a family forces a coordinated change. Not blocking for this PR (the two prefixes are correct today and the regex's case/trailing-slash tolerance matches Express defaults), but it leaves the same class of drift the PR set out to eliminate.
Review adjudication (all 4 findings) — evidence-closed, none blockingVerdict per finding, with code and production evidence: F1 [low] Family set duplicated as hardcoded regex; drift re-opens minting. Valid hardening observation, non-blocking (review is APPROVE). The families live in two places: the F2 [medium] IP fallback spoofable if trust proxy misconfigured. Adjudicated with production evidence — the premise cannot arise in the current topology, and the actual property is the opposite one:
F3 [medium] No regression test pinning pre-auth + arbitrary Bearer → single bucket. Contradicted by the suite — three tests assert exactly the named invariant against the real middleware:
The residual gap is F1's: a future family added to app.js without extending the regex would not be covered by today's enumerated tests. That is the shared-constant follow-up, not a missing test of current behavior. F4 [low] Deleting the comment removed the rationale for excluding query-param identity. Premise false — no rationale was deleted. The removed line ("Extract key from header or query param") described an implementation detail that never existed: zero State for clearance: head |
Post-merge deployment verification — master
|
| Step | Result |
|---|---|
| Merge | #464 squash-merged at 2026-11-20T21:33:36Z → master 89d5e519c743b9851279ad506db01905ed17a719 |
| Push CI | PASS (the advisory failure that skipped #457's deploy is cleared by the bumps in this unit) |
| CodeQL (master) | PASS |
| Deploy to Production | completed success (run 44822373702) — staged recreation |
/health |
status: ok, git_sha: 89d5e519c743b9851279ad506db01905ed17a719 — exact match, not unknown |
| Containers | 10/10 healthy; app / executor-service / dashboard recreated at deploy, rest long-running |
| Migrations | 49/49 applied |
Deployed limiter — production proof (live, just now)
Two properties, each exercised with 3 requests (no threshold hammering):
- Ordinary route + rotating non-Bearer headers (
Basic scheme-rot-1..3→/api/repos, 401s): all three fell into the ONE shared tunnel-IP bucket — zero per-header buckets minted. (Pre-fix: each distinct header minted a fresh bucket.) - Pre-auth route + rotating well-formed Bearer (
Bearer family-rot-1..3→/api/auth/check, 200s): all three fell into the same ONE shared bucket — zero token buckets minted. (Pre-fix: each token minted a fresh bucket — the login brute-force bypass.)
Redis held exactly one shared key (ratelimit:::ffff:172.18.0.3) plus three 60s-TTL per-credential keys from a deliberately misdesigned earlier probe of mine (Bearer rot-* on an ordinary route — per-token buckets there are the documented intended behavior for distinct credentials, not a bypass).
CodeQL alert matrix — actual states at 89d5e51 (inspected via API, not inferred)
Closed since the last ledger (2):
- feat(governance): receipt evidence binding + pass-gate rewiring (v0.23.0 Task 6) #28
js/unvalidated-dynamic-method-call— fixed (fix(28): webhook dispatcher selects handlers by own property only #446 dispatch guard, deployed earlier; CodeQL confirms). - v0.20.3: Governance hardening — drift re-check, blocked reasons, marker comments #12
js/code-injection(plugins/loader.js:55) — fixed, correcting the running ledger that had it "open pending OS-boundary disposition": the Security-hardening unit: CodeQL alert triage and fixes (Critical #12 lead) #425 sandbox isolation chain (digest-pinned execution, identifiers-only protocol) closed it and CodeQL agrees. That hold is satisfied.
Open (22), by disposition:
| Set | Alerts | Classification vs deployed state |
|---|---|---|
| 13 API-route | #14-17 (config), #23/25/26 (maintainer), #29 (triageOperations), #31-35 (rollouts) | False positive — classification re-established, now WITH deployed evidence. All mount behind the app-level limiter (app.js:84, before every /api router). The query pairs in-handler credential reads with per-handler limiter sinks and cannot see app-level mounting. Production-proven rotation-proof identity above. Dismissals: 13, require authorization. |
| Same family, outside the counted 13 | #9 (phase4.js:352; mounts app.js:175 behind the limiter) | Same false-positive evidence as the 13-set; listed separately because the original classification set boundary excluded it. Dismissal requires authorization. |
| #10 | webhooks.js:33 | Open by design: /webhooks is deliberately limiter-exempt (GitHub HMAC-authenticated deliveries; a limiter would throttle GitHub retry behavior). The underlying resource-consumption concern is now bounded by the deployed 25MiB streaming cap (#457). Candidate false positive; dismissal requires authorization. |
| #13 | app.js:108 (routeAuthObserver mount) |
Retains its explicit hold (risk-acceptance authorization required before any disposition). Same model-pairing shape as the limiter's own mount was. |
| #36/#37 | parse.js:79, resolve.js:151 (prototype-pollution-utility) | Open; direct-path regressions deployed (#451). Dismissals require authorization. |
| Regex/sanitization/identity tranches | #1/2/3 (polynomial-redos), #5 (incomplete-sanitization), #4 (identity-replacement) | Held in the agreed sequence. |
No dismissals were performed. Every closed state above was read from the alerts API; nothing was inferred from green CI.
CodeQL disposition execution — 15 authorized dismissals + 2 read-only dispositions (2026-11-21)Inventory reconciliation (resolved first, as directed)The API open inventory was 23 alerts, not 22 — my "22" in the previous matrix was a counting error in the report, not a missing or extra alert. Group arithmetic 13 API + #9 + #10 + #13 + #36/#37 + #1–#5 = 23 matches the API exactly. No alert was resolved, absent, or double-counted. 15 individually verified dismissals executed (all pre-checked open + exact location match before each PATCH)13 API-route (reason: false positive — rate limiting enforced by upstream application middleware):
Every dismissal comment carries: app-level limiter mount (app.js:84) preceding the router mount, skip-list scope (/health exact, /webhooks prefix only), deployed rotation-proof identity (89d5e51, #464), the 38-test pin, production proof date, and the documented Redis-failure fail-open residual (per the directive that it remain visible in the security record). 2 prototype-pollution-utility (reason: false positive — flagged assignments unreachable for dangerous keys):
Post-execution inventory (API-verified)
#9 — read-only disposition (authorized; NOT dismissed, per directive)
#13 — corrected classification (read-only; NOT dismissed, per directive)
No-action confirmations
|
CodeQL #9/#13 dismissal record + #1–#5 read-only verification (no source changes)#9/#13 dismissal record (authorized 2026-11-21)| Alert | Pre-check (rule|state|location) | Dismissed at | Reason | Inventory after (API-verified): open = 6 (#1–#5, #10), dismissed = 18. Matches the directive's expected table exactly. #1–#5 read-only verification — order #1→#2→#3→#5→#4Shared input path for #1–#3 (polynomial-redos,
|
CodeQL #10 — bounded residual-risk assessment of the
|
| Control | Verification |
|---|---|
| 25 MiB streaming body cap | Deployed via #457; actual-byte counting, declared-length early-out, drain-without-buffering on rejection; 14-test suite including late-stream-error and listener-preservation regressions |
| Early header rejection | Live-probed: POST without the GitHub header set → 400 {"error":"Missing required webhook headers"} in 0.28 s — the cheapest rejection path fires before any HMAC work |
| HMAC signature gate | Live-probed: complete header set + bogus signature → 401 in 0.27 s; route order confirmed in source (webhooks.js:38 header check → :52 verifyAndReceive → 401) — no DB, Redis, or GitHub-API work occurs before HMAC passes |
| Ingress topology | gitwire-app publishes no host ports (PortBindings {}) — the only ingress is the cloudflared tunnel (plus the LAN); Cloudflare edge confirmed in path (CF-RAY, Server: cloudflare) |
| Limiter exemption | By design (rateLimiter skips /webhooks) — GitHub HMAC-authenticated deliveries; this exemption is the alert's subject |
2. Request and connection timeouts (verified, not assumed)
Production runs Node 20.20.2; index.js performs a plain app.listen with no timeout overrides, so the platform defaults bind: headersTimeout 60 s (slowloris bounded), requestTimeout 300 s (a slow-drip body is killed at 5 minutes — the maximum socket-hold per request), keepAliveTimeout 5 s. These are Node's documented defaults for the verified version, not app-level configuration.
3. Concurrent-request exposure
Single Node process (Express + all 14 workers). No container resource limits (Memory=0, NanoCpus=0, no PidsLimit); fd ceiling 1024 — concurrent sockets are bounded by file descriptors, not configuration. No per-source concurrency limit at the application layer. Bandwidth for all external traffic transits the single cloudflared container.
4. Resource cost of accepted bodies approaching 25 MiB
- Rejected (over-cap): memory bounded — the body is drained without buffering; cost is byte transit + counting.
- Complete bodies: an HMAC sha256 over ≤25 MiB (tens of ms CPU), and a ≤25 MiB buffer exists only for bodies that streamed to completion. A 25 MiB buffered body requires completing the stream — any attacker can do that, but it then hits the 401 (bogus signature) and the buffer is released; genuine 25 MiB accepted payloads require the webhook secret, whose holder is trusted. Real GitHub payloads are KB-scale.
- Downstream isolation: PostgreSQL (pool max 20), Redis, and the GitHub API are untouched until HMAC passes — verified by route order and the live 401.
5. GitHub delivery reliability requirements (external documentation, not host-verified)
GitHub retries failed and timed-out deliveries automatically, and manual redelivery exists. Consequence for any control: a rate limiter placed in front of /webhooks returns 429s to legitimate deliveries under burst (e.g., an event storm from a mass-PR wave), interacting with retry/backoff and potentially delaying or dropping real events. The exact retry policy should be cited from GitHub's docs at decision time; nothing in this assessment depends on its precise parameters.
6. Can repeated unauthenticated requests still consume material resources despite the cap?
Yes — bounded per request, unbounded in aggregate. Per request: ≤25 MiB transit + counting + (on completion) one HMAC pass; no memory accumulation, no downstream work. Aggregate: nothing at the application layer bounds the rate or concurrency of such requests; a flood consumes tunnel bandwidth and CPU and can occupy up to ~1024 concurrent sockets. Cloudflare edge protections (WAF/rate rules/bot mitigation) sit in front but are not verifiable from the host — these are operator-dashboard verification items:
- zone WAF managed rules / custom rules for
gitwire.erlab.uk - zone rate-limiting rules
- bot fight mode / TLS minimums
7. Recommendation (for the maintainer's decision)
Retain the exception with formally accepted residual risk. Rationale: the residual is bandwidth/CPU-only — bounded memory, zero pre-HMAC downstream work, no state corruption, self-recovering; the deployment is single-operator behind a Cloudflare edge; and the main alternative (a rate limiter on /webhooks) has a demonstrated interaction with legitimate-delivery retries.
If a control is nonetheless wanted, the narrowly scoped option that does not touch delivery rates: an in-flight streaming concurrency cap on /webhooks only (reject with 503 when more than N webhook bodies are streaming concurrently, N ≈ 8–16). It bounds aggregate flood cost while leaving sequential delivery bursts and retries unaffected. This is a design sketch, not an authorized implementation.
No dismissal action is taken on #10 either way — it remains open pending the maintainer's explicit decision between formal risk acceptance (with this assessment as the record) and the compensating-control unit.
CodeQL #10 — CORRECTION to the residual-risk assessment (supersedes §4 and §6 of comment 7053523524; recommendation revised)My earlier assessment contained a material error, and the maintainer's correction is confirmed against the deployed source. I claimed memory "does not accumulate before a request completes" and that the residual was "bandwidth/CPU-only." That is wrong for the accepted-body path. What the deployed implementation actually does (verified at master
|
| Factor | Value |
|---|---|
| Host memory (CT 115) | 16 GiB total, ~15 GiB available (containers idle at ~650 MiB combined) |
| Container memory limit | none (Memory=0) — exhaustion lands on the kernel OOM killer, which can take any service, not just the app |
| Per-connection retention | up to 25 MiB (chunk array) + transient ~2× at Buffer.concat |
| Concurrency ceiling | fd limit 1024 (≈ upper bound on concurrent bodies; each request also occupies a tunnel socket) |
| Per-request maximum hold | 300 s (requestTimeout, Node default — verified no override) |
An unauthenticated flood holding ~600 concurrent near-cap bodies approaches the 16 GiB host budget; a sustained drip-pace flood (each body transmitted slowly within the 300 s window) maintains that working set indefinitely. The fd ceiling bounds this below the naive ∞ but is not a memory-exhaustion control at these sizes — agreeing with the maintainer's analysis. This is a genuine memory-exhaustion vector, not bandwidth/CPU-only.
What stands unchanged from the verified-controls table
Node 20.20.2 with default timeouts; no published ports (tunnel-only ingress); Cloudflare edge in path (CF-RAY); 400/401 live probes; DB/Redis/GitHub-API untouched before HMAC; GitHub retry interaction argument. Cloudflare zone-side protections remain unverified from the host — if the zone has effective rate/concurrency controls, the flood math above changes materially; that verification is an operator-dashboard action.
Revised recommendation (for the maintainer's decision)
Formal risk acceptance is not supported by the current record — the previous recommendation is withdrawn. The options that survive the corrected math:
- Narrow compensating control (now materially justified): in-flight webhook-body concurrency cap — reject with 503 when more than N webhook bodies are concurrently streaming/buffered. Sized by budget: N=16 bounds worst-case webhook buffering to ~400 MiB (+ concat transients) on the 16 GiB host; N=64 to ~1.6 GiB. Sequential legitimate deliveries (GitHub's burst/retry pattern is sequential per hook) are unaffected at any of these N. Threshold + GitHub behavior verification = separate implementation decision, per the directive.
- Alternative/complementary: reduce the per-connection cap. Real GitHub webhook payloads are KB-scale; 25 MiB was already generous. A 4 MiB cap cuts the worst-case aggregate 6×. Changes the deployed fix(10): streaming 25MiB webhook body cap — explicit disposition, swallowed late errors, no blanket listener removal #457 contract — separate decision.
- Retain-with-acceptance only after (a) Cloudflare zone-side protections are verified effective by the operator, or (b) the maintainer explicitly accepts memory-exhaustion DoS as within the threat model for this single-operator deployment.
No dismissal or configuration change made; #10 remains open.
#425 completion record + #10 read-only evidence updateRemediation tranche complete (master
|
| Unit | PR | Master SHA | Chain |
|---|---|---|---|
| #5 escaping v2 | #472 | 075318d |
CI ✓ CodeQL ✓ Deploy ✓ /health exact |
| #1+#2 fence scanner | #469 | 5079945 |
CI ✓ CodeQL ✓ Deploy ✓ /health exact |
| #3 findings scanner | #470 | 12b5b90 |
CI ✓ CodeQL ✓ Deploy ✓ /health exact |
| #4 no-op removal | #471 | 4960456 |
CI ✓ CodeQL ✓ Deploy ✓ /health exact |
CodeQL states after re-analysis (API-inspected, zero manual dismissals): #1 fixed, #2 fixed, #3 fixed, #4 fixed, #5 fixed. Open = #10 only.
#10 evidence update (read-only; corroborating the interim review)
1. Recovery-mechanism gap — corroborated in code. The webhook_deliveries table is only ever READ (webhookDeliveries.js routes); no redeliver call to the GitHub App deliveries API (POST /app/hook/deliveries/{id}/attempts) exists anywhere in the backend. No scheduled job polls failed GitHub-side deliveries. The maintainer's finding stands: a request rejected at ingress never produces an ordinary delivery record, so the dashboard cannot see 503-rejected deliveries, and nothing in the implementation recovers them.
2. Empirical delivery-rate evidence (new, production DB, read-only). Over 208,162 deliveries recorded since 2026-05-15: peak 218 deliveries in one minute, peak 2,252/hour. Bursts are real, not hypothetical. Note this is an arrival-rate figure, not a concurrency figure — legitimate in-flight concurrency is arrival rate × retention time (KB-scale bodies stream in milliseconds), likely single-digit even at the historical peak. Two consequences:
- A concurrency cap sized from arrival rates would be far too small; the cap must be sized from measured in-flight concurrency, which nobody currently measures. A read-only instrumentation step (count in-flight webhook bodies, expose as a metric — no admission control) is the natural first implementation increment when authorized.
- Under the verified no-auto-redelivery contract, a 503 during even a fraction of a 218/min burst means lost business events with no recovery path. The maintainer's sequencing — delivery-recovery demonstration before any cap — is confirmed as necessary, and this measurement strengthens it.
3. Unchanged items. Cloudflare zone-side protections remain operator-dashboard verification (unverifiable from host, both sides agree). Memory math unchanged (per-connection retention incl. Buffer.concat transients; the cap must cover the full retention lifetime). Slot-lifecycle invariant and threshold selection remain design work gated on the recovery mechanism.
No implementation, configuration change, dismissal, or risk acceptance performed. #10 remains open.
Unit #10-B — Delivery-recovery architecture (DESIGN; no implementation) + downstream idempotency assessmentPart 1 — Replay-safety audit of the current webhook pipeline (code-verified at master
|
| Order | Effect on replay | Verified idempotency today |
|---|---|---|
adoptWorker (webhooks.js:87) |
DB adoption rows re-written | Adoption is resolution-based (same principal re-resolved); no duplicate external effect observed — low risk |
createGitwireCheck (webhooks.js:102) |
A second GitHub check run is created on PR open/reopen/ready events | None — Redis setex overwrites the same key, but the check-run creation itself already happened on GitHub — direct duplicate external effect |
routeWebhookToQueue (webhooks.js:132) |
Per-event handlers run inline within the request (webhookHandlers/index.js:89); only unhandled event types enqueue — and the generic enqueue (index.js:92) uses no BullMQ jobId, so duplicate jobs are possible for those |
Per-handler audit below |
evaluateAndExecuteCustomRules (webhooks.js:138) |
Custom-rule actions re-execute (comments, labels, status effects via the P1 identifiers-only boundary) | Action executors have per-action guards of varying strength — not delivery-scoped; a replay re-matches and re-acts |
evaluateQualityGates (webhooks.js:159) |
Gate evaluation re-runs; Telegram notify re-fires | Evaluation is read-mostly; notify is non-critical — low risk |
| delivery-record insert (webhooks.js:198) | no-ops (ON CONFLICT) |
The only delivery-scoped guard — and it is last |
Conclusion: automatic redelivery must NOT be enabled against the current pipeline. The maintainer's caution is confirmed and sharpened: the record insert does not merely fail to "by itself" prevent earlier duplicate operations — it is structurally the final effect, so nothing upstream is delivery-deduped today.
Required replay-safety prerequisite (first implementation increment when authorized): hoist a delivery claim to the top of the handler — the same INSERT … ON CONFLICT (delivery_id) DO NOTHING with RETURNING id, placed immediately after HMAC verification and JSON parsing; if no row is returned (GUID already processed or in flight), respond 202 without replaying any effect. Two design details: (a) the claim must be released or marked-unprocessed if the request later fails before its effects complete (else a crash mid-handler permanently swallows that delivery — the failure-behavior requirement); (b) concurrent duplicate attempts of the same GUID (GitHub-side retry racing an in-flight request) are exactly-once'd by the unique index — the loser gets a terminal 202 without effects, which is safe because the winner is still processing.
Downstream-of-queue idempotency (for replayed queue jobs, relevant once redelivery exists): workers keyed by delivery/job identity vary — triage/comment paths use marker-based find-before-post (findCommentByMarker); check runs are owned per-job (check-run lifecycle P1); the phase4 review path has same-SHA recovery semantics. A per-worker idempotency table (job key → completion state) is the general answer if the generic no-jobId enqueue path is ever relied on under redelivery; the delivery-claim removes the need for it at ingress.
Part 2 — Recovery architecture (design; every requirement mapped)
Authentication & authority. Discovery and redelivery use GitHub App JWT auth (GET /app/hook/deliveries, POST /app/hook/deliveries/{id}/attempts), which getWebhookApp() already provides for App-level operations — distinct from installation tokens; no new credential class. Redelivery requests are write operations against GitHub — they must sit behind an explicit authorization boundary (operator HTTP surface with audit attribution per the OA-01 pattern), not run ungated on a timer from day one.
1. Discovery. Scheduled poller (BullMQ repeatable job, e.g. every 15 min) pages GET /app/hook/deliveries?per_page=100&cursor=… over the 3-day redelivery window only — older entries are unredeliverable and are recorded as permanently lost (failure-behavior requirement) rather than silently skipped. Each entry carries id, guid, status, action, delivered_at.
2. Identity. Correlate by guid across attempts (GitHub's own model). Local projection table webhook_recovery_deliveries (guid PK, github_delivery_ids[], event, status_history, first_seen_at, last_checked_at).
3. Deduplication. A GUID is resolved iff any attempt is recorded in webhook_deliveries (the ingress claim above makes that table the single source of "we processed it"). Unresolved = present in GitHub's 3-day window with no successful local record. Resolved GUIDs are never redelivered; GUIDs whose GitHub status is already succeeded but absent locally (e.g., rejected pre-claim by a future admission cap) are the redelivery candidates — the exact set the concurrency cap would otherwise lose.
4. Replay safety. Prerequisite Part 1 (ingress claim) blocks duplicate effects; queue-side job identity is then single-attempted per GUID by construction.
5. Persistence. The projection table above + a webhook_recovery_state singleton row (poll cursor high-water mark by delivered_at, not list position). Both in the app's existing PostgreSQL — same durability class as the rest of the control plane.
6. Retry policy. Per-GUID redelivery attempts capped (default 3, configurable), exponential backoff (15 m / 1 h / 6 h) inside the 3-day window; GitHub rate-limit responses (x-ratelimit-remaining low / 403 with Retry-After) back off the whole poller, never counted against a GUID's attempt budget.
7. Recovery confirmation. A POST …/attempts 2xx means accepted, not delivered-processed. Confirmation closes the loop only when a subsequent poll sees the GUID's newest attempt succeed and the local claim records it. Until both, the GUID stays "in recovery."
8. Authority. Poller runs as the App identity (read-only discovery); redelivery actions require the operator-gated path (OA-01-style audited HTTP with principal attribution). Config toggle default-off; enabling is an explicit, logged operator decision.
9. Observability. /health-adjacent block + existing dashboard patterns: recovery backlog size, oldest unresolved GUID age, per-GUID exhausted-attempt count, poller last-run/next-run, rate-limit backoff state. Alerts (log-error level) when backlog > threshold or unresolved age approaches the 3-day boundary.
10. Failure behavior. Poll failure → retry with backoff, error surfaced in observability, no skip-forward of the cursor (lossless at-least-once discovery). Persistence failure → poller pauses (no redelivery decisions without durable state). Redelivery POST failure → attempt not consumed unless GitHub returned 2xx; API errors retried per policy; exhausted GUIDs are marked unresolved_exhausted and reported, never silently dropped — the terminal state an operator must see.
Sequencing dependency: #10-A's telemetry (PR #473) defines the load this poller's own requests add (negligible: ≤ ~5 paginated reads per 15 min) and, later, gives the evidence for #10-C's threshold. The ingress claim (Part 1) is the only prerequisite that touches the hot path and should be its own small unit, reviewed separately from the poller.
No implementation, no live redeliveries, no configuration changes performed under this design unit.
#10-B — REVISED recovery architecture (supersedes the recovery section of comment 7059178276; replay-safety audit stands as accepted)The maintainer's three findings are each correct and each changes the architecture. The revisions below follow the required decomposition. B1 (CRITICAL) — Claim is not completion: durable delivery lifecycle statesThe v1 design's single claim row conflated acquisition, processing, and completion. The corrected model (unit #10-B1, design): State machine per delivery GUID (one row,
Ownership and recovery semantics: a claim is a lease (owner id + deadline, renewed on progress), not a boolean. Lease expiry mid- Exactly-once is claimed for NOTHING that crosses the process boundary. The unique GUID constraint provides exclusive acquisition only. For every external effect, the design must state its own idempotency or reconciliation path before automatic replay is enabled:
The false-acknowledgement risk (a concurrent duplicate receiving 202 while the original attempt is in flight) is closed by making the duplicate's response truthful: a duplicate that finds the row B2 (HIGH) — Redelivery eligibility corrected (the v1 matrix was inverted)Confirmed: an admission-cap 503 produces a failed GitHub delivery, not a successful one; the v1 sentence ("succeeded on GitHub but absent locally" as the candidates) described the rare inconsistency case, not the recovery driver. Corrected decision matrix (unit #10-B3 design adopts it verbatim):
Local B3 (HIGH) — Ambiguous redelivery outcomes: intent-persisted submissionsCorrected attempt protocol (unit #10-B4 design; implementation held): before any
Retry budgets are consumed only by confirmed rejections; ambiguous outcomes are resolved by reconciliation before any budget decision — closing the double-submission failure mode. #10-B3 discovery — the required edge casesPagination under sustained bursts (cursor walk with per-page GUID upserts, no assumption of ordering stability); checkpoint timestamp collisions (cursor = Sequencing (as directed)
Governing invariant (adopted verbatim): GitWire must neither lose a delivery nor repeat an irreversible mutation merely because a request disconnected, a worker crashed, or an external API response was lost. No implementation, no live redeliveries authorized in this round. |
#10-B2 — Effect-by-effect replay-safety and crash-recovery design (DESIGN; authorized) + resolutions to the four architectural conditionsPart 1 — The effect audit (actual crash boundaries examined)Classification key: TA = transactionally atomic (effect and lifecycle record in one DB tx) · ID = idempotent (safe unconditional replay) · RC = reconcilable (external state discoverable; adopt-don't-duplicate) · DT = duplicate-tolerant (bounded, visible duplication acceptable) · UR = unsafe for automatic replay (operator/reconciliation path only).
Classification of the pipeline as a whole: ingress becomes safe-by-construction for rows 1/3/5/8/9; rows 2/4/6/7 require the per-effect records above before automatic replay is enabled anywhere. Until then, Part 2 — The four architectural conditionsB1.1 — Durable acceptance includes recoverable work (transactional inbox). Adopted: the B1.2 — Fencing. Adopted: the lifecycle row carries a monotonically increasing B3.1 — Discovery identities. Adopted as specified, four distinct identities: delivery GUID (logical event correlation), GitHub delivery id (individual attempt identity — the unique component of discovery persistence and poll checkpoints; the cursor becomes B4.1 — Budget semantics corrected (previous "rejections only consume" was wrong). Adopted verbatim:
The unlimited-retry hole is closed: an accepted redelivery whose subsequent delivery keeps failing burns the budget and terminates at The three truths (governing invariant, restated)Durably accepted (lifecycle row + recoverable payload), externally executed (per-effect records + reconciliation), and locally completed (the No implementation authorized this round; #10-B4/B5 remain held; no live redeliveries, admission changes, dismissals, or risk acceptance. |
#10-B2 — COMPLETED: implementation specification (DESIGN; no implementation) — B2-F1 and B2-F2 incorporatedPart 0 — What this completes, and what it does not
Part 1 — Ground truth (verified in the code at master
|
| Fact | Where |
|---|---|
| Ingress order: verify, parse, sanitize, then — all before the 202 — create check run, route to queues, run custom rules, run quality gates | routes/webhooks.js:60, 74, 85, 114, 135, 140, 168, response at :211 |
The delivery row is inserted last, with ON CONFLICT (delivery_id) DO NOTHING; nothing consults it before effects run |
routes/webhooks.js:201–204; table in db/migrations/001_initial_schema.sql:113 |
Deduplication is Redis-only and time-bounded: checkAndMark marks before processing (TTL 1 h) in phase4Worker, ciHealWorker, issueFix; the lease lifecycle exists for triage only |
services/idempotencyService.js:61, 224, 271, 298; callers at workers/phase4Worker.js:156, workers/ciHealWorker.js:260, workers/issueFix/submit.js:169 |
| The ingress check-run pointer lives in Redis for 24 h | routes/webhooks.js:124–125; read by services/checkRunFinalizer.js:21 |
18 enqueue sites across 8 handlers; a BullMQ jobId is set at exactly one |
lib/webhookHandlers/*.js; the one is handleWorkflowRun.js:66 |
Queue retention drops finished jobs: removeOnComplete 500, removeOnFail 1000 |
packages/runtime/src/create-queue.js:41–42 |
Four sites create check runs, none sets external_id |
lib/checkStatus.js:35, services/aiReviewService.js:112, services/configValidationService.js:50, services/qualityGateService.js:551 |
| The quality gate adopts a check run by name only, taking the first match | services/qualityGateService.js:528–545 |
No encryption helper and no transaction helper exist in packages/web/src; raw BEGIN/COMMIT appears twice |
repository search |
Latest migration is 049; repeatable BullMQ jobs are an established pattern |
db/migrations/; workers/syncWorker.js:59, workers/phase3Worker.js:152 |
Three properties of the GitHub API, checked read-only against this repository:
- A check-run object carries
external_id. GitHub Actions already fills it with a bare UUID, so GitWire needs its own namespace prefix. check_suite.appcame backnullfor every run in a listing and on a direct fetch. App identity must therefore come from the server-sideapp_idfilter, which behaved correctly: 19 runs for the Actions app, 0 for a foreign app id.- GitWire's own runs (
GitWire,GitWire AI Review) exist on PR heads today with an emptyexternal_id.
Part 2 — B2-F2: one durable record per effect, with the three facts kept apart
Intent, confirmation, and uncertainty are separate durable facts at the effect level, exactly as acceptance, execution, and completion are at the delivery level.
| State | Meaning | Written when | Replay consequence |
|---|---|---|---|
intent |
An owner has committed its intention to perform the effect; the outcome is not yet known | Before the external call, in its own committed transaction | Not replayable |
confirmed |
The external system confirmed the effect | The owner receives a definite success response | Never replayed; terminal |
uncertain |
The outcome is unknown: the owner stopped between intent and a definite answer | A sweep finds an intent whose owner lost its lease |
Not replayable; resolved only by that effect's discovery |
not_executed |
Proven that the effect did not happen | Either a refusal whose status guarantees that no object was created, or discovery proving absence | Replayable, under the attempt budget |
Rules:
- F2-1. The
intentrow is committed before the call and carries theowner_generationthat is about to act. - F2-2. Only that same generation may move
intenttoconfirmedornot_executed. The transition is a conditionalUPDATE … WHERE owner_generation = $g AND state = 'intent'. - F2-3. An
intentrow seen without a live lease isuncertain. It is never read as "not done". - F2-4. No row means never attempted. This is distinct from every state above.
- F2-5.
confirmedanduncertainboth block replay. A delivery whose effects are all inconfirmedornot_executedmay be resumed; one with a singleuncertaingoes toreconciliation_required.
Crash boundaries for one external effect:
| Process stops… | Durable state found | Resolution |
|---|---|---|
| before the intent commit | no row | replay freely |
| after the intent commit, before the request is sent | intent → uncertain |
discovery |
| after the request is sent, before a response | intent → uncertain |
discovery |
| after a success response, before the confirm commit | intent → uncertain |
discovery finds it |
| after the confirm commit | confirmed |
skip |
Part 3 — B2-F1: check-run identity that cannot be mistaken
Rule F1-1 — identity at creation. Every check run GitWire creates carries an external_id in a GitWire-only namespace.
Rule F1-2 — lookup by identity, never by name. A lookup is GET /repos/{o}/{r}/commits/{sha}/check-runs?app_id=<GitWire App>&check_name=<name>, then an exact external_id match. The app_id filter is what establishes ownership; the name alone does not.
Rule F1-3 — adopt only on exactly one match. Zero, one, or several matches mean three different things, and each has one allowed response:
| Matches | Meaning | Allowed response |
|---|---|---|
| 1 | this is the object | adopt it; persist its id on the effect row |
| 0, inside the visibility grace window | unknown — GitHub's listing may lag a creation | look again; treat as uncertain |
| 0, after the grace window | never created | not_executed; the effect may be replayed |
| 2 or more | a defect: two objects exist under one identity | reconciliation_required; no object is chosen |
legacy runs without external_id |
not identifiable | never adopted automatically; listed for the operator |
The earlier "oldest owned run" rule is withdrawn. Picking one of several is a guess that can bind a delivery to the wrong check run.
Two classes of object, because the four creation sites differ:
| Site | Name | Class | external_id |
|---|---|---|---|
routes/webhooks.js:114 |
GitWire |
one per delivery | gw1:d:<delivery_guid> |
services/aiReviewService.js:112 |
GitWire AI Review |
one per review execution | gw1:r:<review execution id> |
services/configValidationService.js:50 |
GitWire Config Validation |
convergent: desired state per commit | gw1:c:<repo_id>:<sha> |
services/qualityGateService.js:551 |
gitwire/quality-gate |
convergent: desired state per commit | gw1:q:<repo_id>:<sha> |
- A per-delivery object must be unique; Rule F1-3 applies in full.
- A convergent object carries a desired state. Applying the desired state to every match is safe and idempotent, so no choice is made. More than one match is reported as a duplicate.
- The review execution id is the delivery GUID when the job carries one (handlers already pass
deliveryIdin job data,handlePullRequest.js:7) and the BullMQ job id otherwise.
Part 4 — Data model (additive; migration 050)
CREATE TABLE webhook_delivery_lifecycle (
delivery_guid TEXT PRIMARY KEY, -- X-GitHub-Delivery, kept as text
event_name TEXT NOT NULL,
action TEXT,
repo_full_name TEXT,
installation_id BIGINT,
state TEXT NOT NULL CHECK (state IN
('received','processing','completed','retryable_failed',
'reconciliation_required','terminal_failed')),
owner_id TEXT,
owner_generation INTEGER NOT NULL DEFAULT 0,
lease_expires_at TIMESTAMPTZ,
attempts INTEGER NOT NULL DEFAULT 0,
http_attempts INTEGER NOT NULL DEFAULT 1,
payload JSONB NOT NULL, -- the sanitized payload
last_error TEXT,
accepted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
completed_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX webhook_delivery_lifecycle_sweep_idx
ON webhook_delivery_lifecycle (lease_expires_at) WHERE state = 'processing';
CREATE TABLE webhook_delivery_effect (
delivery_guid TEXT NOT NULL REFERENCES webhook_delivery_lifecycle(delivery_guid),
effect_kind TEXT NOT NULL, -- 'check_run.create', 'queue.enqueue', 'comment.create', …
effect_key TEXT NOT NULL, -- the subject, e.g. '<queue>:<job_name>' or '<repo_id>:<pr>:<sha>'
state TEXT NOT NULL CHECK (state IN ('intent','confirmed','uncertain','not_executed')),
owner_generation INTEGER NOT NULL,
attempts INTEGER NOT NULL DEFAULT 1,
result JSONB, -- e.g. {"check_run_id": "<id>"}
error TEXT,
recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
resolved_at TIMESTAMPTZ,
PRIMARY KEY (delivery_guid, effect_kind, effect_key)
);webhook_deliveriesstays. Five other modules read it (routes/webhookDeliveries.js,routes/readiness.js,services/setupService.js,services/repoTransferService.js,services/qualityGateService.js). Its insert moves to the top of the handler, inside the acceptance transaction.- Both delivery identifiers are stored as text. The header value is a UUID string. The numeric
idthat the deliveries API returns is a 64-bit integer that exceeds 2^53, and must never pass through a JavaScript number. - The stored payload is the sanitized one.
sanitizeWebhookPayloadexists to make payloads safe to persist (lib/githubSanitize.js:1–10). - Retention: terminal rows 30 days, then deleted; counts kept as aggregates.
Part 5 — Acceptance and execution
Acceptance replaces the head of the route handler:
- Verify, parse, sanitize — unchanged.
- One transaction: insert the lifecycle row (
received, payload) and the audit row;ON CONFLICT DO NOTHING. - If the row already exists, this is a duplicate: respond 202 with
{ queued: false, state }and perform no effect. - If the database cannot commit, respond 503. Nothing was accepted, and the response says so. Today an insert failure is swallowed and 202 is sent anyway.
- Only after the commit: claim (
processing, generation 1, lease) and execute. The 202 follows the commit.
Execution — the same protocol for the first attempt and for any later one:
for each effect of the delivery's plan, in order:
confirmed → skip
uncertain → stop; lifecycle := reconciliation_required
intent / not_executed / none →
commit intent (generation g)
call the external system
definite success → confirmed, result stored, lease renewed
refusal that guarantees no object was created → not_executed, error stored
timeout, 5xx, or any other outcome → leave intent, stop (becomes uncertain)
all closed → lifecycle := completed, in the same transaction as the last confirmation
- The plan is today's inline sequence, in today's order: repository reconciliation, ingress check run, dispatch to queues, custom rules, quality gates.
- Authority is re-derived at execution from the stored payload through
adoptWorker; it is never cached on the row. - A delivery may end in
retryable_failedonly when no effect isintentoruncertain. - Fencing (B1.2). A former owner that resumes presents a stale generation. Its conditional updates match zero rows, and it stops.
Part 6 — The effect audit, restated with identities and discovery
| # | Effect | Class | Identity (effect_key) |
Confirmation | Discovery that resolves uncertain |
|---|---|---|---|---|---|
| 1 | Delivery record | transactional | delivery_guid |
the commit itself | not needed |
| 2 | Check-run creation (4 sites) | per delivery, or convergent | Part 3 | a success response carrying the run id | list by identity (Part 3): 1 → confirmed; 0 after grace → not_executed; ≥ 2 → operator |
| 3 | Queue enqueue (18 sites + generic) | idempotent while recorded | <queue>:<job_name>; jobId = <job_name>:<guid> |
the returned job id | queue.getJob(jobId). Absence proves nothing — retention removes finished jobs — so the effect row is the authority, not the queue |
| 4 | Comments and reviews | find-before-post | <subject>:<marker> |
a success response carrying the comment or review id | findCommentByMarker; one match → confirmed; none after grace → not_executed |
| 5 | Labels and status | convergent | <subject> |
the API's success | re-apply; converges |
| 6 | Custom-rule actions | per action | <rule>:<index> |
by action type | inherits rows 4 and 5 |
| 7 | PR and branch creation | discovery-based | branch name or title marker | a success response carrying the object id | find by convention; ambiguous → operator. Destructive variants: never automatic |
| 8 | Notifications | duplicate-tolerant | <channel> |
none awaited | none; duplicates bounded by the attempt budget |
| 9 | Database writes | transactional or keyed upsert | row key | the commit | not needed |
Part 7 — Integration points (design only)
| Order | Change | Where |
|---|---|---|
| 1 | New service: accept, claim, record effect, transition | services/deliveryLifecycleService.js (new) |
| 2 | New transaction helper | lib/db.js |
| 3 | Acceptance first; audit row inside the acceptance transaction; effects run under the owner protocol | routes/webhooks.js |
| 4 | jobId on every enqueue; effect rows around each |
lib/webhookHandlers/*.js |
| 5 | external_id at creation; identity lookup |
the four creation sites |
| 6 | Replace the name-only find with the identity lookup |
services/qualityGateService.js:536 |
| 7 | The Redis pointer becomes a cache of the confirmed effect row; a miss is never a reason to create a second run | services/checkRunFinalizer.js |
| 8 | New sweep worker | workers/deliveryRecoveryWorker.js (new) |
What does not change: the Redis idempotency inside workers (checkAndMark, the triage lifecycle). Those stay as they are. The durable layer records what the ingress did; it does not re-architect triage, review, or heal.
Part 8 — The sweep (repeatable, every minute)
- A
processingrow whose lease has expired: everyintenteffect of the lost generation becomesuncertain; the lifecycle becomesreconciliation_required; the generation is advanced. - A
receivedrow older than the grace period: enqueue. Nothing was attempted, so nothing can be repeated. - A
retryable_failedrow past its backoff: enqueue. - A
reconciliation_requiredrow: run each effect's discovery and resolve what it can. Re-execution after resolution is not enabled by this unit; it stays behind a configuration switch that defaults to off.
Part 9 — Test oracle
Every row is a crash injected at one point, with the durable state and the next action asserted.
| Scenario | Expected |
|---|---|
| Stop at each of the five boundaries of Part 2, for a check run, an enqueue, and a comment | the state in the table, each time |
| Duplicate delivery while the first is in flight | 202, queued: false, zero effects from the duplicate |
| Stale owner resumes after losing its lease | zero rows updated; it stops |
| Check-run discovery: 0 (inside grace), 0 (after grace), 1, 2, legacy | look again; not_executed; adopt; operator; never adopted |
Two own gitwire/quality-gate runs on one commit |
desired state applied to both; duplicate reported |
Queue job absent from the store, effect row confirmed |
not re-enqueued |
| Database unavailable at acceptance | 503; no 202; no effect |
| Redis unavailable at acceptance | the row is still accepted; the effects that need Redis are recorded and left for the sweep |
One effect uncertain |
lifecycle reconciliation_required; nothing replayed |
| Lease expires mid-processing | uncertain, generation advanced, owner cleared |
Part 10 — Rollout, one authorization per stage
| Stage | On | Off |
|---|---|---|
| 0 — observe | write lifecycle and effect rows | no gating; today's behavior unchanged; compare with the #10-A counters |
| 1 — duplicates | a duplicate performs no effect | everything else |
| 2 — report | the sweep marks uncertain and reports |
any re-execution |
| 3 — resume | automatic resume for received and retryable_failed only |
uncertain effects |
Part 11 — Decisions needed before any implementation
- Payload storage. The B1.1 text says "encrypted at rest". No encryption facility exists in this codebase. Proposal: store the sanitized payload as JSONB, in the same protection class as the GitHub-derived content this database already holds, with the 30-day retention. The alternative — a new keyed-encryption facility — is a separate unit with its own key management.
- Who executes the first attempt. Proposal: the request handler, as today, so that the PR check run still exists before GitHub receives the 202, and so that the change stays small. The alternative moves every inline effect to a worker: a faster request path, and a larger change.
- Duplicate response codes. Proposal: 202 for every non-terminal duplicate, 200 for
completed. - Retention periods. Proposal: 30 days for terminal rows.
- Grace window for discovery. Proposal: 60 seconds, three looks. This rests on an assumption, not on a documented figure: that GitHub's check-run listing can briefly lag a creation. If the lag is ever observed to exceed the window, a replay could create a duplicate. The window is a safety margin and belongs in configuration.
No implementation is authorized by this comment. #10-B4 and #10-B5 remain on HOLD. No live redelivery, no admission change, no dismissal, no risk acceptance.
#10-B2 — Revision 1: the five decisions and the three conditions (DESIGN; no implementation)This revision incorporates the maintainer's review of comment 7079316288. Where the two disagree, this one supersedes it. Everything else in 7079316288 stands: the effect record, identity-based check-run adoption, the six-state lifecycle, the fencing generation. Still not authorized: any code, migration, worker, or change to the webhook path. #10-B4, #10-B5, redelivery and admission control remain on HOLD. Ground truth added for this revision
Part 1 — The five decisionsDecision 1 — The payload is stored encrypted, with keys that are not in the databaseStored form. The lifecycle row does not hold JSONB. It holds:
The sanitizer is not the control. Because
An alternative is to refuse the delivery (503) when sanitization fails. It is simpler to reason about, and it turns a sanitizer defect into a lost event, since recovery is not built yet. The recommendation is to store with the flag; the choice is the maintainer's. What this encryption does and does not protect against. If the key lives in
Proposed for this unit: the first, with this limit written down. Storage budget.
A residual this unit does not close. BullMQ job data carries the payload in clear in most handlers ( Decision 2 — A worker executes every attemptThe HTTP handler stops executing effects. The sequence is fixed:
Promptness of the check run. Today the
Tests that will need to change. Nine files exercise the route or assert inline behavior: The review approved the architectural choice. It did not authorize building the worker. Decision 3 — Response codes
Decision 4 — Retention
Decision 5 — The search window observes; it does not proveThe rule of comment 7079316288 — "0 matches after the grace window →
Part 2 — The three conditionsCondition 1 —
|
| Moment | Audit row |
|---|---|
| Acceptance | inserted inside the acceptance transaction, with processed = FALSE |
Lifecycle reaches completed |
processed set to TRUE in the same transaction |
Lifecycle reaches retryable_failed, reconciliation_required or terminal_failed |
error set to a short classified code — never payload text |
- Meaning.
processed = TRUEmeans every ingress effect is confirmed, queue hand-offs included. It does not mean the handed-off work has finished (Condition 3). errorbecomes real. The column exists and has never been written: 0 of 208,700 rows.- Readers need no change. Verified for all five:
| Reader | Uses | Effect |
|---|---|---|
routes/webhookDeliveries.js |
counts processed = true; lists the column; counts error IS NOT NULL |
becomes meaningful |
routes/readiness.js:23, services/setupService.js:250, services/repoTransferService.js:90, services/qualityGateService.js:183, 243 |
count rows by repository and time; none reads processed |
none |
Dashboard deliveries/page.tsx |
processed_ok, errors, error_rate, per-row processed |
shows real numbers; today it shows every delivery processed and zero errors |
- History is not rewritten. The 208,700 existing rows keep
processed = TRUEwith the old meaning. They are not backfilled, because the truth for them is not knowable. The dashboard states the cutover date.
Condition 2 — A check-run search is complete, or it is unknown
- The query.
GET /repos/{o}/{r}/commits/{sha}/check-runs?app_id=<GitWire App>&check_name=<name>&per_page=100, every page followed to the end of theLinkchain. - Completeness is checked, not assumed. The number of runs fetched must equal the
total_countof the response. If any page fails to load, or the numbers disagree, the search is incomplete. - An incomplete search is no information. It never produces "absent". A rate-limited or failed look is recorded as a failed look and leaves the effect
uncertain. - Ownership comes from the server. Only runs returned under the GitWire App's
app_idare considered, becausecheck_suite.appwas null in every response examined. Nothing is ever patched or adopted outside that set. - The quality gate stops adopting by name.
services/qualityGateService.js:536takes the first run whose name matches. It is replaced by the identity lookup: none → create; one or more → apply the desired state to all of them and report a duplicate.
Condition 3 — Enqueue is not execution
Three durable facts, never inferred from one another:
| Fact | Means | Recorded by |
|---|---|---|
| Accepted | BullMQ took the job and returned an id | the queue.enqueue effect, confirmed |
| Settled | the job reached a terminal queue state, completed or failed | the sweep, while the job is still in the store |
| Evidenced | the job's own business outcome is durably written | the job |
- Only Evidenced is "work done". A delivery is
completedwhen its hand-offs are Accepted. Itsprocessed = TRUEsays that and nothing more. - A job absent from Redis before its outcome is recorded. The queue cannot tell why. Its retention removes only finished jobs; a crash can lose about a second of writes (
appendfsync everysec); an operator can remove one. The rule: an absent job with no Evidenced outcome islost, and its work item goes toreconciliation_required. It is never enqueued again automatically — it may have run in part, and the workers' idempotency markers live in the same Redis and may have been lost with it. - Each job type must declare its Evidenced probe: the durable record and the predicate that proves it finished. Until a job type declares one, its work items can be Accepted and Settled but never Evidenced, and any loss is visible to an operator only.
- The declarations are not made in this revision. The scope of that step is the 17 job names added by the 18 enqueue sites:
triage-issue,triage-pr,comment-command,ai-review,supersede-review,reconcile-pr,pr-labeled-auto-merge,pr-closed-or-unlabeled,review-submitted,checks-updated,eval-rollback,ingest-test-results,collect-evidence,sync-installation,sync-repo,validate-configs,generic-event. For each, the implementation unit names the business row that proves completion and confirms it against the worker's code. Candidates exist for some — the review row forai-review, for instance — and none is asserted here. - Against B1.1. This design acknowledges a delivery only when its hand-offs are recoverable, because the effect rows name the job ids that were accepted. It does not claim to recover the downstream execution. It makes a loss detectable, and it never turns a loss into a duplicate.
Part 3 — The invariants, consolidated
- Nothing is acknowledged that is not stored recoverably: encrypted, committed, key present.
- A recorded GUID never causes a second execution. Duplicates are answered 202 and counted.
confirmedis never replayed.uncertainis never replayed.not_executedrequires evidence; absence from a listing is not evidence.- No object is adopted by name, and none is chosen among several.
- An effect recorded by a stale generation changes nothing.
processed = TRUEmeans the ingress effects are confirmed, and nothing about downstream work.- An absent job is
lost, never re-enqueued. - A non-terminal record is never deleted.
- Admission is unchanged. No delivery is rejected for a reason that does not exist today, other than 503 when it cannot be stored.
Part 4 — Changes to the schema sketch of 7079316288
| Table | Change |
|---|---|
webhook_delivery_lifecycle |
payload JSONB replaced by the seven columns of Decision 1 |
webhook_delivery_effect |
unchanged; the not_executed state now carries the evidence that produced it (result.evidence) |
webhook_delivery_work (new) |
one row per handed-off job: delivery_guid, job_id, queue, job_name, state (accepted, settled, evidenced, lost, reconciliation_required), evidence |
webhook_deliveries |
unchanged schema; processed and error written as in Condition 1 |
Part 5 — Test oracle additions
| Scenario | Expected |
|---|---|
| No payload key configured | 503; no row; no effect |
| Sanitizer throws | row stored encrypted, payload_sanitized = FALSE; no content in logs |
| Ciphertext moved to another row | authentication fails; the row is unusable, never read as another payload's |
| Key rotated | old rows still decrypt by key id |
| Stop after commit, before enqueue | row received; the sweep enqueues it |
| Check-run effect after acceptance | confirmed inside the latency target in a controlled run |
| Search: second page fails | uncertain; not "absent" |
Search: fetched count ≠ total_count |
uncertain |
| Search: no match after the window | reconciliation_required; no second check run |
| Audit row during processing | processed = FALSE |
| Audit row at completion | processed = TRUE, in the same transaction |
| Job absent with no evidence | work item lost; nothing re-enqueued |
| Deletion offered every state | only completed and approved terminal_failed are deleted |
| Duplicate of an expired delivery | 202, queued: false, state: expired, no effect |
Part 6 — Open for the maintainer
- Sanitizer failure: store with the flag (recommended), or refuse with 503.
- Key placement: environment file on the host (recommended for this unit), a file outside the backup set, or an external manager.
- Budget thresholds: 2 GB warn, 4 GB alert.
- Check-run latency target: p95 ≤ 2 s, p99 ≤ 5 s.
- Local attempt ceiling: 10.
- Whether the Redis copy of the payload in job data becomes its own unit now or later.
No implementation is authorized by this comment.
#10-B2 — Revision 2: the three corrections, the six decisions as adopted, and the design of unit #10-R1 (DESIGN; no implementation)This revision applies the maintainer's review of Revision 1 (comment 7081410825). Where they disagree, this one supersedes it. Not authorized by this comment: any code, migration, worker, or change to the webhook path. Implementation of #10-B2, #10-B4, #10-B5, redelivery and admission control stay on HOLD. Part A — The three correctionsCorrection 1 — Revision 1 listed "an id confirmed earlier now returns 404" as evidence for
Correction 2 — an empty search never permits creation on its own. The rule "none → create" for the quality gate, and for every other creation site, is conditioned on the effect record:
This applies to all four creation sites. For the convergent objects the rest of the rule stands: one or more matches → apply the desired state to all of them and report a duplicate. Correction 3 — a Redis failure after the durable commit does not lose the delivery, and is not reported as a rejection. | Point of failure | Lifecycle row | HTTP | What recovers it |
The second half of this correction: detecting a lost job is not recovering it. A job whose enqueue was One observation from today supports the correction. The review of PR #494 was cut by the deployment of Part B — The six decisions, as adopted
Part C — One order, testableRevision 1 called the check run "the first external effect" while keeping the earlier sequence that puts repository reconciliation before it. One list is now the only reference:
Part D — Per job type: evidence probe and approved recovery pathBoth are owed for every job type before recovery is enabled. Neither is asserted in this revision.
17 job names, added by 18 enqueue sites. For each, the implementation unit names the durable record that proves completion and the procedure that recovers a loss, and confirms both against the worker's code. Part E — Unit #10-R1: queue job data carries references, not payloadsDesign authorized; implementation not. Ground truth, verified at
Design.
Test oracle for the unit.
Out of scope for #10-R1: the workers' own idempotency markers, the BullMQ retention counts, and any change to what a job does with the payload. Part F — State
|
Evidence for the recovery follow-up — a review cut by a deployment, and a misreported acknowledgment (2026-11-22)Two observations from PR #494, appended to the recovery thread at the maintainer's direction. No code change; both are inputs to #10-B2 Part D and #10-R1. 1. An in-flight job does not survive a deployment, and nothing recovers it
This is the hand-off case of Revision 2: the review was Accepted — the queue took the job — and then lost with the container. Detection did not happen, and the recovery path that exists today is an operator command. Part D asks each job type to declare an approved recovery path; for 2. The command parser and the "nothing dispatched" acknowledgmentAt 16:27:19Z the bot posted on #494: "No workers could be dispatched. The repository or PR data could not be resolved. Check that GitWire is properly configured." The production log shows the cause:
The next comment on that pull request, written without the literal prefix, drew no reaction — which confirms the cause. What the two observations mean for the design
|
Verification note on the evidence above, and the Redis baseline (2026-11-22)Correction of methodIn the evidence note above, the sentence "the phase-4 queue is empty" was written from a query that returned nothing because it used an option
No waiting or active job — the statement stands. The same broken query had also been used earlier in a production inspection; nothing else in today's records relied on it. Baseline for unit #10-R1: payload copies held in Redis todayRead-only, from production Redis at about 17:12Z. Counts only; no content was read out. 100 jobs were sampled from each set of every queue (the whole set where it holds fewer), and each sampled job's data field was tested for three markers: a
This is the number the second gate of #10-R1 is measured against. |
#10-R1 — the two open gates (DESIGN; no implementation)The maintainer accepted #10-R1 as a specification with two gates unmet. This comment fills them to the extent the code allows today. It authorizes nothing: no migration, no recovery worker, no change to webhook acceptance. How the facts below were obtainedThe nine worker files were traced read-only at Gate 1 — Evidence and recovery path for each job typeThree things decide whether a lost job can be put back on the queue without judgement:
Tally. Of the 17 job names:
What "approved" still requires. For the six that need judgement and the two that are guarded, one of two things per job type:
Choosing between them is the maintainer's decision. Building either is on HOLD.
|
| Queue | Retained jobs | Carries | Share in the sample |
|---|---|---|---|
webhook-events |
500 | full webhook payload | 100 of 100 |
phase2 |
1,500 | full webhook payload | 100 of 100, both sets |
triage |
970 | full webhook payload | 100 of 100, both sets |
ci-healing |
500 | full webhook payload | 100 of 100 |
phase3 |
1,500 | pull-request or repository object | about 97 of 100 |
phase4 |
504 | pull-request object | 96 of 100 |
| eight other queues | 6,284 | none of the three markers | 0 of 100 |
11,758 jobs are retained; about 5,400 carry a payload or a large object. The method is limited to those three markers: "none found" is not proof that a job holds no other sensitive content.
The three producers that are not one webhook delivery
| Producer | Jobs | What its job data holds |
|---|---|---|
the manual run (commentCommands/handleManualRun.js:30, 72, 143, 162, 175) |
triage-issue, triage-pr, ai-review |
the comment delivery's payload with action: "manual-run", and a pull request fetched from the API |
the API route (routes/phase4.js:245–249) |
ai-review-manual |
a pull request fetched from the API, plus repository and installation objects |
schedulers (workers/phase3Worker.js:151–163, others) |
fleet and nightly jobs | no payload |
Decision proposed
Every job payload that is not one webhook delivery gets its own encrypted row, in the store of Revision 2, under a generated id with its origin recorded. The row holds exactly what the job data holds today.
- The job then carries
payloadRefand its routing scalars, like every other job. - For the manual run, the row also records the comment delivery it came from, so the lineage stays traceable.
- This closes the open point of Revision 2 Part E: a manual run neither borrows the comment delivery's row nor goes without one.
- The alternative — fetching again at execution — changes what a job works on, and is not proposed.
The proof, in three layers
- At the producer. One enqueue function. It rejects a job whose data holds a payload-like key, so an inline payload cannot be enqueued by mistake.
- In CI. A test for every enqueue site that inspects the serialized job data.
- In production, read-only, before and after — the method of the baseline above, with a target of zero in every queue, including the three producers' queues. Then the files on disk: after the last old-format job is gone, one AOF rewrite, and a count of payload markers in the AOF and in the snapshots, also zero.
The hard part: what is already there
The 5,400 jobs do not go away by themselves. Terminal jobs keep their data until the count-based retention pushes them out, and a failed set turns over only when newer failures arrive — the 470 failed triage jobs, for instance, can stay indefinitely. Three ways to clear them, none authorized:
| Option | What it does | Cost |
|---|---|---|
| strip the payload fields from terminal jobs in place | keeps the job, its state and its error | a write to every affected job hash in Redis |
| delete the job hashes created before the switch | simple | loses the evidence in failed jobs |
| wait for retention | no action | not bounded in time |
A decision is needed on which, and on when the one-off AOF rewrite may run.
State
| Gate | State |
|---|---|
| 1 — evidence and recovery path per job type | evidence recorded for all 17; recovery path proposed, approved for none |
| 2 — manual and API payloads | decision proposed; proof procedure defined; baseline measured; clearing of existing copies undecided |
| implementation of anything above | HOLD |
#10-D — Recovery contract tests, manual procedures, and the Redis cleanup procedure (DESIGN; nothing implemented, nothing written to production)Design only, under the decision of 2026-11-22: recovery paths are approved for none. The design of the recovery test may continue. The two marker-guarded types get manual reconciliation first. The six types that need judgement get manual recovery only. Production writes, job deletion and the AOF rewrite stay on hold. This comment authorizes nothing. It builds on the classification in the gates record (comment 7082971820). How the facts below were obtained
1. The recovery contractThree statements must hold before a job type may be put back on its queue without judgement.
Four rules bind every recovery path, automatic or manual (maintainer, 2026-11-22):
2. Recovery contract tests for the eight safe job typesEach type gets the same test, with its own identity, evidence and oracle. The last column is what makes the test fail if the type stops being safe.
The test, step by step, for each of the seven types
The suite passes when all seven steps hold for all seven types. The harness
Where the tests live, and the CI job with database and Redis services that runs them, is part of the implementation proposal. It is not made here. 3. The two marker-guarded types: manual reconciliation first
4. The six types that need judgement: manual recovery onlyFor each type the procedure checks the previous effect first. The three outcomes are the same every time: found means confirmed and nothing is run again; clearly absent means the listed path may be used; unclear means uncertain and the operator decides.
5. The Redis cleanup procedureOrder matters: nothing is removed from a job until an encrypted copy of what is removed exists and has been read back.
Design decisions inside the procedure:
6. Copies that live outside the live keysThe cleanup above reaches the live keys. Other copies of the same payload exist, and they do not go away with it.
Retention and expiry policy (proposed; each point is a decision)
7. What has to exist before any of this runs
State
|
#10-D — Revision 1: three corrections, the decisions as adopted, and the backup inventory (DESIGN; nothing implemented, nothing written to production)Under the maintainer's review of comment 7085246710 (2026-11-22). This revises that design and answers the review. It authorizes nothing beyond what the review did: designing the contract tests, designing the strip of terminal jobs, and a read-only inventory of the backups. How the facts below were obtained
Correction of an error in comment 7085246710That comment states that How the error happened: I searched two files with one command and kept the first eight lines of the output. The search tool in my shell returns the matches of several files in no fixed order, so the eight lines were all from Everything below uses the corrected fact. 1. Absence of evidence is not evidence of absenceThe review: no Redis marker and no completion record does not by itself prove that a job did not run. That holds first for Rule adopted.
The contract tests take one more step because of this. For every type, P7 becomes: remove the job from the scratch queue, and require the classification to be 2. What the strip covers, and what it leaves aloneThe review chose the strip in place of the data of completed jobs, with the state and the error kept, on the condition that an isolated test passes first.
Before any strip in production, three proofs, each in an isolated environment:
The AOF rewrite stays a separate authorization after all three. 3. Inventory of the backups of Redis
Facts read:
The exception
That archive is the source of the validator image recovery. It also holds the Redis data of 2026-11-21 in clear. Two facts, one file:
By the review's rule, the condition is not declared complete while that archive is kept. It stays recorded as open, and it needs either the protection of that archive or a separate decision on how long it is kept. Setting the flag is a write to the Proxmox host. It was not made. The three questionsIs there a restorable copy of Redis? Yes. Three kinds: the live files in the volume, ten daily RDB files whose newest and oldest open cleanly, and the seven vzdump archives. A restore was not attempted. Is it consistent in time with PostgreSQL? Not atomic, but close in the file backup, and not checked in the vzdump.
Can the job state be restored without running an undetermined effect again? Not by starting the workers on a restored queue.
A restore therefore needs the rules of section 1 applied before any worker starts: workers stopped, every job in the wait, delayed and active lists classified against the durable evidence, Proposed: the isolated restore testA synthetic queue in a CI job, with no production data: a Redis service, a BullMQ queue, jobs in each state, an RDB saved while one job is active, the RDB loaded into a second Redis, workers started, and a count of how many jobs run a second time. It shows the three rows of the table above with numbers. It needs a test file and a CI job, so it needs the authorization to write them. A restore test with real data should not run until the venue is decided, because it means a copy of the payload data on some host. Two observations, outside this design
State
|
#10-R1 — the 2026-11-21 archive is protected: a long-term retention exception (2026-11-23)Done under the maintainer's approval of 2026-11-23: protect that one archive, by the official Proxmox mechanism, and nothing else. This comment records what was done and what it means for the design. What was done
The flag has the effect intendedThe host has a read-only preview of pruning. It was asked for CT 115 with three window sizes:
Two things follow. The archive survives every rotation until the flag is removed. And it takes no slot: with a window of 6, the six other archives are all kept and the protected one stands apart. The previews were reads. The prune endpoint of this version separates the preview, a What this means for the design
Not done
|
#10-R1 — the synthetic restore trial passed; the plan for the real-data trial (2026-11-23)The synthetic trialBranch The states at the snapshot were as designed:
The assertion of the trial, Three earlier attempts of the trial failed on the harness, not on the finding: a fixed completion list, then a workflow branch filter that did not match the new branch, then a wrong reading of the delayed score. The runs were 45115488689, 45116295800 and the v2 push that the ruleset refused. The plan for the trial with real dataFor approval. The venue is settled by the review of 2026-11-23: a new, isolated container on the Proxmox host, with storage of its own. Nothing below touches CT 115.
Space: the two files are about 136 MB together; the restore of PostgreSQL needs roughly the same again. The 10 GB disk holds both with room. What this trial will not show: that a restored queue is safe to start workers on. The synthetic trial above already showed the opposite, and the review forbids real workers on restored data. State
|
#10-R1 — the trial with real backup data: levels 1 and 2 passed (2026-11-23)Done under the approval of 2026-11-23: levels 1 and 2 only, in an isolated container on the Proxmox host, without workers and without any connection to production. This comment records what was done, what was measured, and what the trial showed about the existing restore path. The lab
Why Ubuntu's Redis was not used: the file is in RDB format version 12, and the Redis of the distribution is 7.0.15. Level 1: the files are sound
Level 2: both restoreRedis.
179 job hashes are in none of these sets; 161 of them are in PostgreSQL. A fresh cluster cannot restore this dump as it is. The first attempt stopped at the first privilege statement:
The two files are not one atomic snapshot
What the trial showed about the existing restore pathRead from
One more fact for the Redis step: the file can be read only by Redis 7.4 or later. Removal
Errors of mine during the trial
What this shows and what it does notIt shows that both files of one dated backup are sound, and that both restore into a fresh, isolated environment with the engine versions of production. It does not show that workers can be started on the restored queue. None was started, and the synthetic trial showed which jobs would run again. State
|
Summary
v9 of the limiter identity remediation chain: #460 → #462 → #463 → here. One surgical correction over #463 (v8); everything else carried unchanged. Supersedes #463.
What this round fixes
The #463 review's finding 2 pointed at
auth.js's comment "Extract key from header or query param" — no query-parameter authentication path exists (zeroreq.queryreads in auth.js; the header is the only in-band key channel). The stale line predates this chain (introduced at 39826c9) but was preserved by the v8 refactor, so it is corrected here rather than left to mislead the next reader into designing a limiter identity for a channel that does not exist.That is the only change in this PR.
The chain this PR carries (from #460/#462/#463, all held and superseded)
/api/auth/*and/api/bootstrap/*always key the limiter on the request IP (8 path-form regressions: case, trailing slash).extractBearerToken()(bearerToken.js) called by bothapiKeyAuthandderiveLimiterIdentity; 12-case corpus contract test pins the one recognition rule both depend on.Adjudication of the #463 review (5 findings)
parsed.error.issues,.refine(fn, "msg"),z.coerce); covered by green suites (config-validator, ci-heal-job-service, issue-fix-analysis-safety). Bundling is deliberate: the master-push CI failed on all 7 advisories at once (fix(10): streaming 25MiB webhook body cap — explicit disposition, swallowed late errors, no blanket listener removal #457 deploy skip); this chain clears the deploy blocker in one unit.extractBearerToken()performs no secret comparison (prefix slice + trim only). The one comparison,keys.has(providedKey)in auth.js, is unchanged by this refactor and pre-dates the chain. (Practical note: API keys are high-entropy random values; Set-membership timing does not practically leak them.)Verification
mergeStateStatus: CLEANat e4b17b7