Dimension-Driven Executors

The needs_* decider, the MR executor actions, and the dimension-kind machinery. Part of the design decision registry.

DDR-45: Dimension-driven decider with needs_* flags

Decision: The decider scans needs_* dimensions in priority order instead of encoding per-concern conditionals.

Context: The original decider checked item.mr_iid is None for create, dashboard_link dimension absence for dashboard notes, and would need more checks for auto-merge, stale detection, metadata sync. Each new concern added another conditional.

Alternatives: (a) Per-concern conditionals in decider. (b) Dimension-driven: events/executors set needs_* flags, decider scans them.

Rationale: Option (b). The decider becomes a simple priority scan. Executors own their trigger-to-next-step logic by setting the appropriate needs_* dimension. Events set needs_reconcile to request re-evaluation. Adding a new concern = new dimension + handler in reconciler, no decider changes needed.

Update (DDR-48): The original three-category model (has_*, needs_*, observed state) was unified into a single needs_* trigger model with "true"/"false" status. See DDR-48.

DDR-46: reconcile_mr pattern

Updated by DDR-52. The “merge latency to seconds” trade-off below did not hold on busy target branches: the branch churn (largely the workqueue’s own fleet) resets mergeability to unchecked faster than the 30-minute cadence re-samples it, starving managed MRs for days. DDR-52 adds the deadline-driven sweep and an adaptive recheck backoff that remove this failure mode; the direct-merge decision itself stands.

Decision: Single reconcile_mr executor handles all MR state convergence, with cheap (always) and expensive (flagged) tiers. Uses direct mr.merge() instead of GitLab auto-merge.

Context: Separate executors per concern (check_stale_mr, enable_auto_merge, sync_metadata) each needed their own registration, decider rule, and dimension tracking. GitLab auto-merge (auto_merge=True) introduced state-management complexity: merge_when_pipeline_succeeds tracking, stale SHA detection after force-push, and recurring 422 noise for non-mergeable MRs.

Rationale: One mergerequests.get() call serves all cheap checks. The reconciler checks detailed_merge_status == "mergeable" and calls mr.merge() directly — no GitLab auto-merge state to track, no skip-lists to maintain, no stale SHA detection. Pipeline completion and approval webhooks trigger reconcile via the needs_reconcile dimension, keeping merge latency to seconds. Expensive operations (empty diff via repository_compare) only run when needs_empty_check is actionable (periodic via pending_until, DDR-48). The reconciler is idempotent — all corrections are conditional on actual vs desired state.

DDR-47: CI job retry herder

Updated by DDR-48. The needs_ci_retry="pending_tick_5m" status and tick_5m promotion mechanism have been replaced by pending_until on the dimension row.

Problem: Hummingbird CI pipelines frequently fail due to transient infrastructure errors (runner system failures, git clone timeouts, OOM kills). Manual retries waste developer time and delay merges.

Options considered:

  • A. Executor action in workqueue-service (selected): Shares existing GitLab tokens, project config, DB-persisted state, and audit trail.
  • B. Standalone herder service: Maximum CKI fidelity but requires a new deployment, duplicates token management, and has no MR lifecycle integration.
  • C. Reconciliation polling: No new webhooks, but 30-minute detection latency and wastes API calls polling healthy pipelines.

Decision: Option A. The matcher engine is ported from the CKI pipeline-herder with a reduced field set. Build events are received via the existing SNS→SQS pipeline and resolved to MR work items by matching pipeline_id against head_pipeline_id on mr_details.

DDR-48: Uniform needs_* dimension model with pending_until

Decision: Unify all dimensions under a single needs_* trigger model with "true"/"false" status and an optional pending_until column for deferred re-evaluation. Drop synthetic tick events.

Context: The dimension system had grown three distinct categories (DDR-45): has_* positive completion markers, needs_* action triggers, and observed state dimensions (approval, pipeline, merge_status, has_conflicts). The has_* and needs_* split created asymmetric decider logic. Observed state dimensions were write-only — the reconciler set them but no code read them. The tick_5m/tick_30m synthetic event mechanism (DDR-42) required hash bucketing, NOT EXISTS guards, and special "pending_tick_5m" status values.

Alternatives: (a) Keep the three-category model and add pending_until alongside tick events — increases complexity with two deferral mechanisms. (b) Unify to needs_* with pending_until.

Rationale: Option (b).

  • Uniform semantics: every dimension is a needs_* trigger. Status is "true" (action needed) or "false" (handled). The decider uses a single check pattern: != "false" means actionable.
  • Absent = actionable: missing dimension rows are treated as needing action, so new items don’t require explicit initialization of every dimension.
  • pending_until replaces ticks: executors set pending_until to schedule future re-evaluation. The sweep finds expired pending_until and notifies — no synthetic events, no hash bucketing, no "pending_tick_5m" status values.
  • Dropped dimensions: approval, merge_status, has_conflicts were write-only. The pipeline dimension carried a single integer and is better modeled as a typed column on mr_details.
  • Deferred dimensions: the decider pre-filters dimensions where pending_until is in the future, treating them as "false".

DDR-49: Replace pending_action TEXT with actionable BOOLEAN

Decision: Drop the pending_action TEXT column. Replace it with actionable BOOLEAN DEFAULT FALSE. The decider is called in exactly one place: the processing loop’s derive-and-dispatch step.

Context: pending_action served three roles: (1) sweep discoverability (WHERE pending_action IS NOT NULL), (2) processing loop continue/exit signal, (3) executor dispatch key. Roles 2 and 3 made the column authoritative for which action to run, creating a sync burden with the dimension-driven decider.

Alternatives:

  • Remove entirely — rejected: the decider treats absent dimensions as actionable, so a SQL query over dimension rows cannot find items whose next action derives from a missing row. A wake-up signal persisted to the DB is required.
  • next_action TEXT (renamed cache) — rejected: requires decider.decide() calls in the CRUD layer. The authoritative-looking name invites future dispatch reads.
  • actionable BOOLEAN — selected.

Rationale: A boolean is sufficient to bridge the absent-dimension discoverability gap. Stale True is harmless (false-positive sweep → loop starts, decider returns None, exits immediately). actionable is written in exactly two places: True when work is enqueued (creation, update, retry, event insertion), False only on the loop’s exit branch (committed atomically when both decider.decide() returns None and no pending events exist). This invariant ensures the item stays sweep-visible throughout processing — a crash at any point leaves actionable = True, preventing items from becoming permanently stuck.

DDR-50: Event drain tolerates concurrent deletion

Decision: The event drain (_process_pending_events) reads the (id, event_type, event_body) of all listed pending events before processing the first one, and deletes rows by id. A row deleted by another pod mid-drain makes the delete a no-op instead of an error.

Context: The lease is acquired once per loop run and renewed only while executor actions run; it is neither renewed nor re-checked during the drain, and the per-item deadline is only checked between drains (DDR-44). A slow drain can therefore outlive the lease — most notably during rolling deployments, where the terminating pod’s in-flight drain overlaps the new pod’s startup sweep. Committing per event expires the remaining ORM instances, so the next iteration’s attribute access lazily refreshes against the database; when the other pod already deleted that row, SQLAlchemy raises ObjectDeletedError and the whole work-item loop dies (observed as Sentry issue 7829339838, 35 seconds after a rollout).

Alternatives:

  • Hold the per-item advisory lock across the drain — rejected: the lock is transaction-scoped (DDR-34) and the drain commits per event for crash isolation; spanning all events would require a single transaction and lose per-event progress.
  • Renew or re-check the lease inside the drain — rejected: shrinks but does not close the takeover window (the lease can still expire mid-iteration), and does not fix the stale-instance crash itself.
  • Re-query each event before processing it — rejected: adds a query per event, and the row can still vanish between the check and the delete.

Rationale: Reading the attributes while the instances are fresh — before the first commit — means no lazy refresh can fire mid-drain, and delete-by-id is naturally idempotent. An event may then be applied by both pods, but application is already at-least-once for crash recovery (DDR-31) and idempotent (dimension upserts, last_event_at guard). The drain becomes robust no matter which actor deletes a row.

DDR-51: Per-item processing ownership and exit safety

Decision: Loop ownership is a loop-lifetime session advisory lock — pg_try_advisory_lock(0x5751, work_item_id.int & 0x7FFFFFFF) taken on a pinned connection at loop entry — and the loop’s exit decision runs under a SELECT ... FOR UPDATE row lock on work_items. The leased_until lease with its heartbeat (DDR-6) and the insert/exit advisory-lock handshake (DDR-34) are removed; the column is dropped by the contract migration after the redesigned version has fully rolled out.

Context: DDR-29/DDR-30 require at most one processing loop per work item across pods, but no mechanism delivered that invariant. The lease was acquired once per loop run, renewed only while an action ran, and had no owner, so it excluded only the next action, not the loop. The exit wrote actionable = false blindly, so an API enqueue committing between the loop’s state read and that write was overwritten — permanently stalling items whose only wake-up signal was a PROCESS_IMMEDIATELY dimension (no pending_events row, invisible to every sweep leg). The transaction-scoped advisory lock covered only the consumer’s INSERT and the exit, not the API writers. The 2026-11-04 ObjectDeletedError (Sentry 7829339838) was one symptom: a new pod’s startup sweep took an item whose lease the old loop had cleared between actions. !1494 (DDR-50) fixed the crash, not the ownership model.

The two-32-bit-key form (classid=0x5751, objsubid=2 in pg_locks) deliberately does not overlap the legacy single-64-bit-key space (objsubid=1), so during a mixed-version rolling update an old pod’s handshake and a new pod’s session lock cannot block each other.

The key is the item UUID’s low 31 bits — the positive range of the int4 second argument. Two unrelated items whose UUIDs share those bits collide: the loser returns immediately (counted in hummingbird_workqueue_processing_lock_skipped_total) and the sweep re-spawns it once the winner’s loop finishes. A collision delays one item; it never allows two loops for the same item and never loses work.

Every enqueue path already updates the work_items row in the same transaction as its durable write (dimension upsert, pending_events insert, retry mark). The row lock serializes the exit against all of them without any new protocol; this contract is now explicit and must hold for future enqueue paths.

Alternatives:

  • Compare-and-set on a new revision column — correct and non-blocking, but adds a migration and a permanent column, and onupdate is ORM-level, so old-pod writers would not bump it during the rollout.
  • CAS on updated_at or xmin — no migration, but updated_at is transaction-start time (uniqueness only by microsecond) and xmin is an obscure system column with freeze/wrap edge cases.
  • Durable enqueue token (a wake-up row per enqueue, consumed only on a clean exit, enumerated by the sweep) — the structural fix that removes the shared-boolean race by construction; deferred as a larger change (a table, an insert on every enqueue path, a drain lifecycle, and a sweep leg).
  • Extend the advisory lock to API writers — couples synchronous HTTP handlers to the processing lock for a whole loop and reintroduces the bug whenever a writer forgets.
  • Fix the timestamp lease in place (owner token, renewal for the whole loop, re-assert before each action) — time-based expiry still cannot exclude a paused or partitioned worker holding the lock past its TTL, and keeps the heartbeat machinery.
  • SERIALIZABLE exit transaction — PostgreSQL SSI only guarantees serialization among serializable transactions; mixing isolation levels and retrying under contention is more machinery than the row lock.
  • Leader election / single-writer pod — removes rollout overlap but defeats replica throughput and distinct-item parallelism.

Rationale: The session lock makes “one loop per item” true by construction for the whole loop lifetime, not per action: a loser returns immediately without holding a worker slot, crashes recover through connection death plus the sweep, and no TTL or heartbeat is needed. The row lock makes the exit decision atomic with respect to every writer without a migration, and old-pod writers block on it too. A spawn request that arrives while the loop is still exiting is captured by a per-item rerun flag, and after a clean exit the loop unlocks, re-checks for work, and re-acquires if a writer slipped in.

Each running loop pins one pooled connection (pool sized to the worker count with overflow headroom, pool_pre_ping, libpq keepalives and tcp_user_timeout), and every loop session binds to it. A dead connection therefore fails the work — the exception propagates and the loop aborts — instead of leaving a loop running under a lock the server already released; the still-actionable item is recovered by the sweep. The API request path can block for the duration of the exit decision (a few DB-only statements), so the exit transaction must stay DB-only.

