Skip to content

[Fix] Serialize system incident creation per impact - #128

Merged
Aloento merged 2 commits into
mainfrom
fix/issue-116-system-incident-lock
Dec 1, 2026
Merged

Aloento merged 2 commits into
mainfrom
fix/issue-116-system-incident-lock

Conversation

@Aloento

@Aloento Aloento commented Dec 1, 2026

Copy link
Copy Markdown
Member

addComponentToSystemIncident looked up active system incidents on the pool and then created one when no impact matched, without serialization. Two concurrent requests for the same impact could both observe no incident and insert duplicates.

The lookup and the insert now run in a single transaction that first takes pg_advisory_xact_lock(hashtext("system-incident|<impact>")), mirroring lockComponentName. A competing caller waits, re-queries inside its own transaction, and links its component to the committed incident. createEvent is split into createEventTx and AddComponentToIncident gains a Tx variant so the whole sequence shares the transaction.

Verification: go build ./..., go vet ./..., go test ./internal/.... No DB-free test can prove advisory-lock serialization, so tests/system_incident_lock_test.go fires four concurrent system incident requests with the same impact and asserts a single incident holds all components; the tests/ suite runs in CI against Postgres.

Closes #116

The system incident lookup and creation ran on the pool without a lock, so
concurrent requests with the same impact could each find no match and create
a duplicate. Both now run in one transaction that first takes
pg_advisory_xact_lock(hashtext("system-incident|<impact>")): a competing
caller waits, re-queries through its own transaction, and attaches its
component to the committed incident.

createEvent is split into createEventTx, and AddComponentToIncident gains a
Tx variant, so the system path keeps the lookup and the write in one
transaction.
@Aloento Aloento self-assigned this Dec 1, 2026

@ecosquad-autoreview ecosquad-autoreview Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

This PR fixes the lost-update race in addComponentToSystemIncident (#116) by serializing the lookup-and-create under a per-impact pg_advisory_xact_lock inside a single transaction, mirroring the existing lockComponentName pattern. The structure is sound:

  • internal/db/lock.go:52-71 — WithSystemIncidentLock opens one transaction, takes the xact lock on db.rawFor(tx), and runs the critical section. Because tx.go:43-49 binds the raw executor and the Ent client to the same *sql.Tx connection, the lock, the re-query, and the insert/commit are genuinely atomic, and the xact lock releases on commit/rollback.
  • The re-query after lock acquisition (GetEventsInternalTx via clientFor(tx)) is correct under Postgres' default READ COMMITTED isolation, so a waiter observes the previous holder's committed incident instead of inserting a duplicate.
  • db.go refactors to thread the Ent client through getEventsWithCount/statusesByIncident are mechanical and consistent with the existing non-Tx paths.

Build passes; go-test and go-test-acc are still running, so the new 4-concurrent-request test in tests/system_incident_lock_test.go is not yet confirmed (note: it is the only real proof of the fix, since nothing in the unit tests can exercise the lock).

Findings

Warning

  1. Unbounded wait on the advisory lock — internal/db/lock.go:60: pg_advisory_xact_lock blocks with no timeout. The lock is held for the whole critical section — a full event lookup with count, component subqueries, and status history load (db.go getEventsWithCount) plus the incident insert — on a pooled connection (pool max 25, db.go:34). If one holder's commit stalls (e.g. a write-lock wait elsewhere, a wedged backpressure), every concurrent request for the same impact queues indefinitely and consumes a pool connection each. The existing lockComponentName has the same property, but that critical section is much smaller.
    Fix: cap the wait, e.g. run SET LOCAL lock_timeout = '5s' (or a short statement_timeout) on tx.driver right before lockSystemIncident, and surface the timeout as a retriable 503.

  2. Correctness silently depends on READ COMMITTED — the whole scheme requires that the re-query inside the lock sees rows committed by the previous holder, which only holds under READ COMMITTED (or SERIALIZABLE). internal/db/tx.go:53 starts transactions with BeginTx(ctx, nil), i.e. the pool default — fine today on Postgres, but if the isolation level is ever changed in New() or begin, this breaks without any compile-time or test signal (the CI test would, but only in the Postgres suite).
    Fix: pin it explicitly — pass &sql.TxOptions{Isolation: sql.LevelReadCommitted} in begin (or at least in WithSystemIncidentLock) and extend the comment on GetEventsInternalTx (db.go) to name the isolation requirement.

Suggestion

  1. Unverified createEventTx split — the PR description says createEvent was split into createEventTx, and the system-incident path calls createEventTx(ctx, dbInst, log, tx, &incIn, nil, nil) (internal/api/v2/v2.go around line 668). The tool output truncated the body of createEventTx, so I could not confirm that passing userID=nil/pub=nil is handled (e.g. no nil-pointer in status-creation or notification code, and that system events are intentionally not published). go build passes and CI tests are running, but please double-check the nil-publisher path in createEventTx before merging.

  2. Broken CodeQL config (repo, not this PR) — the CodeQL run is neutral because the Default setup for language:go on main was deleted; the Go analysis (Analyze (go)) is still in progress. Worth restoring the config so security scans actually cover this code.

Verdict

Approve — the fix is correctly structured and no critical issues were found in the reviewed code. Items 1 and 2 are worth addressing (either here or a quick follow-up) since they are about robustness of the locking path the PR introduces; item 3 should be confirmed before merge.

@Aloento
Aloento merged commit b4365f9 into main Dec 1, 2026
13 checks passed
@Aloento
Aloento deleted the fix/issue-116-system-incident-lock branch December 1, 2026 10:57
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.

[db] Serialize system incident creation

1 participant