Repository navigation
[Fix] Serialize system incident creation per impact - #128
Conversation
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.
There was a problem hiding this comment.
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—WithSystemIncidentLockopens one transaction, takes the xact lock ondb.rawFor(tx), and runs the critical section. Becausetx.go:43-49binds the raw executor and the Ent client to the same*sql.Txconnection, 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 (
GetEventsInternalTxviaclientFor(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.gorefactors to thread the Ent client throughgetEventsWithCount/statusesByIncidentare 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
-
Unbounded wait on the advisory lock —
internal/db/lock.go:60:pg_advisory_xact_lockblocks 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.gogetEventsWithCount) 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 existinglockComponentNamehas the same property, but that critical section is much smaller.
Fix: cap the wait, e.g. runSET LOCAL lock_timeout = '5s'(or a shortstatement_timeout) ontx.driverright beforelockSystemIncident, and surface the timeout as a retriable 503. -
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:53starts transactions withBeginTx(ctx, nil), i.e. the pool default — fine today on Postgres, but if the isolation level is ever changed inNew()orbegin, 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}inbegin(or at least inWithSystemIncidentLock) and extend the comment onGetEventsInternalTx(db.go) to name the isolation requirement.
Suggestion
-
Unverified
createEventTxsplit — the PR description sayscreateEventwas split intocreateEventTx, and the system-incident path callscreateEventTx(ctx, dbInst, log, tx, &incIn, nil, nil)(internal/api/v2/v2.goaround line 668). The tool output truncated the body ofcreateEventTx, so I could not confirm that passinguserID=nil/pub=nilis handled (e.g. no nil-pointer in status-creation or notification code, and that system events are intentionally not published).go buildpasses and CI tests are running, but please double-check the nil-publisher path increateEventTxbefore merging. -
Broken CodeQL config (repo, not this PR) — the CodeQL run is neutral because the
Default setupforlanguage:goonmainwas 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.
addComponentToSystemIncidentlooked 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>")), mirroringlockComponentName. A competing caller waits, re-queries inside its own transaction, and links its component to the committed incident.createEventis split intocreateEventTxandAddComponentToIncidentgains aTxvariant so the whole sequence shares the transaction.Verification:
go build ./...,go vet ./...,go test ./internal/.... No DB-free test can prove advisory-lock serialization, sotests/system_incident_lock_test.gofires four concurrent system incident requests with the same impact and asserts a single incident holds all components; thetests/suite runs in CI against Postgres.Closes #116