During a mixed-version rolling update, an old pod’s leased loop and a new pod’s locked loop can briefly both run the same executor action for one item: the two-key lock cannot conflict with the old lease path. Read-and-upsert actions (reconcile_mr, ensure_plr_status, ensure_expected_plrs) converge on the same state. Creation actions and retry_ci_jobs check their result field (e.g. mr_iid) before acting, so a duplicate requires both loops to pass that check before either commits — possible in the worst case, producing one duplicate external mutation (a second MR or note, or a second CI retry) for an item mid-action during the pod replacement. New pods deliberately do not skip rows with an unexpired leased_until: a lease written by a pod that died mid-rollout must not hide the item. The window is bounded by the rollout and ends when the contract migration drops the column.

DDR-52: Deadline-driven sweep and adaptive merge-recheck

Decision: The sweep wakes at deadlines instead of polling: after each pass it sleeps until the earliest armed pending_until (plus ~1 s epsilon), capped at the former 5-minute interval as a backstop — or for just the epsilon when a deferred timer is already due, letting the next pass’s expired scan pick it up. unchecked/checking/unknown merge statuses re-arm needs_reconcile at now + RetrySchedule.delay(step) on an exponential schedule (15 s, doubling, 5-minute cap) with the step persisted in the dimension detail, and a partial index on work_item_statuses (pending_until) covers the sweep’s hot path.

Context: The direct-merge design (DDR-46 lineage; !1327) merges when a reconcile GET observes detailed_merge_status == "mergeable", with a 30-minute retry cadence and the sweep (fixed 5 minutes) as the only timer. On busy target branches this starves: every push to the target branch resets stored mergeability to unchecked, GitLab recomputes it only lazily on a single-MR GET (seconds), the service samples once per 30 minutes, and GitLab emits no webhook when a recheck completes. Evidence: containers!22697 unmerged 6 days while green; 2026-11-10 logs show 15/16 reconcile GETs observing unchecked and the two mergeable observations losing the merge PUT race to concurrent fleet merges (422 “Branch cannot be merged”). The branch churn is largely the workqueue’s own lockfile fleet (59 merges in two hours on 2026-11-10), so the service invalidates its own merge candidates. The branch churn also means any fixed short interval is a compromise: real blockers need minutes, rechecks need seconds.

now is passed to the deadline query as a bound parameter rather than SQL now() because pending_until values are written with the Python clock; comparing in one clock domain avoids app-vs-DB skew shifting wakeups. The MIN query mirrors find_expired_pending’s item filters (active phase, accepted types) so completed items — which keep their last dimension rows — cannot pin the sweep to a stale deadline. The deadline lookup computes the earliest future deadline and a past-due flag in one filtered-aggregate query — one snapshot — so a timer expiring between the sweep’s expired scan and the lookup cannot be missed by both; the past-due flag excludes actionable items, mirroring the expired scan, so a running loop’s timer cannot spin the sweep. A wake event interrupts the sleep when an earlier deadline is armed in-process (set from spawn_loop()’s enqueue paths and after executor action commits; sweep-initiated submissions deliberately do not poke — they arm no timer, and poking would wake the sweep into a pass that re-submits, spinning cross-pod while another pod’s loop holds the item lock during a rollout); spurious wakes cost one indexed query and a no-op sweep. Multi-pod: each pod computes its own MIN; the arming pod wakes exactly, others see the work within the backstop cap, and duplicate spawns are absorbed by the per-item advisory lock (DDR-51).

Alternatives:

  • Shorter fixed sweep interval — wasted cycles and still granular; a +30 s timer would still round up to the interval.
  • Short dimension timers without a sweep change — the 5-minute sweep granularity silently becomes the effective interval; the timer is a lie without deadline-driven wakeups.
  • Sleeping and re-GETting inside the executor — holds a worker slot (10 max) and the pinned DB connection, brushes the 60-second item deadline (DDR-44), and violates the “reconcile_mr: cheap operations only” contract (DDR-46).
  • Fixed fast interval without backoff — a permanently-unchecked MR would poll ~2880×/day.
  • Backoff step derived from row timestamps (updated_at deltas) — fragile, implicit, breaks on any other write to the dimension row.
  • RetryAfter state merged into the crud state union with a reserved detail key — more machinery and magic than needed for one consumer; revisit on a second non-MR consumer.
  • Re-enabling GitLab server-side auto-merge — removes service ownership of the merge decision (DDR-46); the adaptive recheck achieves convergence without it.

Rationale: A mergeable MR converges within one or two recheck probes (~15–45 s) instead of winning a 30-minute lottery, and concurrent-merge race losers recover within seconds, so the fleet race self-heals — the 422 → immediate retry → unchecked → +15 s → mergeable → merged sequence replaces the 30-minute re-sample. unknown shares the fast family (GitLab documents it alongside unchecked); a persistent unknown settles at the 5-minute cap, and the mr.state != "opened" guard keeps closed/merged MRs from being polled. Permanently-unchecked MRs poll at the 5-minute cap (the same cadence as error backoff), visible via the hummingbird_workqueue_merge_rechecks_total counter labeled by merge status. Real blockers keep the 30-minute cadence and reset the backoff step (detail=None, the documented clear path); webhook re-arms preserve the step (the _PRESERVE sentinel) and consume one — each immediate reconcile observing unchecked advances the backoff, deliberately throttling poll storms on chatty MRs. The GitLab-error path (the 5-minute error re-arm without a detail write) also preserves a matured step, so the first unchecked probe after an outage waits at the cap — deliberate. The sweep runs as often as the earliest deadline (potentially every ~15 s under recheck storms); each pass is one indexed MIN query, one expired-pending query, and the actionable-or-pending-events union query, and only items with due work spawn loops — hence the partial index. The direct-merge decision stands; this record removes its starvation failure mode on busy branches. Rollout: the deadline-driven sweep and its supporting partial index land first, then the reusable RetrySchedule type, then the merge-recheck application (schedule constant, detail step, outcome enum, metric, and docs); the migration adds the partial index only.

DDR-53: Scenario-keyed test PLR tracking in the unified needs_plr dimension

Decision: Test PipelineRuns are tracked in the existing needs_plr / needs_expected_plrs dimension pair alongside build PLRs, not in a separate pair. NeedsPlrDetail gains a scenarios section (dict[scenario → {group: PlrInfo, components: dict[comp → PlrInfo]}]) next to the existing components section; NeedsExpectedPlrsDetail gains scenarios, group_apps, group_scenarios, and pr_group_sha fields. ensure_expected_plrs fetches the manifest once and derives both build and test expectations. ensure_plr_status polls both selectors and merges both sections. needs_plr arms when either build components or test scenarios are expected; it reaches DONE only when both sections are terminal.

Test PLR events are classified via the group-test-info annotation vs the component label: Konflux creates test PLRs per snapshot (per-component and PR-group), so multiple PLRs per scenario are normal; newest-by-startTime wins across distinct runs within each slot, and for the same PipelineRun (same metadata.name) the fetched status always updates the stored one so the fallback poll recovers Running slots once a run finishes. Group test PLRs are selected by MR identity read from the group-test-info annotation — each entry carries pullRequestNumber and repoUrl, and the event resolver matches active items by MR iid + project from those entries. The 30-minute fallback poll queries the test.appstudio.openshift.io/pr-group-sha label with test.appstudio.openshift.io/type=group: the hash is sha256(source_branch)[:62], stored in the expectation detail (derived from the source branch for details that predate the field) and cross-checked against the pr-group-sha label the push’s build PLRs carry, adopting the observed value on mismatch. The cross-check reads only build PLRs carrying this MR’s pipelinesascode.tekton.dev/pull-request and url-repository identity labels (verified on production build PLRs to carry the bare MR number and bare repository name), so a build from another MR sharing the head commit — a branch forked from another open-MR branch — cannot redirect the group poll; with no verifiably-own build carrying the label, the stored or computed hash stays in force. Because the branch key can surface runs from other MRs sharing the branch name, the poll keeps only runs whose annotation names the item’s MR, on top of the constituent build-PLR-name validation. Expectations are presence-based: for each application with at least one path-matched component in the MR’s changed files, every entry of the integration_test_scenarios section of that application in the PR manifest must have at least one observed test PLR for the item SHA, and all observed PLRs of expected scenarios must have reached a terminal state (Succeeded or Failed). A Failed scenario is terminal for lifecycle purposes — the 30-min fallback poll stops — and the status note renders it red. The absent-section case (integration_test_scenarios key missing from the manifest) is treated as no expectations. For scenarios the PR manifest marks group: true, the per-app group run is additionally required when that application has ≥2 affected components; scenarios marked group: false never produce group runs.

