Skip to content

fix(auth): remove stale query-param comment — limiter identity chain v9 - #464

Merged
Alajmah merged 3 commits into
masterfrom
security/limiter-identity-v9
Nov 20, 2026
Merged

Alajmah merged 3 commits into
masterfrom
security/limiter-identity-v9

Conversation

@Alajmah

@Alajmah Alajmah commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

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 (zero req.query reads 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)

  1. Pre-auth family coverage — /api/auth/* and /api/bootstrap/* always key the limiter on the request IP (8 path-form regressions: case, trailing slash).
  2. Structural Bearer lockstep — shared extractBearerToken() (bearerToken.js) called by both apiKeyAuth and deriveLimiterIdentity; 12-case corpus contract test pins the one recognition rule both depend on.
  3. Advisory remediation — next 16.4.6 (dashboard, middleware→proxy.ts rename, @next/swc aligned) + 15.5.28 (demo-dashboard, manifest+lockfile synced), body-parser 1.20.9, zod ^4.6.6. Both dashboard builds verified green locally.

Adjudication of the #463 review (5 findings)

  • F1 [low] zod major without migration changes — verified compatible: consumers use only v4-stable APIs (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.
  • F2 [low] query-param auth has no limiter counterpart — premise was a stale comment, not code; fixed in this PR (the only change).
  • F3 [medium] pre-auth identity from attacker-controlled header enables rotation — premise false, and explicitly verified by three dedicated regressions: login end-to-end (130 rotating random Bearer tokens → ONE shared IP bucket, 429 at request 121), AUTH-CHECK (rotating Bearer + valid session → ONE bucket), BOOTSTRAP-STATE (anonymous rotating → ONE bucket), plus the PRE-AUTH OVERRIDE contract test (even a well-formed valid Bearer keys the IP on all four family paths). The reviewer's own ask ("needs explicit verification of the invalid-token fallback path") is exactly what those tests do.
  • F4 [low] per-IP pre-auth limits can lock out shared-NAT users — the trade-off is real and accepted: 120 req/min/IP on login/bootstrap is the intended brute-force tightening. The alternative (per-credential buckets before authentication) is the bypass this chain closes. This is a design decision for the maintainer, not a defect; a higher pre-auth threshold is a one-line follow-up if wanted.
  • F5 [low] helper comparison not constant-time — misattributed: 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

  • v8 checks: 20 pass + 1 expected skip, mergeStateStatus: CLEAN at e4b17b7
  • This round: comment-only change, no behavioral surface; gates re-run on this head

…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>
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-20T20:38:26.209590Z
We couldn’t complete this review. Comment @codex review to try again.
d3f3fa2 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@gitwire-hq gitwire-hq Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@Alajmah

Alajmah commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Review adjudication (all 4 findings) — evidence-closed, none blocking

Verdict 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 app.js mounts (app.js:87 /api/auth, app.js:93 /api/bootstrap) and the limiter's prefix regex. The structural fix — one shared PRE_AUTH_PREFIXES constant consumed by both — is a bounded follow-up. Recorded threshold: any change to the pre-auth mount set (or a third family) must extend the limiter family regex and its regressions in the same unit.

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:

  • No trust proxy is configured anywhere (grep over app.js/index.js: zero hits), so Express ignores X-Forwarded-For entirely; req.ip is the raw socket address. An attacker cannot influence it with headers — there is no XFF path to spoof.
  • Empirical check just now: three anonymous requests from an external client through the Cloudflare tunnel minted exactly one key — ratelimit:::ffff:172.18.0.3 — the tunnel connector's Docker address. req.ip in production is the tunnel container's address, not the client's.
  • Consequence (the honest mirror of this finding): all tunnel traffic shares ONE anonymous/pre-auth bucket (120 req/min global). This is pre-existing for anonymous callers (bearerToken || req.ip predates this chain); this chain only extends shared-bucket treatment to Bearer-carrying requests on pre-auth routes — which is precisely the rotation bypass being closed. No availability regression: an attacker could already saturate the shared anonymous login bucket before this change.
  • Follow-up decision parked for the maintainer, not this unit: configuring app.set('trust proxy', …) keyed to cloudflared's XFF would give per-client-IP buckets; that is a separate design decision with its own trust-boundary analysis (any container on gitwire-net could then forge XFF).

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:

  • rate-limiter-identity.test.js:114 — END-TO-END: 130 POSTs to /api/auth/login with a fresh random Bearer per request → counts.size === 1, value 121, 429 at request 121.
  • :164 AUTH-CHECK — rotating Bearers + valid session cookie on /api/auth/check → ONE bucket, 429@121.
  • :187 BOOTSTRAP-STATE — anonymous rotating Bearers on /api/bootstrap/state → ONE bucket, 429@121.
  • Plus the PRE-AUTH OVERRIDE contract test (well-formed valid Bearer still keys the IP on all four family paths).

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 req.query reads in auth.js, in this or any recent revision (the line dates to 39826c9). It recorded no decision; there is no SSE/websocket feature and no rejected query-param design to memorialize. Inventing a decision record for a design that never existed would be fabrication. If a query-param auth channel is ever genuinely proposed (e.g., for EventSource), that proposal gets its own security review — the corpus contract test is the in-code pointer to how recognition is pinned.


State for clearance: head d3f3fa222a6c725753fbe26d92614c27d530bf28, 20 checks pass + 1 expected skip (publish-release-images, PR event), mergeStateStatus: CLEAN, review APPROVED / high confidence. Chain: #460 → #462 → #463 → here.

@Alajmah
Alajmah merged commit 89d5e51 into master Nov 20, 2026
21 checks passed
@Alajmah

Alajmah commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Post-merge deployment verification — master 89d5e51 (all steps observed, none inferred)

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):

  1. 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.)
  2. 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):

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.

@Alajmah

Alajmah commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

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):

Alert Location verified Router mount (behind limiter at app.js:84) Dismissed at
#14 config.js:68 configRouter app.js:180 22:28:11Z
#15 config.js:117 configRouter app.js:180 22:28:27Z
#16 config.js:165 configRouter app.js:180 22:28:29Z
#17 config.js:210 configRouter app.js:180 22:28:32Z
#23 maintainer.js:236 maintainerRouter app.js:160 22:29:05Z
#25 maintainer.js:280 maintainerRouter app.js:160 22:29:08Z
#26 maintainer.js:370 maintainerRouter app.js:160 22:29:11Z
#29 triageOperations.js:94 triageOperationsRouter app.js:192 22:29:13Z
#31 rollouts.js:171 rolloutRouter app.js:196 22:28:41Z
#32 rollouts.js:105 rolloutRouter app.js:196 22:28:43Z
#33 rollouts.js:203 rolloutRouter app.js:196 22:28:46Z
#34 rollouts.js:233 rolloutRouter app.js:196 22:28:49Z
#35 rollouts.js:261 rolloutRouter app.js:196 22:28:51Z

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):

Alert Flagged site Reachable guard (verified) Deployed regression Dismissed at
#36 resolve.js:151 (target[key] = value, mergeSparse scalar branch) resolve.js:133 if (isDangerousConfigKey(key)) continue; inside the Object.keys(source) own-keys loop, before any target access; upstream validation rejects dangerous keys (documented backstop, resolve.js:124–129) #451 @ 779f58f — direct-dangerous-keys.test.js 22:29:40Z
#37 parse.js:79 (target[key] = source[key], mergeDeep) parse.js:69 if (isDangerousConfigKey(key)) continue; inside the Object.keys(source) own-keys loop, before any access #451 @ 779f58f — direct-path __proto__/constructor/prototype + nested-prototype reference invariants 22:29:44Z

Post-execution inventory (API-verified)

  • Open: 8 — #1, #2, #3, #5, #4 (regex/sanitization/identity tranches, held sequence), #9, #10, #13 (holds below)
  • Dismissed: 16 — the 15 above + #27 (earlier, pre-existing)
  • Arithmetic: 23 − 15 = 8 ✓

#9 — read-only disposition (authorized; NOT dismissed, per directive)

  • Alert: js/missing-rate-limiting, single instance, phase4.js:352–359.
  • Flagged handler: GET /audit/verify (audit-chain verification; reads req.query.from/to as integers, calls verifyChain — read-only DB traversal).
  • Mount: phase4Router at app.js:175 (app.use("/api", phase4Router)) — after the limiter (app.js:84) and after apiKeyAuth (app.js:96).
  • Limiter skip list (/health exact, /webhooks prefix) does not match /api/audit/verify.
  • Individual review found no additional bypass surface: same mechanism as the 13 — the query cannot see app-level mounting.
  • Disposition: qualifies for the same false-positive treatment. Dismissal not authorized; returned for decision.

#13 — corrected classification (read-only; NOT dismissed, per directive)

  • Alert location today: app.js:108 — which is app.use(routeAuthObserver). The message aggregates six flows ("This route handler performs authorization, but is not rate-limited." ×6).
  • The earlier matrix's association with the intentionally unthrottled /health endpoint does not match what the alert pins today. The /health route sits at app.js:113; the alert's flagged middleware is the observer at :108. The historical association cannot be carried forward.
  • What the flagged operation actually is: routeAuthObserver (routeAuthObserver.js:225) performs declaration-driven authorization — observe-mode decisions and the W1-03 central enforcement gate (routeAuthObserver.js:98–211). It early-skips /api/auth, /api/bootstrap, /api/setup (routeAuthObserver.js:227–232).
  • Upstream protection: the observer mounts at app.js:108, after the limiter at app.js:84 — every request reaching it has traversed the limiter, and its early-skipped families are exactly the pre-auth families the limiter now keys by IP.
  • Disposition per the stated conditional ("if it concerns a middleware operation already protected by the upstream limiter, it may qualify for the same false-positive treatment"): the evidence supports that reading. It is not a /health risk-acceptance case. Dismissal not authorized; returned for decision.

No-action confirmations

  • #12, #28: fixed states confirmed via API earlier — no manual disposition required or performed.
  • #10: untouched, remains open pending its residual-risk assessment (not a false positive per the directive).

@Alajmah

Alajmah commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

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 |
|---|---|---|---|
| #9 | js/missing-rate-limiting|open|phase4.js:352 ✓ | 2026-11-20T23:21:54Z | false positive — full chain rateLimiter(app.js:84)→apiKeyAuth(:96)→routeAuthObserver(:108)→phase4Router(:175)→GET /audit/verify; skip list has no match |
| #13 | js/missing-rate-limiting|open|app.js:108 ✓ | 2026-11-20T23:21:42Z | false positive — flags routeAuthObserver, which mounts after the limiter and skips non-/api + auth/bootstrap/setup; all six flows share one protected path; /health rationale not used |

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→#4

Shared input path for #1–#3 (polynomial-redos, packages/rules/src/reviewSchema.js)

Source/sink trace: all three regexes live in extractReviewJSON(text) (reviewSchema.js:257), the LLM-output JSON-extraction cascade. Callers: aiReviewService.js:346 (extractReviewJSON(rawText), inside the review pipeline), adversarialReview.js:197, adversarialDefense.js:5. Sink = the regex engines at lines 273, 284, 324–325.

Attacker-controlled input: indirect — rawText is the review LLM's completion (bounded max_tokens: 32768, aiReviewService.js:1031). A PR author controls diff content the model reads; prompt injection can coerce the model into echoing a pathological payload (e.g., "repeat this block verbatim"). Output ceiling ≈ 32k tokens ≈ up to ~10⁵ chars; a newline-dense payload fits that budget.

Where it executes: the shared Node process — index.js starts all 14 workers and the Express server in one process, so a blocked event loop stalls every worker plus /health.

#1 — fence regex, single match (line 273)

  • Regex: the fenced-block matcher at line 273: three backticks, optional json, then \s*\n? (greedy any-whitespace + optional newline), lazy [\s\S]*? body, \n?\s*, closing three backticks.
  • Failure mode: the greedy \s* (which matches \n) followed by \n? makes the whitespace bridge ambiguous — the engine re-splits long whitespace runs while the lazy body expands, giving O(n²) per opening-fence occurrence on non-terminating input (e.g., one fence prefix + ~32k \n, no closing fence). At n≈10⁴–10⁵ that is 10⁸–10¹⁰ engine steps — 0.1 s to minutes of blocked loop.
  • Existing protection: none at this site — no length cap, no timeout around the cascade; strategies 1 (direct parse) and 3–5 don't bound it.
  • Smallest safe correction: make the bridge unambiguous — replace both \s* with horizontal-only [ \t]* around the single optional newline. Matches every valid fenced block byte-identically; only pathological whitespace-run inputs change behavior. Plus an adversarial regression asserting the fence + 32k-\n no-close input resolves to failed under a time bound.

#2 — same regex, matchAll (line 284)

  • Failure mode: identical pattern with the global flag; every fence occurrence is an independent start position, multiplying the per-occurrence O(n²) — worst case O(n²·k) for k fence markers.
  • Existing protection: none; reached only when Strategy 1 (direct JSON.parse) already failed.
  • Smallest safe correction: the same character-class fix as deps: bump node from 20-alpine to 26-alpine #1 applied to the global variant (a single shared constant used by both sites would also prevent drift — consistent with the lockstep fix pattern).

#3 — findings-pattern fallback (lines 324–325)

  • Regex: the {"findings": [ ... ], "overall_correctness" matcher at line 324.
  • Failure mode: .match retries the literal {"findings":[ prefix at every index; on the attack input (that prefix repeated to the token ceiling, no completion) each of the ~n/14 occurrences starts a fresh lazy-body expansion → O(n²)-class scanning, same blocked-loop consequence.
  • Existing protection: none; this is the last strategy before failed.
  • Smallest safe correction: anchor to literal occurrences — const at = trimmed.indexOf('{"findings"'); if (at !== -1) then run the existing regex on trimmed.slice(at) (loop over occurrences if exact all-occurrence fallback semantics must be preserved). indexOf is linear with no backtracking; first-match behavior is unchanged for all valid inputs.

#5 — incomplete-sanitization, packages/web/src/services/flakyTestService.js:220

  • Source/sink trace: candidates (flaky-test detections parsed from CI run logs) → buildQuarantineWorkflow (line 208) → line 220 builds the generated GitHub Actions YAML's shell command: --testNamePattern="<testFilter>" where testFilter joins each candidate's test_suite + " > " + test_name with |, and the ONLY escape is replace(/"/g, '\\"').
  • Attacker-controlled input: direct, with gates. Test names come from the repository's own CI output. A PR author can add a deliberately flaky test (random pass/fail) whose name contains a backslash — e.g. a name embedding \" — which survives into candidates after the flakiness window, then into the generated workflow.
  • Demonstrated failure mode: escaping " without first escaping \ breaks on input containing \": the source pair becomes \\" in the generated command, where \\ collapses to a literal backslash and the following " terminates the shell's double-quoted string early — the remainder of the test name runs as shell syntax in the Actions runner when the quarantine workflow executes. Even with \ fixed, $ and backtick still expand inside double quotes, so both are injection vectors too.
  • Existing protection: quote-escaping (incomplete by definition of this alert); the quarantine workflow ships as a bot-opened PR, so a human merge is a gating control — but the YAML is auto-generated boilerplate a reviewer is unlikely to line-read.
  • Smallest safe correction: escape backslash first, then the double-quote-context metacharacters: replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\$/g, "\\$") plus backtick — or switch the generated command to single-quote wrapping with '\'' escaping. Regression: adversarial test-name fixtures (\", $(), backtick, backslash) asserting the generated YAML contains no unescaped metacharacters, plus valid-name fixtures proving output unchanged.

#4 — identity-replacement, packages/web-dashboard/src/app/custom-rules/page.tsx:63

  • Source/sink trace: API.repoConfig(owner, repo) (api.ts:124) returns /api/config/${owner}/${repo} — which already contains /api/config/. Line 63 then calls .replace("/api/config/", "/api/config/") — a self-replacement, the exact pattern js/identity-replacement flags — and appends /custom-rules.
  • Verified current behavior: the replace is a byte-level no-op; the resulting URL /api/config/{owner}/{repo}/custom-rules correctly resolves against the live backend route configRouter.get("/:owner/:repo/custom-rules") (config.js:238). No functional bug today.
  • Attacker-controlled input / failure mode: none — the replaced value is a compile-time constant; the alert is a code-smell query (self-replacement marks an unfinished edit or dead code). Residual risk is maintenance-only: a reader assumes a transformation is happening, or a future intended prefix change gets "fixed" into the wrong slot.
  • Existing protection: none needed — the value is static.
  • Smallest safe correction: delete the self-.replace call entirely (provably behavior-identical); no regression beyond the page's existing tests.

Proposed remediation order when implementation is authorized

#1+#2 as one unit (same constant, two call sites) → #5 (escaping + adversarial YAML regressions) → #3 (anchor + timing regression) → #4 (dead-code deletion). Each as its own PR with targeted adversarial regressions; valid-input behavior preserved by construction in every case. No implementation started — verification only, per the directive. #10's residual-risk assessment and the held queue (differential gate, 421-D, W3-03) are unchanged.

@Alajmah

Alajmah commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

CodeQL #10 — bounded residual-risk assessment of the /webhooks/github ingress path (read-only; no config changed)

Per the directive: controls verified in production are distinguished from defaults merely assumed; the assessment ends with a recommendation for the maintainer's decision — retain the exception with formally accepted residual risk, or a narrowly scoped compensating control.

1. Controls verified in production (this session, against 89d5e51)

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.

@Alajmah

Alajmah commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

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 89d5e51, webhooks.js → express_raw_body_middleware())

  • Over-cap rejection path only: rejected bodies are drained without buffering — my statement was true there and only there.
  • Under-cap bodies: every accepted chunk is pushed to a chunks[] array and retained in memory until the request ends (the buffer is needed for HMAC). At completion, Buffer.concat(chunks) transiently allocates a second buffer of comparable size. The 25 MiB cap therefore bounds memory per connection, not in aggregate.
  • HMAC rejection does not protect the resources consumed before verification — a bogus-signature request buffers its full body first, then gets the 401. Verified live earlier: the 401 path works, but it works after the buffering.

Corrected exposure math (production figures)

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:

  1. 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.
  2. 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.
  3. 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.

@Alajmah

Alajmah commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

#425 completion record + #10 read-only evidence update

Remediation tranche complete (master 496045682216317c6fcab7ae880b551e8a4e88a8, deployed)

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.

@Alajmah

Alajmah commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Unit #10-B — Delivery-recovery architecture (DESIGN; no implementation) + downstream idempotency assessment

Part 1 — Replay-safety audit of the current webhook pipeline (code-verified at master 4960456)

The delivery-dedup insert — INSERT INTO webhook_deliveries … ON CONFLICT (delivery_id) DO NOTHING (webhooks.js:198) — is the last effect of the handler, immediately before the 202. On a redelivered GUID (GitHub redelivery reuses the delivery GUID; the docs' own recovery procedure groups attempts by it), every step before the insert replays:

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.

@Alajmah

Alajmah commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

#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 states

The 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, webhook_delivery_lifecycle):

State Meaning Transition trigger
received Authenticated delivery durably recorded; no effects attempted HMAC pass + body parse (replaces today's last-effect insert)
processing An execution owner holds the delivery (owner id + lease deadline) owner claims from received/retryable_failed
completed Required processing completed (the ONLY state that suppresses future attempts) owner's terminal success transition
retryable_failed Failure with NO external effect emitted, or all emitted effects verified compensable/idempotent owner's classified failure
reconciliation_required Completion of an external effect is uncertain (crash between effect and record) crash discovery / lease expiry mid-processing
terminal_failed Recovery exhausted; operator intervention required attempt budget exhausted or unresolvable uncertainty

Ownership and recovery semantics: a claim is a lease (owner id + deadline, renewed on progress), not a boolean. Lease expiry mid-processing moves the row to reconciliation_required — never silently back to received (which would repeat uncertain effects) and never to completed (which would lose unfinished work). Reconciliation resolves per-effect state before any replay (unit #10-B2).

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:

  • check-run creation → owner-keyed reuse (the existing Redis check key becomes a durable lookup keyed by GUID, checked before creation; a check created by a crashed owner is adopted, not duplicated);
  • queue jobs → jobId = delivery GUID (BullMQ dedup) once the claim gates enqueue;
  • comments/labels → marker/find-before-post patterns as they exist, audited per handler;
  • custom-rule actions → the P1 identifiers-only boundary re-evaluated for replay;
  • DB writes → transactional with the lifecycle transitions where possible.

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 processing under a live lease responds 202 only because the row itself is the durable acceptance of responsibility — the delivery is recorded received/processing before any 202, so "durably accepted responsibility" holds by construction. What the duplicate must NOT do is report completed; it won't — completion is a separate transition.

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):

GitHub delivery state Local lifecycle state Action
Failed Absent Recovery candidate (the cap-loss case)
Failed completed Reconcile discrepancy (why did GitHub see failure after our completion — response lost post-processing); never repeat effects
Failed processing Resolve current ownership first; not a replay candidate
Failed retryable_failed Resume via the verified replay-safe path only
Successful completed Resolved
Successful Absent/incomplete Investigate inconsistent acknowledgement — never blind replay

Local completed (not the claim, not the row's existence) is the sole completed-processing marker for recovery decisions.

B3 (HIGH) — Ambiguous redelivery outcomes: intent-persisted submissions

Corrected attempt protocol (unit #10-B4 design; implementation held): before any POST /app/hook/deliveries/{id}/attempts, the intent is durably persisted (row transitions to a redelivery_submitted sub-state with a monotonically increasing attempt counter). Outcome classes handled distinctly:

  • confirmed rejection (non-2xx received) → intent cleared, attempt consumed per policy;
  • confirmed acceptance (2xx received) → await GitHub-side delivery confirmation on later polls;
  • ambiguous (connection lost before response) → no automatic resubmission; the next poll reconciles against GitHub's delivery history for that GUID (a new attempt appearing there means the submission landed; the persisted intent plus observed history is the authority, not the lost response);
  • confirmed subsequent delivery (poll sees a newer attempt for the GUID) → observe its outcome;
  • confirmed local completion (the redelivered delivery ingests and completes) → resolved.

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 cases

Pagination under sustained bursts (cursor walk with per-page GUID upserts, no assumption of ordering stability); checkpoint timestamp collisions (cursor = (delivered_at, guid) tuple, not timestamp alone); overlapping polling windows (idempotent upserts make re-reads free); and outages exceeding the 3-day window: the poller records a durable coverage_gap interval whenever it was down past the boundary — deliveries that aged out unobserved are counted and reported as a gap in the record, never allowed to disappear simply because GitHub no longer lists them.

Sequencing (as directed)

Unit Scope Authority
#10-B1 Durable delivery identity, ownership/lease, lifecycle-state design DESIGN (this comment)
#10-B2 Effect-by-effect replay safety + crash-recovery design (per-effect idempotency table) DESIGN — next deliverable
#10-B3 GitHub-side discovery, durable pagination, coverage gaps, recovery projection + corrected eligibility matrix DESIGN (adopted above)
#10-B4 Authorized redelivery execution + outcome reconciliation incl. ambiguous submissions HOLD implementation
#10-B5 Controlled end-to-end recovery proof HOLD

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.

@Alajmah

Alajmah commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

#10-B2 — Effect-by-effect replay-safety and crash-recovery design (DESIGN; authorized) + resolutions to the four architectural conditions

Part 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).

# Effect (verified call site) Crash window examined Verdict Design requirement
1 Delivery record insert (webhooks.js:198, ON CONFLICT (delivery_id) DO NOTHING) insert vs. response TA Becomes the received lifecycle row, moved to the top of the handler; same transaction as nothing else — atomic by itself
2 GitHub check-run creation (webhooks.js:102, PR open/reopen/ready only) creation succeeds → process dies before redis.setex(checkKey) — the durable GUID-keyed lookup stays empty RC The lookup alone cannot solve it (the maintainer's point, confirmed). Recovery = discovery: on reconciliation_required, list check runs for the head SHA (GET /repos/{o}/{r}/commits/{sha}/check-runs), identify GitWire-owned runs by name+owner signature, adopt the existing id (persist GUID→check-id durably this time), never create a second. Residual ambiguity (multiple candidates): reconcile to the oldest owned run, flag the rest for operator review. Crash BEFORE creation → safe to re-create (nothing exists) — distinguished by the discovery result itself
3 BullMQ enqueue (generic path, webhookHandlers/index.js:92, no jobId today) enqueue vs. record ID† Adopt jobId = delivery GUID. †Time-bounded, not permanent: production retention is removeOnComplete: {count: 500} / removeOnFail: {count: 1000} (runtime/src/create-queue.js:41-42) — a completed job eventually leaves the store and the same jobId re-enqueues. Therefore the enqueue is idempotent only while the lifecycle row gates it: a delivery in completed never re-enqueues at all, so retention expiry cannot cause duplication. The queue is a scheduler, not the dedup ledger — the lifecycle row is
4 Comments/reviews (triage auto-comment marker; review delivery) marker lookup → create → response lost RC find-before-post markers (findCommentByMarker) make replay idempotent when the create SUCCEEDED; the ambiguous window (created, response lost before marker visible) resolves by re-listing — marker-based lookup is the reconciliation. Concurrent-create race: GitHub has no unique constraint — mitigation = single-writer per GUID (the lifecycle lease serializes replays)
5 Labels/status updates apply → record ID (convergent) Desired-state semantics: set-label/commit-status operations converge on the desired state; re-application is a no-op delta. Authorization revalidation: replays run under the recovered adoption principal, not cached authority
6 Custom-rule mutations (evaluateAndExecuteCustomRules, post-P1 identifiers-only boundary) rule match → action execution → record UR/RC per action type Each action type inherits its row's verdict (comment→4, label→5, status→5). The design requirement: per-action identity — each executed action records (guid, ruleName, actionIndex) durably before execution; a replay re-checks that record per action, so partial execution (action 1 done, crash, action 2 pending) resumes at the boundary rather than repeating action 1
7 PR creation / branch mutations (heal/issue-fix paths) create → id never persisted RC (discovery-based), UR for destructive variants External-object discovery: find-by-title-marker/branch-name convention before create; ambiguous discovery → operator. Destructive mutations (force-push, close, delete) → UR: reconciliation proposes, operator confirms
8 Notifications (Telegram, fire-and-forget) send → record DT Explicit duplicate-delivery tolerance declared (bounded: replay count ≤ retry budget); dedup optional via (guid, channel) sentinel
9 DB writes (triage fields, ci_runs, heal_prs, ai_reviews, decision log) write vs. lifecycle transition TA where co-transactional with lifecycle transitions; otherwise keyed upserts The lifecycle completion transition and the business write share one transaction wherever the write is the LAST effect — the completion record then cannot exist without the effect

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, reconciliation_required routes to the operator surface (#10-B4), not to automatic re-execution.

Part 2 — The four architectural conditions

B1.1 — Durable acceptance includes recoverable work (transactional inbox). Adopted: the received lifecycle row carries the full authenticated payload (encrypted at rest with the same key class as other secrets-adjacent storage, or a durable reference if payloads prove too large — GitHub webhook payloads are KB-scale, so inline storage is the default). Scheduling: the 202 is sent only after the row commits, and a ready-queue sweep (BullMQ repeatable job) re-enqueues any row stuck in received/retryable_failed past its lease horizon — accepted work cannot disappear between persistence and execution. Reconstruction: a replacement worker reads the row's payload + per-effect progress; nothing requires the original HTTP request. Retention: lifecycle rows (and payloads) expire on an explicit schedule (default: 30 d terminal / 3 d unrecoverable-boundary alignment), with coverage-gap records retained as counts only. The invariant adopted verbatim: no acknowledgement of work the system cannot subsequently recover.

B1.2 — Fencing. Adopted: the lifecycle row carries a monotonically increasing owner_generation; every state transition and every effect-authorization record carries the generation that performed it. A resumed former owner (paused past its lease) presents a stale generation: its transitions are rejected by the row's conditional UPDATE, and its per-effect records are marked orphaned for reconciliation. For external APIs that cannot enforce GitWire's token (all of GitHub), the fence bounds local bookkeeping; the effect itself relies on the per-effect verdicts in Part 1 — exactly as directed (the lease coordinates ownership; it does not guarantee exactly-once external execution).

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 (delivered_at, github_delivery_id)), poll cursor (discovery progress only), owner_generation (local execution authority). The recovery projection keys rows by GUID with per-attempt sub-records keyed by GitHub delivery id. Coverage gaps: recorded as intervals with unknown contents — the count of unknown deliveries inside a gap is reported as unknown unless an independent evidence source exists.

B4.1 — Budget semantics corrected (previous "rejections only consume" was wrong). Adopted verbatim:

Outcome Budget treatment
Confirmed API rejection Submission policy and backoff
Confirmed API acceptance Consume a recovery attempt
Ambiguous submission Reserve the attempt pending reconciliation
Confirmed subsequent delivery failure Already-consumed attempt remains counted
Rate-limit rejection Provider backoff, no recovery-attempt consumption
Confirmed local completion Close recovery lifecycle

The unlimited-retry hole is closed: an accepted redelivery whose subsequent delivery keeps failing burns the budget and terminates at terminal_failed — operator-visible, never looping.

The three truths (governing invariant, restated)

Durably accepted (lifecycle row + recoverable payload), externally executed (per-effect records + reconciliation), and locally completed (the completed transition) are three separate durable facts. The design never infers one from the existence of another: acceptance doesn't imply execution, execution doesn't imply completion, and completion is the only state that suppresses recovery attempts.

No implementation authorized this round; #10-B4/B5 remain held; no live redeliveries, admission changes, dismissals, or risk acceptance.

@Alajmah

Alajmah commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

#10-B2 — COMPLETED: implementation specification (DESIGN; no implementation) — B2-F1 and B2-F2 incorporated

Part 0 — What this completes, and what it does not

  • Supersedes two things in comment 7060443247: the adoption rule of effect row 2 ("reconcile to the oldest owned run" is withdrawn), and the single-column verdicts, which become per-effect state machines.
  • Stands unchanged: the crash-window findings of the effect audit, the four architectural conditions, and the budget table.
  • Not in this unit: any code; any redelivery call (docs(runbook): repository ID reconciliation procedure #10-B4); the end-to-end recovery proof (docs(runbook): repository ID reconciliation procedure #10-B5); automatic replay of an uncertain effect. Admission control stays on HOLD.

Part 1 — Ground truth (verified in the code at master bba0a08, and against the live API)

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.app came back null for every run in a listing and on a direct fetch. App identity must therefore come from the server-side app_id filter, 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 empty external_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 intent row is committed before the call and carries the owner_generation that is about to act.
  • F2-2. Only that same generation may move intent to confirmed or not_executed. The transition is a conditional UPDATE … WHERE owner_generation = $g AND state = 'intent'.
  • F2-3. An intent row seen without a live lease is uncertain. It is never read as "not done".
  • F2-4. No row means never attempted. This is distinct from every state above.
  • F2-5. confirmed and uncertain both block replay. A delivery whose effects are all in confirmed or not_executed may be resumed; one with a single uncertain goes to reconciliation_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 deliveryId in 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_deliveries stays. 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 id that 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. sanitizeWebhookPayload exists 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:

  1. Verify, parse, sanitize — unchanged.
  2. One transaction: insert the lifecycle row (received, payload) and the audit row; ON CONFLICT DO NOTHING.
  3. If the row already exists, this is a duplicate: respond 202 with { queued: false, state } and perform no effect.
  4. 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.
  5. 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_failed only when no effect is intent or uncertain.
  • 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)

  1. A processing row whose lease has expired: every intent effect of the lost generation becomes uncertain; the lifecycle becomes reconciliation_required; the generation is advanced.
  2. A received row older than the grace period: enqueue. Nothing was attempted, so nothing can be repeated.
  3. A retryable_failed row past its backoff: enqueue.
  4. A reconciliation_required row: 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

  1. 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.
  2. 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.
  3. Duplicate response codes. Proposal: 202 for every non-terminal duplicate, 200 for completed.
  4. Retention periods. Proposal: 30 days for terminal rows.
  5. 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.

@Alajmah

Alajmah commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

#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

Fact Where
On a sanitizer failure the function logs a warning and returns the original payload lib/githubSanitize.js:53–55
In production, 0 of 208,700 delivery rows have processed = false, and 0 have error set webhook_deliveries, read 2026-11-22
Redis persistence is AOF with appendfsync everysec production redis-cli CONFIG GET
Job data carries the payload itself in most handlers; collect-evidence is the exception and already keys its job by delivery lib/webhookHandlers/handlePullRequest.js:7; handleWorkflowRun.js:49–68
A BullMQ job id cannot contain : comment at lib/webhookHandlers/handleWorkflowRun.js
Nine test files drive the webhook route or assert its inline behavior listed under Decision 2
Every delivery id is a 36-character UUID string 208,700 of 208,700 rows

Part 1 — The five decisions

Decision 1 — The payload is stored encrypted, with keys that are not in the database

Stored form. The lifecycle row does not hold JSONB. It holds:

Column Content
payload_ciphertext AES-256-GCM over the compressed payload
payload_nonce 96 bits, random, one per row
payload_tag the GCM authentication tag
payload_key_id which key encrypted it
payload_sha256 digest of the stored plaintext, for verification
payload_bytes uncompressed size
payload_sanitized whether the stored payload is the sanitized one
  • Algorithm and dependency. AES-256-GCM through Node's built-in crypto. No new package.
  • Row binding. The delivery GUID is the additional authenticated data. A ciphertext cannot be moved to another row without failing authentication.
  • Compression first. Encrypted data does not compress, so the payload is compressed before it is encrypted. The ratio is not assumed: it is reported once payload_bytes and the stored size are both recorded. A 25 MiB payload that does not compress stays 25 MiB.
  • Keys. 32-byte keys, named by id, supplied to the web process through its environment. They are never written to PostgreSQL. Rotation adds a new key at the front; old keys stay listed until every row they encrypted has been deleted.
  • Fail closed. If no key is configured, encryption fails, or the transaction cannot commit: respond 503. Nothing is accepted that cannot be stored recoverably. This is the rule of Decision 1 verbatim.

The sanitizer is not the control. Because sanitizeWebhookPayload returns the original payload when it fails, the design does not rely on it for confidentiality. Two things follow:

  • Every stored payload is encrypted, sanitized or not.
  • On a sanitizer failure the row is stored with payload_sanitized = FALSE, the event is logged without content, and sanitization is repeated before any consumer reads the payload.

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 production.env on the host, the host's backups contain both the database and the key. That placement protects against disclosure of the database alone — a dump, a replica, a query-injection, a dashboard that exposes rows. It does not protect against disclosure of a full host backup. Three placements:

Placement Protects against Cost
Environment file on the host, the class of DB_PASSWORD database-only disclosure none new
A key file outside the backup set database-only disclosure, and backup disclosure an operational step the backup job must exclude
An external secret manager the above, plus host compromise a new dependency

Proposed for this unit: the first, with this limit written down.

Storage budget.

  • Production receives about 1,100 deliveries a day (208,700 from 2026-05-15 to 2026-11-22). At 30 days that is roughly 33,000 live rows.
  • Payload sizes are not recorded today. The first stage records payload_bytes and reports median, 99th percentile and maximum. The budget below is a starting point until those numbers exist.
  • Per row the ceiling is the request cap in force, 25 MiB. That cap is not changed here.
  • Proposal: warn when the table exceeds 2 GB, alert at 4 GB. CT 115 has a 50 GB root filesystem, and filled it on 2026-11-21, so the guard is not theoretical.
  • Exceeding the budget never rejects a delivery. The response is an operator action: shorten retention or add capacity. Admission stays as it is.

A residual this unit does not close. BullMQ job data carries the payload in clear in most handlers (handlePullRequest.js:7 is one). Redis writes it to its AOF, so a copy of each payload outlives the request until the queue's retention removes the job. Closing it means job data carries only the GUID and every worker reads from the lifecycle row: 18 enqueue sites and every worker. That is a separate unit. It is recorded here so that "encrypted at rest" is not read as covering Redis.

Decision 2 — A worker executes every attempt

The HTTP handler stops executing effects. The sequence is fixed:

verify signature → parse → sanitize
→ one transaction: lifecycle row (received, encrypted payload) + audit row
→ commit
→ enqueue delivery-process (jobId dw-<guid>)
→ HTTP 202
  • The handler makes no GitHub call. Today it creates the check run, evaluates custom rules and evaluates quality gates before it responds.
  • A stop between commit and enqueue loses nothing. The row is received; the sweep enqueues it after a grace period.
  • The worker claims and executes. Claim (processing, generation 1, a lease that is renewed on each confirmation), then the plan of comment 7079316288 Part 5 with one change: no effect is ever replayed from an uncertain state.
  • A new queue. delivery-process, with a constant in @gitwire/core. It is dedicated, so that long review or triage jobs cannot delay it.
  • Job ids use -, never :. BullMQ rejects a colon in a job id — the constraint is recorded at lib/webhookHandlers/handleWorkflowRun.js. The ids of comment 7079316288 (dw:<guid>, <job_name>:<guid>) are corrected to dw-<guid> and <job_name>-<guid>.
  • Bounded local retries. A failed attempt leaves retryable_failed; the sweep re-enqueues with backoff. After a configured number of attempts (proposal: 10) the row becomes terminal_failed. It never loops.

Promptness of the check run. Today the GitWire check run exists before GitHub receives the 202. After this change the worker creates it. That is the cost of the decision, so it is measured and tested rather than assumed:

  • A new duration: from acceptance commit to the confirmation of the check-run effect, on the /health block beside the existing docs(runbook): repository ID reconciliation procedure #10-A counters.
  • A starting target: 95th percentile at or under 2 s, 99th under 5 s.
  • Two safeguards: the check-run effect is the first external effect in the plan, and the queue is the dedicated one above.
  • The shadow stage (Part 4 of 7079316288) measures the real distribution in production before anything is switched over. If it misses the target, the worker is not switched on until it does.

Tests that will need to change. Nine files exercise the route or assert inline behavior: tests/helpers.js, tests/stress/auth-edge-cases.test.js, tests/stress/mutation-webhook-ingest.test.js, tests/unit/check-run-lifecycle.test.js, tests/unit/rate-limiter-behavior.test.js, tests/unit/wave2-webhook-vertical.test.js, tests/unit/webhook-body-limit.test.js, tests/unit/webhook-dispatch-own-property.test.js, tests/unit/webhook-telemetry.test.js. Each is to be reviewed in the implementation unit; none is changed now.

The review approved the architectural choice. It did not authorize building the worker.

Decision 3 — Response codes

Situation HTTP Body Effect
New delivery, committed 202 queued: true eligible for processing
Duplicate of one in flight 202 queued: false, state: processing none
Duplicate of a completed one 202 queued: false, state: completed none
Duplicate of a failed or parked one 202 queued: false, state: … none; it is recorded as a new arrival
Database cannot commit 503 error nothing accepted
  • Every previously accepted duplicate answers 202, including completed. The 200 of comment 7079316288 is withdrawn: today's path answers 202, and one code changes the external contract least.
  • No arrival with a recorded GUID re-executes any effect. Duplicates are counted (http_attempts) and answered.
  • 503 is the only non-2xx that this design adds. It lands in the docs(runbook): repository ID reconciliation procedure #10-A telemetry as error today; a distinct class, unstored_503, is proposed so that a storage outage is not read as a handler failure.

Decision 4 — Retention

Record Policy
completed delete 30 days after completion
terminal_failed delete 30 days after an approved operational closure
reconciliation_required never deleted automatically before it is reconciled
Stuck processing subject to inspection and recovery, never deletion
retryable_failed not deleted before its attempts are resolved
Aggregates kept, without GUIDs and without payloads
  • Deletion is one transaction: the lifecycle row and its effect rows together. Before it, one aggregate row is written per day and state.
  • Nothing that can be replayed survives the payload. The four artifacts that could re-execute a delivery are each covered: the lifecycle row (deleted with its effects); the audit row (kept as a tombstone — below); queue jobs that name the GUID (bounded by the queue's own retention, and they are the execution of an accepted delivery, not a replay); operator recovery actions (they require a lifecycle row, in a state that permits it).
  • The tombstone. The audit row in webhook_deliveries has no payload and is small: the table is 48 MB for 208,700 rows. It stays for at least a year. A late duplicate of a long-expired delivery finds the tombstone and answers 202 with queued: false, state: expired, and no effect. Without the tombstone, a redelivery older than the retention would look like a new delivery and would run again.
  • Backups. A deleted payload remains in database backups until those age out — seven daily archives on this host. Retention is therefore "deleted from the live database", and the documentation says so.
  • Required before this is enabled: a test that offers the deletion job a row in every state and asserts that only the two permitted states are deleted; a test that a row younger than 30 days is never deleted; one restore drill from a backup taken after the feature is live.

Decision 5 — The search window observes; it does not prove

The rule of comment 7079316288 — "0 matches after the grace window → not_executed" — is withdrawn.

Search result Effect state
Exactly one identity match confirmed
Two or more identity matches reconciliation_required; no object is chosen
No match, inside the window stays uncertain; look again
No match, after the window reconciliation_required — not replay, not not_executed
Search failed or incomplete uncertain; it counts as no information
  • The window (proposal: 60 s, three looks) decides only when to stop looking and escalate.
  • No second check run is ever created because time passed.
  • not_executed requires evidence that the effect did not happen. Two kinds exist: the creating call returned a status that guarantees nothing was created, recorded at the time; or an id confirmed earlier now returns 404. Absence from a listing is never that evidence.

Part 2 — The three conditions

Condition 1 — processed tells the truth

Today the audit row is written at the end of the handler with processed = TRUE, unconditionally. That is why production has no row with processed = false.

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 = TRUE means every ingress effect is confirmed, queue hand-offs included. It does not mean the handed-off work has finished (Condition 3).
  • error becomes 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 = TRUE with 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 the Link chain.
  • Completeness is checked, not assumed. The number of runs fetched must equal the total_count of 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_id are considered, because check_suite.app was null in every response examined. Nothing is ever patched or adopted outside that set.
  • The quality gate stops adopting by name. services/qualityGateService.js:536 takes 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 completed when its hand-offs are Accepted. Its processed = TRUE says 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 is lost, and its work item goes to reconciliation_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 for ai-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

  1. Nothing is acknowledged that is not stored recoverably: encrypted, committed, key present.
  2. A recorded GUID never causes a second execution. Duplicates are answered 202 and counted.
  3. confirmed is never replayed. uncertain is never replayed.
  4. not_executed requires evidence; absence from a listing is not evidence.
  5. No object is adopted by name, and none is chosen among several.
  6. An effect recorded by a stale generation changes nothing.
  7. processed = TRUE means the ingress effects are confirmed, and nothing about downstream work.
  8. An absent job is lost, never re-enqueued.
  9. A non-terminal record is never deleted.
  10. 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

  1. Sanitizer failure: store with the flag (recommended), or refuse with 503.
  2. Key placement: environment file on the host (recommended for this unit), a file outside the backup set, or an external manager.
  3. Budget thresholds: 2 GB warn, 4 GB alert.
  4. Check-run latency target: p95 ≤ 2 s, p99 ≤ 5 s.
  5. Local attempt ceiling: 10.
  6. Whether the Redis copy of the payload in job data becomes its own unit now or later.

No implementation is authorized by this comment.

@Alajmah

Alajmah commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

#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 corrections

Correction 1 — confirmed is history; it is never undone.

Revision 1 listed "an id confirmed earlier now returns 404" as evidence for not_executed. That is withdrawn. A creation that was confirmed stays a fact whatever happens to the object afterwards: it may have been deleted or become unavailable, and neither means it was never created.

Event on a confirmed effect Result
A later read of the confirmed id returns 404 recorded as an observation (object_unavailable); the lifecycle goes to reconciliation_required
Automatic re-creation after such a 404 never
Transition confirmed → not_executed does not exist

not_executed therefore has exactly one source of evidence: the creating call itself returned a status that guarantees no object was created, and that status was recorded at the time.

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:

Prior attempt on record Empty search means Allowed
none nothing was ever attempted create
not_executed, by the evidence of Correction 1 the proven non-execution stands create
intent or uncertain the earlier attempt may have succeeded no creation — reconciliation_required

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 |
|---|---|---|
| Before or at the PostgreSQL commit | none | 503 — not accepted | GitHub's own retry, or the operator |
| After the commit; enqueue fails or the process stops | received, durable | 202 — accepted, { queued: false, state: "received", deferred: true } | the sweep, after the grace period |

  • The response says what is true: the delivery is durably accepted; only the hand-off to the queue is deferred.
  • The earlier rule "respond 503 whenever the database cannot commit" is unchanged. It never applies after a successful commit.

The second half of this correction: detecting a lost job is not recovering it. A job whose enqueue was confirmed and that later vanished is not "recoverable" because the loss can be seen. Every job type needs an approved reconciliation or recovery path before the recovery feature is enabled in production. Revision 1 said the design makes a loss detectable and never turns it into a duplicate. That remains true and is not enough. Part D lists what is still owed.

One observation from today supports the correction. The review of PR #494 was cut by the deployment of a1b3665: the retry finalized the first check run as interrupted and left a second one in progress, with no job left in the queue. Nothing recovers that today; the operator command was needed.

Part B — The six decisions, as adopted

# Decision Rule Conditions attached
1 Sanitizer failure the payload is stored, encrypted, with payload_sanitized = FALSE The row is quarantined. No worker that executes external effects may receive an unsanitized payload. The row goes to a state that requires reconciliation; sanitization is retried under supervision; the failure is logged without content. If encryption or the commit is impossible: 503
2 Key location a protected configuration file on the host, first stage Documented limit: the database and the key sit in the same host backup, so a leaked full-host backup discloses both. Acceptance requires three things — an independent encrypted copy of the key kept off the host; access permissions set on the file; and a demonstrated restore of the database and decryption of its rows after the loss of CT 115. The key is never written to PostgreSQL and never to operational logs
3 Storage budget 2 GB warning, 4 GB alert Measure the growth rate and the free space on the root filesystem, not the table size alone. No new delivery is dropped for crossing a threshold — that would be an admission change, and #10-C is on HOLD
4 Check-run latency p95 ≤ 2 s and p99 ≤ 5 s, as initial targets Targets, not guarantees, measured on the worker path itself — see Part C
5 Local attempts 10 at most A retry requires proven replay safety. uncertain is never replayed. The count is durable and is not reset by a worker restart or by a duplicate webhook
6 Redis a separate unit Design in Part E. A mandatory gate before the recovery path is enabled in production. PostgreSQL encryption alone does not support the claim "the payload is encrypted at rest" while a clear copy persists in the Redis AOF

Part C — One order, testable

Revision 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:

Order Step Kind
1 repository reconciliation local database write
2 ingress check run the first external effect
3 dispatch to queues external hand-offs
4 custom rules by action type
5 quality gates by action type
  • The plan is an ordered list, and the worker records the effects in that order. A test asserts the order of the effect rows.
  • The shadow stage cannot prove the worker's latency, because it observes and does not execute the new path. The targets are measured where the path is real: first in a controlled run, then on a bounded share of live traffic behind the configuration switch, before full enablement.

Part D — Per job type: evidence probe and approved recovery path

Both are owed for every job type before recovery is enabled. Neither is asserted in this revision.

Job name Evidence probe Approved recovery path
triage-issue, triage-pr to declare to declare
comment-command to declare to declare
ai-review, supersede-review to declare to declare
reconcile-pr to declare to declare
pr-labeled-auto-merge, pr-closed-or-unlabeled to declare to declare
review-submitted to declare to declare
checks-updated, eval-rollback to declare to declare
ingest-test-results, collect-evidence to declare to declare
sync-installation, sync-repo, validate-configs, generic-event to declare to declare

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 payloads

Design authorized; implementation not.

Ground truth, verified at a1b3665.

Fact Where
8 enqueue sites embed the complete webhook payload in job data handleIssues.js:17, handleCheckSuite.js:6, handlePullRequestReview.js:6, handleInstallation.js:5, handlePullRequest.js:7, handlePush.js:8, handleWorkflowRun.js:17, webhookHandlers/index.js:91
Three job shapes carry large sub-objects — the pull request, the repository and the installation objects ai-review (handlePullRequest.js:17, 34), supersede-review (:56), reconcile-pr (:44)
Manual and API-triggered runs carry payloads that are not one webhook delivery: the manual run combines the comment delivery with a pull request fetched from the API; the API route builds its own objects commentCommands/handleManualRun.js:30, 72, 82, 143, 162, 175; routes/phase4.js:245
One job carries scalars only collect-evidence (handleWorkflowRun.js:49)
10 worker files unpack job data, at 17 sites workers/*.js
Redis persists job data to its AOF appendonly yes, production

Design.

  1. A reference instead of a copy. Job data carries payloadRef and the few scalar keys a job needs to route and to deduplicate. It never carries the payload.
  2. One encrypted store. The lifecycle row is the store for a webhook delivery. A run whose payload is not one webhook delivery — a manual run, an API-triggered run, a scheduled one — gets a row of the same kind under a generated id, with a stated origin and its own retention. The same columns, the same key, the same fail-closed rules as Decision 1. One point stays open: a manual run's payload is the comment delivery plus an API fetch, so it may reference the comment delivery's row, a new row, or both.
  3. Selectors for the sub-object jobs. ai-review, supersede-review and reconcile-pr carry payloadRef plus the name of the part they need. The worker loads the row and selects.
  4. Consumers. Every worker reads the payload through one function — load by payloadRef, decrypt, verify the digest, sanitize if the row says so. The 17 unpack sites change their source, not their logic.
  5. Fail closed. A job whose row is missing or undecryptable does not skip and does not guess: it ends in a visible failed state that names the reference.
  6. Retention. A row outlives any job that can reference it. A job that outlives its row is the fail-closed case above.
  7. Rollout. Producers stop writing inline payloads at once. Consumers accept both forms for one queue-retention period, so that jobs enqueued before the switch still run. After that, an inline payload in job data is rejected.
  8. The AOF itself. Old payloads remain in the existing AOF and in existing snapshots until they are rewritten and aged out. A one-off AOF rewrite belongs to the rollout; host backups taken before it keep their copies and are documented.

Test oracle for the unit.

Scenario Expected
Any job enqueued after the switch its serialized data contains no payload field — asserted on the bytes stored in Redis
A job enqueued before the switch still runs
Job data with an inline payload after the transition period rejected
Row missing or undecryptable the job fails visibly, naming the reference
Each of the 17 unpack sites covered by a test that loads through the one function

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

Item State
#10-B2 design Revision 2; the three corrections applied
Unit #10-R1 designed here
Implementation of anything above HOLD
Owed before enablement Part D, both columns, for 17 job names

@Alajmah

Alajmah commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

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

Time (UTC) Event
16:08:11 the deployment of a1b3665 starts; it recreates the app container
16:08:17 PR #494 is opened; the review job starts
16:10:05 the queue retries the job; it finds its "processed" marker, sees its check run still queued, finalizes that check run as interrupted, and exits without publishing
after that the phase-4 queue is empty; a second check run stays in progress
16:18:21 an operator requests the review again by comment; it completes in about two minutes and approves

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 ai-review that path is, today, this manual step.

2. The command parser and the "nothing dispatched" acknowledgment

At 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:

{"command":"run","pillar":"review`.","repo":"Octo-Lex/GitWire","issue":494,"isPR":true,"dispatched":[],"blocked":[]}
  • The trigger was my own checks comment. It quoted the re-run command inside inline code. The parser (lib/commentRouter.js, parseGitwireCommand) searches for its prefix anywhere in the body, code formatting included.
  • The argument it read was the word review followed by a backtick and a period. No pillar matches that value, so nothing was dispatched.
  • The acknowledgment path for "nothing dispatched" (commentCommands/handleManualRun.js, postAcknowledgment) then reported a configuration and data-resolution problem. Neither was true.

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

  • Acknowledgment truthfulness belongs to the recovery contract. An operator who acts on "check that GitWire is properly configured" looks in the wrong place.
  • The parser has two gaps: it accepts a command from inside code formatting, and it does not validate its argument.
  • Both are outside every authorization so far. They are recorded, not fixed.

@Alajmah

Alajmah commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Verification note on the evidence above, and the Redis baseline (2026-11-22)

Correction of method

In 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 redis-cli does not have. The conclusion happened to be right, but it was not supported when it was written. The working query, run afterwards, gives:

phase-4 queue count
waiting 0
active 0
delayed 1
failed 4
completed 500

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 today

Read-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 payload key, a pull-request object, a repository object.

Queue Retained jobs (completed + failed) What their data carries Share in the sample
webhook-events 500 full webhook payload 100 of 100
phase2 1,500 full webhook payload 100 of 100, in both sets
triage 970 full webhook payload 100 of 100, in 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
ci-evidence, diagnosis, issue-fix, maintainer, patch, sync, verification, critic 6,284 none of the three markers 0 of 100 in each sampled set
  • 11,758 jobs are retained in Redis across 14 queues: 3,470 in the four queues whose jobs carry a full payload, 2,004 in the two queues whose jobs carry objects, 6,284 elsewhere. About 5,400 of them carry webhook-derived payloads or large objects (3,470 whole sets, plus about 1,940 of the 2,004, at the sampled shares).
  • They persist because of the queue retention: up to 500 completed and 1,000 failed jobs per queue. Failed jobs are not removed by time, only when newer failures push them out.
  • The database holds 48 MB of delivery rows without payloads. Redis is where the payload content lives today, in memory and in the AOF.

This is the number the second gate of #10-R1 is measured against.

@Alajmah

Alajmah commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

#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 obtained

The nine worker files were traced read-only at 3847171 — four parallel traces, each required to cite file:line for every claim or mark it unverified. I then re-read the lines that carry the weight of the argument: the review completion write, the publication claim, the uniqueness constraints, the revert branch name, the test-result insert, the queue comment, the comment-command handler. The baseline numbers come from production Redis, read-only, counts only.


Gate 1 — Evidence and recovery path for each job type

Three things decide whether a lost job can be put back on the queue without judgement:

  • what durable record proves the job finished (evidence);
  • what state shows that it never ran (loss indicator);
  • whether running it a second time can duplicate an effect (blind re-enqueue).
Job name Evidence of completion A lost job looks like Blind re-enqueue Candidate recovery path
generic-event none needed — the handler only logs (workers/webhookWorker.js:36–37) nothing harmless, pointless none
sync-installation installations: deleted_at or updated_at (webhookWorker.js:50–70) a stale row safe — upsert on github_id the 30-minute full-sync heals it (workers/syncWorker.js:55–63)
sync-repo repositories.updated_at (webhookWorker.js:84–101) a stale row safe — upsert full-sync, or the on-demand sync
validate-configs none — no consumer exists (webhookWorker.js:29–37: the dispatch has two cases; this name falls to the default branch and is logged) nothing observable pointless a decision: implement it, or stop enqueuing it. See below
collect-evidence repair_proposals.status = 'evidence_collected', plus the event ci_evidence_collected (services/repairProposalService.js:1504–1536) a proposal stuck at detected safe — unique (repo_id, source_fingerprint), a version check, a replay that is a no-op re-enqueue from the proposal's run identity. No sweep exists
triage-issue issues.triaged_at and the triage_* columns; a decision_log row; managed_actions rows succeeded; a Redis complete marker that lives one hour (workers/triageWorker.js:306, 329–344) an issue with no triaged_at guarded — blocked for one hour by the marker; after that the model call repeats, while the label and the comment stay protected by managed_actions the manual triage command, which clears the keys and re-enqueues
triage-pr a decision_log row; a managed_actions row for the size label. No triage column is written (triageWorker.js:588, 597–611) no decision row for the delivery guarded, as above as above
comment-command none for most commands; only the settings commands write (workers/maintainer/commands.js:54–68) invisible not safe — no deduplication of any kind; the response comment is posted unconditionally (workers/maintainerWorker.js:379–381) the maintainer re-issues the command. Today a lost command leaves no trace
checks-updated merge_queue_entries: status and check columns, when an entry matches the head (services/mergeQueueService.js:136–165) an entry stuck pending safe — conclusions are fetched live re-enqueue. No sweep exists
eval-rollback rollback_events.status = 'reverted' with completed_at (services/errorRecoveryService.js:132–135) a row pending, or none not safe — the table has no unique constraint, and the revert branch name embeds a timestamp (:104), so a second run can open a second revert pull request read rollback_events and look for an existing revert pull request first; otherwise the operator
pr-labeled-auto-merge a merge_queue_entries row, unique on (repo_id, pr_number) (mergeQueueService.js:71–82) a labelled pull request that is not queued partly — the row is safe; the admission comment is posted without a lookup and would duplicate (:89–93, :316–320) the manual admit endpoint (routes/phase2.js:91–102), which accepts the duplicate comment; otherwise the operator
review-submitted the same handler as the row above as above partly, as above as above
pr-closed-or-unlabeled the queue entry's status set to the removal reason; a no-op when nothing is active (mergeQueueService.js:265–268) a stale queue entry safe — idempotent re-enqueue
ingest-test-results test_results rows; the flaky_tests upsert (services/flakyTestService.js:70–117) a run with no rows not safe — test_results has no unique constraint; a second run inserts the rows again and skews the flakiness score needs a per-run deduplication key before any re-run. Today the operator
ai-review ai_reviews: started = completed_at null; completed = completed_at set; published = publication_state = 'published' (services/aiReviewService.js:753–775) a row started and never completed; a check run that never ends not blind — the marker is written before the work and lives one hour; the check run is created unconditionally; the retry branch finalizes as interrupted, as on #494 the manual review command — the only path today. No sweep exists
supersede-review ai_reviews.integrity_state = 'SUPERSEDED' (aiReviewService.js:1310–1330) a published review for an older head, not marked safe — row state and a marker lookup re-enqueue; the next synchronize also re-enqueues
reconcile-pr managed_actions set inactive, status cancelled (services/managedActionService.js:110–115) managed actions still active safe — WHERE active = TRUE re-enqueue

Tally. Of the 17 job names:

Class Count Job names
safe to re-enqueue, or harmless 8 generic-event, sync-installation, sync-repo, collect-evidence, checks-updated, pr-closed-or-unlabeled, supersede-review, reconcile-pr
guarded by a marker that expires 2 triage-issue, triage-pr
not safe without judgement 6 comment-command, eval-rollback, pr-labeled-auto-merge, review-submitted, ingest-test-results, ai-review
no consumer 1 validate-configs

What "approved" still requires. For the six that need judgement and the two that are guarded, one of two things per job type:

  1. a manual procedure, written down — it exists in the code for triage-issue, triage-pr, ai-review and the two admit jobs, and for none of comment-command, eval-rollback, ingest-test-results;
  2. an automatic path behind a precondition that does not exist yet — a per-run key for test_results, a revert-pull-request lookup for eval-rollback, a durable record for comment-command, a find-before-post for the admission comment.

Choosing between them is the maintainer's decision. Building either is on HOLD.

validate-configs is enqueued and never processed

  • The name occurs once in the source: the producer (lib/webhookHandlers/handlePush.js:11). The worker's dispatch has no case for it (workers/webhookWorker.js:29–37).
  • Every push enqueues it with the complete push payload. In production, 249 of the 500 jobs retained on webhook-events are this job — half of that queue's payload copies buy nothing.
  • Whether validation on push was intended is not known from the code. It is a decision, not a defect to fix silently.

Gate 2 — Manual and API payloads, and the proof that nothing clear remains

Baseline: what Redis holds today

Read-only, about 17:12Z. 100 jobs sampled from each set of every queue, each tested for three markers: a payload key, a pull-request object, a repository object.

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 payloadRef and 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

  1. 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.
  2. In CI. A test for every enqueue site that inspects the serialized job data.
  3. 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

@Alajmah

Alajmah commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

#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

  • Handler behaviour, evidence and constraints: as recorded in the gates record at 3847171. No handler line was re-read for this comment.
  • BullMQ interfaces: the public type definitions of the installed bullmq@5.81.3 (dist/esm/classes/job.d.ts, queue-getters.d.ts), read-only.
  • Production Redis: PING, then CONFIG GET, INFO keyspace and INFO persistence. Read-only, 2026-11-22.
  • Backup scripts: scripts/backup.sh and scripts/restore.sh at 3847171.
  • No job was re-enqueued. No key was written. No AOF was rewritten. No backup was touched.

1. The recovery contract

Three statements must hold before a job type may be put back on its queue without judgement.

# Statement Why it is needed
C1 One identity. One job can be told apart from every other by values that survive its loss from Redis: a delivery id, a run id, a proposal fingerprint, a (repo, pull request) pair. A job found absent from Redis can be matched with its evidence only if its identity is known from somewhere else.
C2 Evidence and effect are one write, or a unique key stands in front of the effect. A second run then either finds the work done and stops, or is refused by the database.
C3 No write to GitHub that is not guarded. Every write is either absent, or made only through a durable record that a second run consults. A repeated label, comment or pull request is visible to users and cannot be taken back by a retry.

Four rules bind every recovery path, automatic or manual (maintainer, 2026-11-22):

  1. A job whose effect is confirmed is never run again.
  2. A job whose state is uncertain is never run again.
  3. A job's absence from Redis is not evidence that it did not run.
  4. A new attempt is made only after the previous effect has been checked.

2. Recovery contract tests for the eight safe job types

Each 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.

Job type Identity (C1) Durable evidence Oracle after a second run
sync-installation installation.id installations row, keyed by github_id one row for the github_id; only updated_at may differ
sync-repo repository.id repositories row (updated_at) one row; only updated_at may differ
collect-evidence (repo_id, source_fingerprint) and the run identity repair_proposals.status = 'evidence_collected'; event ci_evidence_collected one proposal and one event; the second run writes no second event
checks-updated (repo_id, pr_number) and the head merge_queue_entries status and check columns one entry; check columns equal the live conclusions
pr-closed-or-unlabeled (repo_id, pr_number) queue entry status, set to the removal reason a second run updates zero rows
supersede-review the review row the job names ai_reviews.integrity_state = 'SUPERSEDED' one transition; a second run changes nothing
reconcile-pr (repo_id, pr_number) managed_actions rows set inactive and cancelled a second run updates zero rows (WHERE active = TRUE)
generic-event none none no test. The handler only logs. Recovery does not apply.

The test, step by step, for each of the seven types

Step Setup What must hold
P1 baseline seed the rows the job needs; run it once record the database change D1 and every GitHub write W1
P2 replay enqueue the same job data again, under a new job id; run it the database equals its state after P1, except timestamps the test names; row counts are unchanged; no unique constraint is raised; no write of W1 is made a second time
P3 lost before it ran fresh seed; do not run P1; run once the result equals D1 and W1 exactly
P4 crash before the first write make the handler fail before its first statement the database is unchanged; the classification is not started
P5 crash between evidence and effect make the handler fail right after it wrote its evidence the classification is confirmed, so the decision is to skip. Where a type has one upsert only, the test asserts instead that one transaction holds the evidence and the effect together
P6 effect sent, answer lost make the GitHub recorder raise after it sent a write the classification is uncertain, so the decision is manual
P7 absent from Redis delete the job from the scratch queue before classifying the decision is the same as with the job present. Absence changes nothing

The suite passes when all seven steps hold for all seven types.

The harness

Part Requirement
Database a scratch PostgreSQL database with every migration applied. Never the production connection
Redis a scratch instance of its own, or a database index set aside for tests. Never the production URL
GitHub the real client modules, backed by a recorder that logs every call and fails the test on any write the test did not declare
Code under test the real worker handlers, with their queue replaced by the scratch one
Evidence that the oracle is real for each type, remove its guard in a scratch copy (drop the unique constraint, remove the WHERE active = TRUE), and require P2 to fail

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

triage-issue and triage-pr are blocked for one hour by a Redis marker. After that the model call repeats, while the label and the comment stay protected by managed_actions. Automatic recovery is a later decision.

Step triage-issue triage-pr
1. Find the evidence issues.triaged_at and the triage_* columns; a decision_log row for the delivery a decision_log row for the delivery; a managed_actions row for the size label
2. Evidence complete confirmed. Nothing is run again confirmed. Nothing is run again
3. No evidence, and the marker key exists the first attempt may still be running. Wait for the marker to expire, then repeat step 1 the same
4. No evidence, and no marker not started, by evidence and not by absence from Redis. The manual triage command is the path that exists today the same
5. Part of the evidence uncertain. The operator decides. Nothing is run again uncertain. The operator decides

4. The six types that need judgement: manual recovery only

For 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.

Job type What is checked, and where Previous effect found Clearly absent Unclear when
comment-command the timeline of the issue or pull request, after the command comment, for the response confirmed. Stop the maintainer issues the command again. No durable record of the command exists today the timeline cannot be read
eval-rollback rollback_events for the incident, then open pull requests whose branch carries the revert prefix confirmed. Stop the operator decides whether a revert is still wanted a pending row exists, or the pull request list cannot be read. A second run can open a second revert pull request
pr-labeled-auto-merge merge_queue_entries for (repo_id, pr_number), then the pull request timeline for the admission comment both are there. Stop the manual admit endpoint the entry exists without the comment. The endpoint accepts a duplicate comment, so the operator chooses between the missing comment and a possible duplicate
review-submitted the same two checks the same the same the same
ingest-test-results test_results rows for the run any row. Stop. A second run would duplicate rows and skew the flakiness score never automatic. The operator reads the worker log for the job id before any decision zero rows. Zero rows does not show whether the job was lost or stopped before its insert
ai-review ai_reviews for the head: completed_at, publication_state; the check run published. Stop the manual review command, the only path today a row started and not completed, or a check run that never ends. The command creates a new check run

5. The Redis cleanup procedure

Order matters: nothing is removed from a job until an encrypted copy of what is removed exists and has been read back.

Phase What it does State
0. Baseline count the jobs that carry a payload, by queue and set, read-only done 2026-11-22: 11,758 jobs retained, about 5,400 carry a payload or a large object
1. Inventory list the job id of every job whose data holds a payload-like key, through Queue#getJobs and Job#toJSON(). Counts and ids go into the record. No job content leaves the host read-only. Not run
2. Migrate for each listed job, write one row to the encrypted store of #10-R1: the queue, the job id, the state, the timestamps and the job data. Read the row back, decrypt it, and require equality with the original before the row counts as migrated HOLD. Needs the store, which is not built
3. Rehearsal outside production a scratch Redis holding synthetic jobs in the old format, built from generated payloads and no production content. Run phases 2 and 4 against it allowed in principle. It needs the tools of phase 2, which do not exist
4. Strip for each migrated job, call Job#updateData() with the payload keys removed and every other key kept, in batches. Between batches compare counts and a sample with the snapshot taken before the batch. A job that fails its comparison is left as it is and listed HOLD
5. Verify the sampling method of phase 0 again, on every queue and every set. Target: zero. Then count payload markers in the AOF file and in the RDB file, which stay above zero until phase 6 read-only
6. Rewrite one AOF rewrite, after the last job in the old format is gone. Before it: disk headroom, memory headroom under the 256 MB limit with noeviction, a fresh backup. After it: zero markers in the new AOF HOLD

Design decisions inside the procedure:

  • Supported interfaces only. The strip uses Job#updateData(). The inventory uses Queue#getJobs, Job#toJSON() and Queue#getJobCounts(). No command edits a job hash directly.
  • Failed jobs keep their error. Stripping in place keeps the job, its state, its failedReason and its stacktrace. Deleting the jobs would lose that evidence, and waiting for retention is not bounded in time. The choice among the three remains the maintainer's.
  • What phase 3 must show before phase 4 is asked for. Every job keeps its id, state, timestamps, attempts, failedReason and stacktrace. Every key of data other than the payload keys is unchanged. The job counts per set are the same before and after. A worker can load every job. The payload marker count is zero.
  • Rollback. Until phase 6 the original bytes are still in the AOF. From phase 4 on, the encrypted rows are the only copy of the removed fields.

6. Copies that live outside the live keys

The cleanup above reaches the live keys. Other copies of the same payload exist, and they do not go away with it.

Copy Where it is How it goes away
live keys Redis db0: 12,187 keys when read phases 2 to 4
AOF file /data/appendonly.aof in the redis_data volume. AOF is on; 45,685,903 bytes when read It holds every command since the last rewrite, so it holds each payload even after the job was stripped. Only phase 6 removes it
RDB file /data/dump.rdb, rewritten under save 3600 1 300 100 60 10000 Replaced at the next save after phase 4. Earlier snapshots survive only inside infrastructure backups
infrastructure backups Backups of CT 115 taken before phase 6. They are expected to include the Docker volume, and with it the old AOF and RDB. The inventory confirms it Not by any step above. They need the retention policy below
file backups scripts/backup.sh has no Redis step: a search for redis, aof and rdb in it finds nothing. scripts/restore.sh restores Redis only if a file named redis_dump.rdb is in the backup directory Nothing to remove unless such a file exists somewhere. That is to be inventoried

Retention and expiry policy (proposed; each point is a decision)

  1. Inventory. List every infrastructure backup of CT 115 taken before phase 6, with its location and the date it rotates out. The inventory has not been made.
  2. No early deletion. Each of those backups stays protected and access-restricted until its own rotation removes it. This design deletes none of them. The backup vzdump-lxc-115-2026_11_21-03_00_04 is excluded from deletion by standing instruction. The maintainer's note is that it rotates out after 2026-11-28.
  3. The condition has a date. "The payload is encrypted at rest" is complete when the last backup from the inventory has rotated out. That date is the latest rotation date in the inventory, and it is known only once the inventory exists.
  4. Until then the condition is recorded as open, with the reason.

7. What has to exist before any of this runs

Needed for What is missing
Phases 2 and 4, and the rehearsal the encrypted store and the one enqueue function of #10-R1, which are on hold
The contract tests a CI job with database and Redis services, and the authorization to write the tests
Phase 6 a separate authorization, with its preconditions met
The expiry policy the backup inventory

State

Item State
Recovery contract tests, 8 types designed here. Not written. Writing them needs authorization
Manual procedures, 2 guarded and 6 that need judgement written here
Redis cleanup designed here. Phase 0 done. Phase 1 not run. Phases 2, 4 and 6 on hold
Backup inventory and expiry policy proposed. Inventory not made
"The payload is encrypted at rest" not complete
Any implementation HOLD

@Alajmah

Alajmah commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

#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

  • Design changes: from the review. No handler line was re-read.
  • Production and the Proxmox host: read-only on 2026-11-22 between 22:14Z and 22:20Z. Times of the vzdump job are in the host's time zone, UTC+3; they are given here in UTC. CONFIG GET, INFO persistence, LASTSAVE, directory listings, the cron entry, the backup log, /etc/pve/jobs.cfg, pct config 115, the vzdump logs.
  • Two Redis backup files were opened with redis-check-rdb. It ran in a container that was removed on exit, with no network, a read-only root, the file mounted read-only, a 256 MB memory cap and a 64 process cap. It reads the file and writes nothing.
  • No backup was created, changed or deleted. No protection flag was set. Nothing was restored.

Correction of an error in comment 7085246710

That comment states that scripts/backup.sh has no Redis step. That is wrong. The script saves Redis: it calls BGSAVE, then copies /data/dump.rdb from the Redis container into the backup directory as redis_dump.rdb, and writes the list of bull:* key names to redis_keys.txt. Eight lines of the script mention Redis. A cron entry on CT 115 runs it every day at 03:00.

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 restore.sh and the backup.sh lines were cut off. I concluded from a truncated output. The maintainer's caution in the review was right.

Everything below uses the corrected fact.


1. Absence of evidence is not evidence of absence

The review: no Redis marker and no completion record does not by itself prove that a job did not run. That holds first for triage-issue, triage-pr and ingest-test-results. A partial set of rows in test_results does not prove that all results were inserted.

Rule adopted. not started is reached only from positive evidence that the handler never began. It is never reached from an absence. Everything else without completion evidence is uncertain, and an uncertain job is never run again automatically.

Job type Step 4 of comment 7085246710 Revision 1
triage-issue, triage-pr no evidence and no marker: "not started", and the manual triage command no evidence and no marker: uncertain. Nothing is run again by rule. The operator decides
ingest-test-results "any row: confirmed" rows present: uncertain whether all of them were inserted. Nothing is run again by rule. Zero rows: uncertain, as before
every other type as written not started only with positive evidence, for example a worker log that shows the job was never taken

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 uncertain whenever the evidence is absent.


2. What the strip covers, and what it leaves alone

The 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.

Job set Treatment
completed stripped in place, after the data was moved to the encrypted store and read back
failed untouched. It is retried from this set, and nothing shows yet that a change of its data leaves that path intact
wait, delayed, active, paused untouched

Before any strip in production, three proofs, each in an isolated environment:

Proof What it must show
Job#updateData() keeps what the job needs after the call: same id, state, timestamps, attempts, failedReason, stacktrace, and every key of data except the payload keys
The moved data comes back the row written to the store decrypts to exactly the original data, compared as canonical JSON, before any job is stripped
An interruption leaves nothing half done the job is either untouched or fully stripped, never in between, and its encrypted row exists before the strip begins. This holds when the process is stopped before, during and after each step

The AOF rewrite stays a separate authorization after all three.


3. Inventory of the backups of Redis

Copy Where Taken Kept Holds payload data in clear
live keys Redis db0, 12,187 keys when read live live yes
live AOF /data/appendonlydir/ in the volume gitwire_redis_data. AOF on, appendfsync everysec, 49,432,211 bytes every write until the next rewrite yes
live RDB /data/dump.rdb in the same volume, last save 22:14:14Z, status ok save 3600 1 300 100 60 10000 replaced at each save yes
file backup /opt/gitwire/backups/<date>/redis_dump.rdb on CT 115, by scripts/backup.sh every day at 03:00Z, by cron the last 10. Now 2026-11-13 to 2026-11-22, 1.3 GB in all yes
infrastructure backup vzdump-lxc-115-<date>.tar.zst on the Proxmox storage local-backup (/mnt/local-backup/dump). Job nightly-critical, mode snapshot, the whole root filesystem, which includes the Docker volumes and the 10 file backups every day at 00:00Z, which is 03:00 in the host's time zone (UTC+3) the last 7. Now 2026-11-16 to 2026-11-22, about 18.7 GB each and 3.42 GB for 2026-11-22 yes, several copies in each archive

Facts read:

  • The newest file backup, 20261122_030001/redis_dump.rdb: redis-check-rdb reports checksum OK, 12,179 keys. The oldest kept, 20261113_030001: OK, 12,174 keys.
  • The Redis container has run for 5 months and PostgreSQL for 3 months; no restart happened during this inventory.
  • Each vzdump archive holds about 11 copies of the Redis data of its day: the live files and up to 10 file backups.
  • A payload copy taken on a day D therefore leaves the file backups by D+10 at the latest, and leaves the vzdump archives by about D+17.

The exception

vzdump-lxc-115-2026_11_21-03_00_04.tar.zst carries no protection flag on the Proxmox host. The job keeps the last 7 archives. Unless a flag is set, the rotation removes the 2026-11-21 archive at the run of 2026-11-28 00:00Z, when seven newer archives exist.

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:

  • For the validator record, it is kept by standing instruction.
  • For the condition "the payload is encrypted at rest", it is one plaintext copy that outlives every daily copy.

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 questions

Is 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.

  • File backup: pg_dump started at 03:00:01 and uses one snapshot for its whole run. The Redis RDB was written at 03:00:19, about 18 seconds later. Whatever changed in PostgreSQL in those 18 seconds is in the Redis copy and not in the PostgreSQL copy.
  • vzdump: one storage snapshot of the whole filesystem, so both data directories are from one instant. Whether PostgreSQL starts cleanly from that copy was not tested.
  • backup.sh copies dump.rdb two seconds after it calls BGSAVE. Redis writes a temporary file and renames it, so the copy is always a complete RDB, but it can be the previous one when the save takes longer than two seconds.

Can the job state be restored without running an undetermined effect again? Not by starting the workers on a restored queue.

Job in the restored copy What happens when the workers start Risk
it was active at the snapshot its lock is old. BullMQ moves such jobs back to the wait list (the installed 5.81.3 has moveStalledJobsToWait and maxStalledCount for this) it runs again, although its first run may have completed after the snapshot
it completed after the snapshot it is in the wait or delayed list again it runs again
it was enqueued after the snapshot it is not there it never runs

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, confirmed and uncertain jobs removed by hand, and only what is not started on positive evidence left to run. That is design. No tool for it exists.

Proposed: the isolated restore test

A 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

  • The two backups do not meet. The vzdump snapshot of a day is taken at 00:00Z and holds the file backups made until 03:00Z of the day before. That day's own file backup follows three hours later. So the newest complete pair of a day is never in the archive of the same day.
  • In each file backup gitops_hub.dump has mode 644 in a directory with mode 755. redis_dump.rdb and web.env have mode 600. The host has two accounts with a shell, root and runner.

State

Item State
Recovery contract tests, 8 types designed, with the uncertain rule of Revision 1. Not written
Manual procedures, 2 guarded and 6 that need judgement written, with Revision 1
Strip of completed jobs designed. Scope: completed jobs only. The three proofs are specified and not run
Backup inventory done, read-only
Restore test with synthetic data proposed. Not written
Restore test with real data not run. Venue to be decided
Phase 1 of the cleanup (inventory of the jobs) read-only. Not run
Phases 2, 4 and 6 (migrate, strip, rewrite) HOLD
Protection flag on the 2026-11-21 archive not set. Decision needed before the run of 2026-11-28 00:00Z
"The payload is encrypted at rest" not complete

@Alajmah

Alajmah commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

#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

Step Result
Identity confirmed first the archive is vzdump-lxc-115-2026_11_21-03_00_04.tar.zst on the storage local-backup (/mnt/local-backup/dump). CT 115 is the running container with the hostname gitwire. Host: node pve, PVE 8.4.21
Protection set at 2026-11-23 04:37:24Z, through the Proxmox API, on this archive only: pvesh set /nodes/pve/storage/local-backup/content/backup/<archive> --protected 1
Read back the API returns "protected":1 for the archive. Among the 7 archives of CT 115 it is the only protected one. On the whole storage, 28 archives, 1 protected
The archive itself not touched. Before and after: the same inode, 19,849,287,903 bytes, mode 644 root:root, the same modification time and the same change time to the nanosecond. One empty file was created next to it, <archive>.protected. Its log file is unchanged. It is one file, not split into parts
Access unchanged: mode 644 in directories of mode 755, owned by root. The only account with a shell on the host is root, and the only Proxmox user is root@pam. The storage is not exported by NFS or Samba
Daily backup unchanged. /etc/pve/jobs.cfg has the same checksum before and after: job nightly-critical, enabled, keep-last=7, every day at 03:00 host time. The scheduler is active
Storage headroom unchanged by the flag: used 248,631,016 KB, available 711,655,404 KB, before and after

The flag has the effect intended

The host has a read-only preview of pruning. It was asked for CT 115 with three window sizes:

Window 2026-11-17 … 2026-11-20 2026-11-21 2026-11-22 and 2026-11-23
keep-last=7 (the job's setting) keep protected keep
keep-last=2 remove protected keep
keep-last=1 remove protected remove (11-22), keep (11-23)

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 GET, from the prune itself, a DELETE. The DELETE was not called.

What this means for the design

  • A long-term exception. Until a decision removes the flag, the archive stays. It holds 19.85 GB. The storage for this container now grows by one protected archive beyond the seven that rotate.
  • Protection from deletion is not protection from disclosure. The archive holds the Redis data of 2026-11-21 in clear, as the inventory of Revision 1 records, and it holds the PostgreSQL data and the configuration of that day too. Access is limited to root on the host. It stays limited.
  • The condition stays open. "The payload is encrypted at rest" cannot be declared complete while this archive is kept, by the maintainer's rule of 2026-11-22.
  • The validator record depends on it. The archive is the source of the validator image recovery. The recovery copies on the Proxmox host and on the workstation are unaffected.

Not done

  • The flag is the only change on the host. No archive was moved, recompressed or deleted, and no retention setting was changed.
  • The flag can be removed later with the same API call and --protected 0. That is a decision for later.
  • A content hash of the archive was not computed. That it was not modified rests on the unchanged inode, size, modification time and change time.

@Alajmah

Alajmah commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

#10-R1 — the synthetic restore trial passed; the plan for the real-data trial (2026-11-23)

The synthetic trial

Branch study/redis-restore-synthetic-v5, run 45116541475: success. Two throwaway Redis instances on the runner, generated jobs with no secrets, and a BullMQ worker from the repository's own lockfile. A snapshot was taken by BGSAVE while one job was active, the RDB file was moved into the second instance exactly as a restore would, and a second worker started on it.

The states at the snapshot were as designed: J0 completed, J1 active, J2–J5 waiting, JD delayed. On instance A, afterwards, J0–J4 finished.

Job State at the snapshot Ran again on the restored queue
J0 completed (before the snapshot) no
J1 active yes
J2, J3 waiting; they completed on A after the snapshot yes
J4, J5 waiting; J4 also completed on A, J5 never ran yes
JD delayed 30 minutes no; still delayed, schedule intact

The assertion of the trial, mismatches: [], is the rule of Revision 1 in numbers: a job runs again on a restored queue exactly when its state at the snapshot was active or waiting. What became of it afterwards does not matter, so a job that already completed after the snapshot runs a second time. This is why a restore is not safe until the wait, delayed and active lists are classified against durable evidence.

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 data

For 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.

Point Proposal
Container a new LXC on the Proxmox host, unprivileged, 2 cores, 2 GB memory, 10 GB disk on local, no swap requirement. Temporary id and name, e.g. restorelab
Network an internal bridge only, or no network device at all. No route to 192.168.3.0/24, no gateway to the internet, no DNS. Tools and images enter through a temporary bind mount from the host, which is detached before the data arrives
Data in one pair of files from one dated backup directory of CT 115, read through a bind mount opened read-only for the duration: gitops_hub.dump and redis_dump.rdb. Nothing else, no .env, no keys, no compose file
What runs redis:7-alpine and postgres:16-alpine as plain containers in the lab container, and small read-only scripts. Level 1: redis-check-rdb and pg_restore --list. Level 2: Redis loads the RDB and answers key counts by prefix; PostgreSQL restores the dump and answers row counts for a fixed table list. No BullMQ worker, no GitWire service, nothing that can produce an external effect
Accounts the lab runs as root inside its own container; the host sees only the Proxmox API
Data out the numbers only: counts and names, no payload contents. The scripts print counts, never values
Removal after the evidence is recorded, the containers, their volumes and the container itself are destroyed, and the disk with it. Proposed retention before destruction: 48 hours, for a re-read if a number is questioned

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

Item State
Synthetic trial passed, run 45116541475
Trial with real data plan above. Waits for the approval of its parameters
Workers on a restored copy forbidden
Production Redis, the strip, the AOF rewrite HOLD

@Alajmah

Alajmah commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

#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

Point As built
Container LXC 911 on the Proxmox host, unprivileged, 2 cores, 2 GB, 10 GB on local, no network device at all, onboot 0. The nesting feature was removed before the data arrived
Isolation, read from inside only the loopback interface; 0 routes; CT 115, the host bridge and the internet unreachable; DNS lookup fails; no Docker socket; no host path mounted except the pair
The pair the dated backup 20261123_030001 on CT 115: gitops_hub.dump, 100,416,271 bytes, and redis_dump.rdb, 35,908,625 bytes. Streamed from CT 115 to /root/lab-911/data on the Proxmox host through a pipe; nothing was written on the workstation. The sha256 of the two files is the same on CT 115 and on the host
How the lab saw it a bind mount with ro=1, the files as nobody:nogroup 644. Five kinds of write from inside were refused: create, append, delete, chmod, mkdir
Storage, checked before the import 8.4 GB free on 9.8 GB. Needed: a 36 MB working copy of the RDB, the database (474 MB in production, with indexes and WAL), small temporary files
PostgreSQL 16.15, from the Ubuntu packages, carried in as files: 21 packages, each checked against the sha256 in the Ubuntu index
Redis the engine of production: the layers of redis@sha256:6ab0b6e73817… pulled on the workstation from the registry, each layer's sha256 checked against the manifest. redis-server, redis-cli, redis-check-rdb and four libraries were carried in. It reports v7.4.9
Not used Docker. The lab had no network to fetch images, so the two engines were run directly, which the review allowed. Docker inside an unprivileged LXC was not tried
Not present no credentials, no worker, no GitWire service. PostgreSQL and Redis listened on 127.0.0.1 only

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

Check Result
redis-check-rdb 7.4.9, the engine of production Checksum OK, RDB looks OK, 12,181 keys read, 18 with an expiry, 0 subexpires
redis-check-rdb 7.0.15, the distribution's exit 1: Can't handle RDB format version 12, 0 keys read
pg_restore --list exit 0. 77 tables, 77 table data entries, 50 sequences, 139 indexes, 134 constraints, 95 foreign keys, 64 privilege entries, 49 default privilege entries

Level 2: both restore

Redis. DB loaded from disk in 0.422 seconds.

Reading Value
Keys 12,163. The check read 12,181; the 18 with an expiry had expired by the time of the load
Memory 147.26 MB
Keys by type hash 12,103; zset 32; string 13; stream 13; list 2
Key families bull 12,162; gitwire 1
Job hashes that carry a failedReason 5,652. The failed sets hold 5,648
Queue Job hashes completed failed delayed active
ci-evidence 552 500 51 – –
ci-healing 501 500 – – –
critic 1 – – – –
diagnosis 501 500 – – –
issue-fix 128 110 17 – –
maintainer 1,821 500 1,000 160 –
patch 1,501 500 1,000 – –
phase2 1,501 500 1,000 – –
phase3 1,507 500 1,000 3 –
phase4 507 500 4 1 –
sync 610 500 106 1 1
triage 971 500 470 – –
verification 1,501 500 1,000 – –
webhook-events 501 500 – – –
Sum 12,103 6,110 5,648 165 1

179 job hashes are in none of these sets; 161 of them are in maintainer. Not examined.

PostgreSQL. A fresh cluster cannot restore this dump as it is. The first attempt stopped at the first privilege statement: role "gitwire_auth_fn_owner" does not exist. The dump names six roles: gitwire, gitwire_admission, gitwire_app, gitwire_auth_fn_owner, gitwire_executor, gitwire_operator. After they were created, without login and not superuser, the restore with ownership kept ended with exit 0 and an empty log, in 25 seconds.

Reading Value
Schemas 2
Tables 77: 62 in public, 15 in gitwire_auth. All 77 owned by gitwire
Other objects 1 view, 50 sequences, 273 indexes, 67 functions, 52 triggers, 95 foreign keys
Database size 429 MB
Exact row count taken for 77 of 77 tables, no error
Rows in all tables 928,895: 323,121 in public, 605,774 in gitwire_auth
Tables by rows 25 empty; 31 with 1 to 99; 16 with 100 to 9,999; 5 with 10,000 and more
Largest tables auth_decision_log 555,643; webhook_deliveries 208,980; attribution_gap_evidence 50,108; repair_proposal_events 34,447; ci_runs 31,692
Constraints and indexes 378 validated constraints; 0 invalid indexes; 43 of 50 sequences have a value

The two files are not one atomic snapshot

pg_dump took its snapshot at the start of the run, about 03:00:01Z. The RDB was written at 03:00:19Z. They come from the same dated folder and are about 18 seconds apart. A matching date does not show that they are consistent with each other.

What the trial showed about the existing restore path

Read from scripts/restore.sh on master, not exercised:

Step of the script Observation
PostgreSQL, lines 63–70 restores with --no-owner --no-acl. That skips the 64 privilege entries and the 49 default privilege entries of the dump. After such a restore the roles other than the owner hold no privileges on the database
PostgreSQL, line 72 and line 110 the check counts tables in public only. The 15 tables of gitwire_auth are not counted
Redis, lines 80–85 copies dump.rdb into the existing volume, next to the AOF files. The compose file starts Redis with --appendonly yes. Whether the server then loads the RDB or the AOF was not tested
Restart, line 96 docker compose up -d starts every service, the workers included, on the restored queue. The synthetic trial of comment 7092268545 showed which jobs run again

One more fact for the Redis step: the file can be read only by Redis 7.4 or later. redis:7-alpine satisfies that today.

Removal

Item State
Lab shut down and destroyed at 07:16Z with pct destroy --purge: no configuration file, no disk volume, no mount left
Host scratch /root/lab-911, /tmp/lab-911-debs, /tmp/lab-911-image removed. 0 paths with the name left on the host
The two data copies on the host an overwrite before the removal was requested; its report was discarded, so the overwrite is not confirmed. The files are removed
Workstation scratch held public packages and image layers only; removed. The three output files of the trial, counts only, are kept
Originals on CT 115 sha256 and modification times the same before and after
Protected archive of 2026-11-21 still protected: 1. The backup job is unchanged

Errors of mine during the trial

  • The first pass read Redis while it was still loading and used an option that this redis-cli does not have. Its counts were void. The second pass corrected both.
  • The first extraction of the roles matched table names too, 65 names in all. Two role creations failed harmlessly (current_user, pg_extension). The six roles above are the ones the restore needed.
  • Before the lab existed, I tried to write a copy of the dump into the production PostgreSQL container to measure a size. Nothing was written, the empty file was removed at once, and the container's /tmp holds 0 entries. It should not have been attempted; the measurement belonged in the lab.
  • In my working notes I called containers 216 and 801 unprivileged. Their init process runs as host uid 0, so they are privileged. No container on this host runs Docker as unprivileged.

What this shows and what it does not

It 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

Item State
Levels 1 and 2 with real data done
Workers on restored data forbidden; not done
Production untouched, apart from reading the two files out
The restore path four observations above; no change made
The strip, the migration, the AOF rewrite HOLD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant