Events and Processing Semantics
The event pipeline from SNS to work-item threads, phase semantics, and the per-item processing loop. Part of the design decision registry.
DDR-29: Events processed in work-item threads, not consumer threads
Decision: The SQS consumer thread stores events in the
pending_events table. Existing per-work-item threads drain and
process them.
Context: The ProcessingManager already runs one thread per work item with per-item ownership (DDR-51). Processing events in the same thread means events and actions are naturally serialized per work item.
Alternatives: (a) Consumer threads handle events directly — concurrency conflicts with action threads. (b) FIFO queue + in-memory dispatch — receipt handle management, visibility timeout extensions, message loss on crash.
Rationale: Option (c). Events join the existing thread structure. The decider runs after each event, determining follow-up actions. The single-thread-per-item invariant is preserved.
DDR-30: pending_events table as durable event store
Decision: Use a PostgreSQL table (pending_events) instead of
FIFO queues or in-memory queues for event delivery to work-item threads.
Context: Since work-item threads do the processing, the SQS consumer just needs to deliver events to them durably.
Alternatives: (a) FIFO queue + in-memory dispatch — complex EventBroker, receipt handle management, message loss on crash. (b) FIFO queue + direct handling — concurrency conflicts.
Rationale: The DB provides durability (crash recovery), serialization
(single thread per work item), and ordering (last_event_at guard). No
FIFO queue, router thread, MessageGroupId computation, in-memory queues,
or visibility timeout management needed.
DDR-31: SQS delete after INSERT, not after full processing
Decision: Delete the SQS message after INSERT+COMMIT into
pending_events, not after full event processing.
Context: The hummingbird-agent deletes after handling (no DB intermediary). The workqueue-service can delete after INSERT+COMMIT because the event is crash-recoverable in PostgreSQL.
Alternatives: Delete after full processing — requires visibility timeout extensions, receipt handle passing, heartbeat management.
Rationale: After INSERT+COMMIT the event is durable in PostgreSQL.
Duplicate SQS delivery may INSERT the same event twice; the
last_event_at guard makes processing idempotent.
DDR-32: Resolver filters by phase, consumer stays read-only
Decision: The resolver filters by phase = 'active' on the
MRWorkItem query. SQLAlchemy’s joined table inheritance handles the
work_items table access implicitly. The consumer does SELECT +
INSERT only, no UPDATE, no row lock contention.
Context: Only active items accept event-driven transitions (see
DDR-37). Filtering at resolve time avoids unnecessary INSERTs into
pending_events, thread spawns, and no-op processing for terminal
items.
Alternatives: (a) Resolve without phase filter, guard only at processing time — wastes work for terminal items. (b) Consumer checks phase and applies transitions directly — contention with work-item threads.
Rationale: The phase filter adds negligible cost (PK lookup on
work_items, typically one row). The consumer remains read-only.
Business logic (phase transitions, decider, audit) is applied by the
generic handle_event layer in the work-item thread.
DDR-33: Raw events stored, interpretation separated from application
Decision: The pending_events table stores the raw event JSON
body and event type. Type-specific handlers interpret events (read-only
on the work item), the generic layer applies the result.
Context: Event processing has three concerns: interpretation (what does this event mean?), application (phase transition, decider, audit), and routing (which work items?). Mixing them makes handlers hard to test and inconsistent across types.
Alternatives: (a) Handlers apply all changes directly — mixes interpretation with mutation, each handler reimplements decider/audit boilerplate. (b) Pre-process events in the consumer — consumer needs type-specific knowledge.
Rationale: Handlers return an EventResult dataclass (phase,
event_ts, trigger metadata). The generic handle_event applies the
phase transition via update_work_item_from_event, runs the decider,
and emits audit entries. Handlers have read-only access to the work
item and session (e.g. to check existing dimensions or detail fields)
but EventResult is their only output — they never mutate the work
item directly. This ensures decider/audit logic is consistent across
all item types. See DDR-38 for the dimension delivery extension.
DDR-34: Per-work-item advisory lock for insert/drain coordination
Superseded by DDR-51. The insert/exit handshake was replaced by a
SELECT ... FOR UPDATErow lock onwork_itemsaround the exit decision, which serializes every enqueue writer. See DDR-51 for the design and its motivation.
DDR-35: Sweep for startup recovery
Decision: Extend the periodic sweep to also check for work items
with unprocessed pending_events rows.
Context: Events that arrive while the service is stopped, or that survive a mid-processing crash, must be processed on restart.
Alternatives: Separate startup-only scan.
Rationale: Unifying startup recovery with the periodic sweep keeps
a single code path. The sweep runs immediately on manager.start(),
catching events from downtime. It also serves as a safety net behind
the advisory lock.
DDR-36: Consumer lifecycle and shutdown ordering
Decision: The SQS consumer is a single daemon thread started from the FastAPI lifespan. Shutdown stops the consumer before work-item threads.
Context: If work-item threads stop while the consumer is still INSERTing, events could be orphaned. The consumer must stop first.
Alternatives: Non-daemon thread with explicit join.
Rationale: Single thread is sufficient for low event volume (MR
state changes). Daemon thread ensures process exit even if the thread
hangs. Shutdown ordering: (1) set shutdown_event, (2) join consumer
thread (timeout=30s), (3) call manager.stop(). No consumer when
WORKQUEUE_SERVICE_EVENTS_QUEUE_URL is unset.
DDR-37: Terminal phase semantics — only active items accept events
Decision: Only items in phase = 'active' accept event-driven
phase transitions. completed, failed, and cancelled are terminal
phases — recovery requires explicit action via the retry API.
Context: Initially only failed was guarded (phase != 'failed').
completed and cancelled items could be modified by events: a
closed event could transition a completed item to cancelled, and an
opened event could reactivate a cancelled item.
Alternatives: (a) Guard only failed — inconsistent, completed
items are accidentally mutable. (b) Growing exclusion list
(NOT IN ('failed', 'completed')) — fragile if new phases are added.
(c) Positive match phase = 'active'.
Rationale: Option (c). A single positive match is clearer and
future-proof. If a work item was cancelled (MR closed) or completed
(MR merged), only deliberate human action (retry API) should
reactivate it — not an automated event. The retry API accepts both
failed and cancelled items. The resolver also filters by
phase = 'active' at query time (DDR-32) to avoid unnecessary
INSERT/processing for terminal items.
DDR-38: Dimension updates via EventResult
Decision: Event handlers return dimension upserts as part of
EventResult. The generic handle_event layer applies them.
Context: DDR-33 established that handlers return structured results and the generic layer applies them. Dimensions (DDR-1, DDR-3) need the same pattern — handlers identify which dimensions changed, the generic layer upserts them and emits audit entries.
Alternatives: (a) Handlers call crud.upsert_dimension() directly —
breaks the read-only handler contract from DDR-33. (b) Separate
dimension-specific consumer — duplicates the resolver/handler
infrastructure.
Rationale: EventResult.dimensions is a list of DimensionUpdate
dataclasses. After phase transition logic, handle_event iterates over
dimensions and calls crud.upsert_dimension() for each, emitting an
AuditEntry with event_type="dimension_change" using the existing
dimensions field. Dimension upserts run even when the phase transition
is stale (the early return is refactored to skip only the phase/decider
block). This ensures dimension-only events (e.g. note events with no
phase change) are still applied.
DDR-39: Server-derived idempotency keys with phase-aware uniqueness
Decision: Replace the client-supplied idempotency_key field with a
server-derived key mr:{project}:{source_branch}:{generation}. Enforce
uniqueness only among non-terminal phases via a partial unique index.
Context: The original API required callers to supply a unique
idempotency_key per submission. Recurring callers (dist-git sync,
upstream sync) had to invent unique keys for each invocation and track
them across runs. The global unique constraint also blocked new
submissions for a branch that had a previous completed or cancelled item
with the same key.
Alternatives: (a) Client-supplied key with a prefix convention —
callers still need to generate and track keys. (b) Server-derived key
from the natural deduplication identity (project, source_branch) with
a generation counter for lifecycle restarts.
Rationale: Option (b). The idempotency key is a DB-level safety net,
not a caller concern. The natural identity is (project, source_branch);
the generation counter increments when a new item is created after the
previous one reached a terminal phase. The partial unique index
(WHERE phase NOT IN ('completed', 'cancelled')) ensures at most one
active/failed item per idempotency key while allowing completed items to
coexist with their successors.
DDR-40: Upsert semantics for recurring MR management
Decision: Replace one-shot insert_mr_work_item with
upsert_mr_work_item that looks up an existing active/failed item by
(project, source_branch) and determines the correct action from a
content hash comparison.
Context: Recurring callers submit MRs for the same branch repeatedly. Under the old insert model, each submission created a new work item — even when the previous one was still active, leading to orphaned branches and duplicate MRs.
Alternatives: (a) Client manages deduplication — check before submit, handle conflicts. (b) Server-side upsert — callers always submit current desired state, the service deduplicates transparently.
Rationale: Option (b). The upsert does a
(project, source_branch) lookup among non-terminal items and branches
on the result:
- No match → create a new item (
actionable = true) - Active, same content → store submitted MR metadata and return existing,
"unchanged"; no branch update. An explicit metadata refresh can still run (DDR-54). - Active, different content → update fields, set
actionable = true, resetneeds_mr = "true" - Failed → reset to active, update content, clear error (
"retried"), setactionable = true - Terminal (completed/cancelled) → create a new generation (DDR-39)
Concurrent insert races are handled via DDR-39’s partial unique index —
the loser catches the IntegrityError, rolls back, and retries.
DDR-41: ThreadPoolExecutor with bounded workers
Decision: Replace unbounded per-item threading.Thread spawning
with a fixed-size ThreadPoolExecutor (10 workers).
Context: The periodic tick mechanism (DDR-42) can wake many idle items simultaneously. Unbounded thread creation would cause resource spikes (~109 threads in the worst case).
Alternatives: (a) Keep per-item threads with a semaphore. (b) Bounded thread pool.
Rationale: Option (b). ThreadPoolExecutor provides built-in
queuing when all workers are busy, deduplication via _submitted set,
and clean shutdown via pool.shutdown(wait=True). The 10-worker limit
caps concurrent GitLab API calls.
DDR-42: Hash-bucketed tick events for periodic re-evaluation
Superseded by DDR-48. The synthetic
tick_30mandtick_5mevents were replaced by thepending_untilcolumn onwork_item_statuses. See DDR-48 for the design and its motivation.
DDR-43: Empty diff detection via repository_compare
Decision: Detect and handle empty MR diffs at two call sites:
ensure_mr (prevention on create and force-push) and check_empty_diff
(periodic via sweep).
Context: The detection-execution race causes empty MRs when the target branch moves between change detection and MR creation. Also, existing MRs can become empty after creation.
Alternatives: (a) Compare file content hashes before commit. (b)
GitLab repository_compare API after commit/push.
Rationale: Option (b). The repository_compare endpoint returns
the diff between two branches. Empty diffs list means the branches
are identical. This is authoritative and handles edge cases that hash
comparison might miss (e.g. whitespace normalization). Cost: one API
call per check (~4 calls/minute across all items for periodic checks).
DDR-44: Per-item processing deadline
Decision: Exit the work item loop after 60 seconds of wall-clock time.
Context: The tick mechanism (DDR-42) and check_stale_mr action
could cause extended processing loops for items that repeatedly generate
new actions. A deadline prevents any single item from holding a pool
worker indefinitely.
Alternatives: (a) Limit loop iterations. (b) Wall-clock deadline.
Rationale: Option (b). Wall-clock time is predictable regardless of action duration. The deadline is between loop iterations, not mid-executor, so executors have their own HTTP timeouts. The item is re-picked by the next sweep if work remains.