Context: The SNS FilterPolicy already delivers all PipelineRun events; test PLRs were dropped only at _mr_resolve’s type == "build" gate, and the test SHA label fallback (pac.test.appstudio.openshift.io/sha) was already implemented. The build component tracking (NeedsPlrDetail.components) assumes one PLR per component — wrong for tests, where a multi-component MR yields per-component plus PR-group runs per scenario — hence the separate scenarios section. Scenario granularity matches how results surface in GitLab (Konflux kflux-prd-rh03 / … commit statuses). Presence-based expectations avoid re-deriving Konflux snapshot internals while still catching the failure mode that matters for the later approval gate: a missing or red scenario.

Production verification (Nov 24, 2026) drove the selection keys: group test PLRs carry no pac.test.appstudio.openshift.io/pull-request label — 0 of 269 runs in a 7-day window, re-confirmed across a 500-run KubeArchive sample — so selecting by that label (the initial resolver and fallback-poll mechanism) matched nothing and group runs were unreachable for every MR. MR identity lives only inside the group-test-info annotation, and pr-group-sha is the platform’s own PR-group join key (the Konflux integration service label-selects by it; KubeArchive indexes label selectors), so the event path resolves via the annotation and the poll selects by the pr-group-sha label — bounded by the branch’s push generations rather than global group-run growth.

Alternatives:

  • Separate needs_expected_test_plrs / needs_test_plr dimensions (rejected): mirroring the build pair isolates the concerns at the dimension level but duplicates all staleness/merge/terminality machinery into a second copy that must be kept in sync. The algorithms are identical in both sections; the data structures differ only in the per-scenario nesting vs the per-component flat dict. A second dimension pair adds two executor functions, two decider arms, and two sets of reset calls in ensure_mr / reconcile_mr — all structural overhead with no algorithmic gain. A single dimension pair with two sections eliminates the duplication while keeping the two PLR types clearly separated within the JSONB detail.
  • Use the variant column for per-scenario rows — active_dims collapses rows by dimension name (processing.py), so variants would silently overwrite each other in the decider’s dict.
  • Track only k8s scenarios — conforma and testing-farm are also non-optional pre-merge gates; excluding them would leave the future approval gate blind to them.
  • Count-precise expectations (exactly N per-component runs) — brittle against snapshot internals the service does not own; only the per-app group slot is individually required, per-component presence stays ≥1.

Rationale: Build and test PLR tracking share the same algorithms (presence, staleness, terminality, 30-min fallback poll). Keeping them in one dimension pair with two sections eliminates duplication, reduces decider complexity, and avoids a split reset/rearm pattern across ensure_mr and reconcile_mr. Scenario keying matches the producer’s granularity. Presence-based terminality is robust to Konflux internals and keeps the dimension useful as the data source for the later mr-auto-approver gate (all expected PLRs present and green).

DDR-54: MR metadata is reviewer-owned with an explicit opt-in refresh

Decision: Store submitted title, description, and draft settings on the work item. Use them at MR creation. After creation, force-push and reconciliation leave those fields alone. Only update_mr_metadata: true schedules needs_mr_metadata to apply all three stored values in GitLab, even when the branch content is unchanged. Omitting draft leaves the stored value unchanged; a refresh still applies it to GitLab.

Context: Reapplying stored metadata during routine processing can undo reviewer edits, including a reviewer marking an MR as draft or ready.

Alternatives: Continuously reconcile GitLab to the stored values, or treat all submitted metadata as creation-only.

Rationale: One opt-in refresh reapplies the latest values from the work item without overwriting reviewer changes during routine processing.

DDR-55: The sweep recovers stranded armed-immediate dimensions

Decision: The periodic sweep selects active work items that have a dimension row with status='true' and no pending_until while the item is not actionable, and spawns their processing loops — the same recovery the expired-timer leg provides for deferred dimensions. An enqueue path that arms an immediate dimension without marking the item actionable now degrades to a one-backstop-interval delay (SWEEP_INTERVAL) instead of stranding the work.

Context: The actionable invariant — every enqueue path sets actionable = True in the same transaction as its durable write — was documented in two docstrings and enforced nowhere. !1548 added an enqueue path that violated it: needs_mr_metadata armed on a non-actionable item, masked by the in-process spawn, and invisible to all three sweep scans (the actionable scan requires actionable=True, the expired-timer scan requires a non-NULL pending_until, and no pending event existed). The specific case was fixed in !1548, but every future enqueue path re-faces the trap, and a second gap exists today: a sweep-spawned loop that crashes after an executor’s immediate re-arm leaves the same stranded state, because only API- and event-spawned loops carry actionable=True.

Alternatives: A wake primitive combining the durable arm, the actionable flag, and the spawn (spans crud and the processing manager; executor-side re-arms must not use it since the loop owns actionable during execution; still relies on each enqueue path choosing the helper); an audit test over the known enqueue paths (verifies only what exists at test time; covers no future path).

Rationale: The stranded state (status='true', pending_until=NULL, actionable=False) is transient in correct operation — a running loop processes it in milliseconds — so the new scan leg fires only for rows nothing else owns. It converts a documentation-only invariant into a query-level guarantee, is core-level and generic across accepted item types, closes the crash-after-immediate-re-arm gap, and preserves the fast path: enqueue paths still set actionable, and the sweep is the backstop, not the primary wakeup. Rows on the new leg have no deadline, so they ride the SWEEP_INTERVAL backstop exactly like the actionable scan. The premise holds universally: every dimension is always processable (the status note renders without the dashboard link when dashboard_base_url is unset, and CI retry with no matcher config is a legitimate no-op), so an armed-immediate row is always consumed rather than permanently re-woken.

DDR-56: GitLab MR fetches classify transient errors and fail the item when the MR is gone

Decision: Executors that fetch a managed merge request classify GitLab errors with a shared helper. Connection errors and 5xx are transient: the executor re-arms its dimension on the 5-minute error backoff and leaves the item active. A 404 or 410 means the MR no longer exists: the item fails with a “MR no longer exists” error. Any other 4xx — besides 429 rate limits and 408 timeouts, which are transient like 5xx because a later retry may succeed — also fails the item, with the GitLab error. retry_ci_jobs uses the same classification, so a transient GitLab outage no longer fails items through the CI-retry path. The classifier itself is core-level (workqueue_service/gitlab_errors.py), not MR-specific, so future work item types that talk to GitLab reuse it; only the fetch helper and the per-dimension re-arm policy live in the MR executor.

Context: Six MR-fetch sites handled GitlabError in four different ways. apply_mr_metadata, check_empty_diff, and reconcile_mr re-armed on a 5-minute backoff forever — including the 404 from a hard-deleted MR, which sends no webhook, so nothing ever terminated the cycle. _cancel_empty_update logged and continued (the item is cancelled on that path regardless). retry_ci_jobs via _resolve_pipeline returned failure on any GitLab error, failing the item even on transient 5xx. ensure_dashboard_note already classified transient (5xx/connection → backoff) vs everything else (item failed); this decision generalizes that precedent. Connection-level failures count as transient because python-gitlab raises raw requests exceptions for them (it does not wrap them in GitlabError after its internal retries), so the migrated handlers catch both exception hierarchies.

Alternatives: phase = "cancelled" on a gone MR (treats an unexplained deletion as intentional abandonment and hides it from failed-item views; cancelled is reserved for the superseded empty-diff case the service itself decided); marking only the dimension done (the other fetching dimensions keep hitting the same 404 on their next cycle); leaving retry_ci_jobs unchanged (a GitLab hiccup fails items through one path while every other executor backs off).

Rationale: Failing the item matches the in-repo precedent, makes the problem visible to operators, and stops the infinite retry; a resubmission retries the work if the deletion was a mistake. One shared, core-level classifier removes the four-way inconsistency, applies uniformly to future item types that talk to GitLab, and gives every fetch site — including the CI-retry path — the same transient backoff.

DDR-57: Dimension kinds are owned by the dimension, not the decider

Decision: Each work-item type declares its dimensions as a typed enum. Every member carries a kind — STANDING (an absent row means not yet done; the dimension is pending until discharged) or ON_DEMAND (an absent row means nothing requested; the dimension fires only after an explicit write) — and a pending(dims) method that encapsulates the check form. The decider calls pending(); raw != "false" / == "true" comparisons on dimension statuses do not appear in decider code. The kind enum and the dimension mixin live in the core service; each item type declares its dimensions next to its typed detail dataclasses. The arming sites are typed too: crud.upsert_dimension, crud.get_dimension, and events.DimensionUpdate accept the typed dimension (a core protocol implemented by the per-type enums) and reject bare strings at runtime, so a typo’d or unknown dimension is structurally impossible at every call site, not just the decider. The typing carries no arming policy — any dimension may be armed by any writer, exactly as before, and every dimension is always processable: the decider applies no config gates, because the status note renders without the dashboard link when dashboard_base_url is unset and CI retry with an empty matcher config is a legitimate no-op. Moving the typed-state machinery (DimensionState, ProcessAt, the detail protocol) to the core dimensions module also repairs the core→mr layering inversion: core crud and events no longer import anything from the mr package.

Context: The MR decider used two check forms over a plain dict[str, str]: != "false" (absent = actionable) for dimensions pending from item creation (needs_mr, needs_expected_plrs, needs_status_note, needs_empty_check, needs_reconcile, needs_ci_retry) and == "true" (absent = dormant) for dimensions that fire only after an explicit write (needs_plr, needs_mr_metadata). The distinction is load-bearing: every work item created before needs_mr_metadata existed has no row for it, so normalizing its check to the standing form would apply stored MR metadata to every legacy item and overwrite reviewer edits fleet-wide. The distinction was undocumented and easy to get wrong in practice: while documenting it in !1548, needs_ci_retry was misclassified as on-demand in the docs. More work item types are planned, and the core already imported MR-specific dimension machinery (crud.py and events.py imported mr/constants.py), so the fix must be item-type-generic and repair the layering.

Alternatives: A separate dimension-name → kind registry (a dimension can be added without registering it; a second list to keep in sync); a typed accessor on the active-dimensions map wrapper (semantics live on the dict; call sites still pair string names with accessors by convention); module-level helper functions plus an audit test (names stay stringly-typed; the test is the only guard); eager row creation so absent never occurs (a backfill migration plus per-type creation lists, complicated by config-dependent dimensions).

Rationale: Enum members make the kind mandatory at declaration — a dimension cannot exist without choosing standing or on-demand. The names state the absent-row semantics directly: “armed” was misleading (both kinds get armed — upsert arms needs_mr, a standing dimension — what distinguishes the second family is that arming is required), and “bootstrap” named the first-cycle occasion rather than the standing rule. The check form lives in exactly one method owned by the dimension, so the wrong comparison form is unwritable at call sites. __members__ provides a free registry for exhaustive tests (a truth table over every member × absent / true / false / deferred) and for docs consistency checks. Per-type enums over a core mixin generalize to new work-item types, and moving the machinery to core repairs the layering inversion.

DDR-58: Sentry stack-frame-local scrubbing via denylist mode

Decision: Initialize Sentry without send_default_pii and with data_collection={"stack_frame_variables": {"mode": "denylist"}}, filtering local variables with sensitive names out of captured stack frames.

Context: sentry-sdk 3.x removed send_default_pii and no longer scrubs stack-frame local variables by default. The service authenticates requests with bearer tokens (validated against trusted issuers via JWKS) and connects to PostgreSQL with credentials from the environment, so an uncaught exception would otherwise send token or connection values to Sentry. The CLI client obtains and caches Kerberos tokens while talking to the API and uses the same posture.

Alternatives: (a) Plain removal of send_default_pii=True — the 3.x defaults collect a comparable amount of data overall, but stack-frame locals go out unscrubbed. (b) The restrictive data_collection dict — turns off user info and HTTP bodies, discarding request context that an API service needs for debugging. (c) stack_frame_variables: False — disables local-variable capture entirely.

Rationale: The denylist keeps the request and error context the service needs for debugging while filtering variables whose names match the built-in sensitive-term list (token, password, …). This scrubs strictly more than the previous 2.x configuration with send_default_pii=True, which scrubbed nothing.