Repository navigation
[Fix] Read extraction incidents inside the transaction - #132
Conversation
There was a problem hiding this comment.
Summary
The fix addresses the stale-read race in ExtractComponentsToNewIncident (#117) correctly in shape: lock the source incident row (SELECT id FROM incident ... FOR UPDATE in internal/db/lock.go:51-66), re-read it with components and statuses inside the transaction (getIncidentTx, internal/db/db.go:267-296), and re-read the components to extract via currentComponentsTx (internal/db/db.go:863-898) in caller order, failing with ErrDBComponentDSNotExist if one is gone. The new status read also correctly goes through the transaction client (c := db.clientFor(tx)), which the old statusesByIncident path did not do for the single-incident read. A regression test is added in tests/extract_tx_test.go.
Findings
Critical — acceptance CI is red on the head commit
go-test-accand thecheckrun both failed on commitae50a67(CodeQL, build, unitgo-test, and golangci-lint pass). The PR description explicitly says "thetests/suite runs in CI against Postgres", and the newTestExtractComponentsUsesFreshIncidentStateis the verification for exactly this fix. A failing acceptance suite means the fix is not verified against a real database.- Fix: check the
go-test-accoutput for this commit — most likely the new test (orTestExtractComponentsRollsBackOnSecondPhaseFailureunder the new lock ordering) is failing, e.g. becauseAddComponentToIncidentbetween the caller read and the extract now blocks on the incident row lock and the test's timeout/expectation doesn't account for it, or because the re-read path changed whatExtractComponentsToNewIncidentreturns. Fix the failure and re-run; do not merge with a red acceptance suite. (I cannot execute the suite from here, so I'm flagging rather than diagnosing.)
Warning — currentComponentsTx does not filter soft-deleted components
internal/db/db.go:877-882— the re-read usescomponent.IDIn(ids...)with noDeletedAtfilter, even thoughComponentcarries aDeletedAtfield (seecomponentFromEnt,internal/db/mappers.go:105-126). A component that was deleted in the same window will be reported as present with its (deleted) attributes rather than aborting withErrDBComponentDSNotExist, which is the stated intent of the re-read ("a component that disappeared aborts the extraction"). IfDeletedAt != nilmeans deleted here, addcomponent.DeletedAtIsNil()to the query (and check howSaveComponenttreats it to confirm semantics).
Suggestion — component rows are not locked, only the source incident
lockIncidentRows(ctx, db.rawFor(tx), incOld.ID)locks only the source incident. Two concurrent extractions from different source incidents that share a component are not serialized (different lock rows), so the same component could still be extracted into two new incidents. If the invariant "a component belongs to at most one incident" matters, lock the component rows too (there is already an advisory-lock helper for names ininternal/db/lock.go). If this out-of-scope race is acceptable, worth a comment onlockIncidentRowsnoting the deliberate source-only locking.
Suggestion — minor
internal/db/lock.go:51: the signature takesids ...uintand casts tointfor the SQL arg; the only caller passes a single ID. Fine, but the variadic + ascending-order machinery suggests multi-ID use — if it's only ever one ID, a single-argument signature is simpler.
Note on review scope
The db.go patch was truncated in the diff view, so the re-read/saveIncidentFull body between the lock and client := db.clientFor(tx) (db.go:969) was not directly inspected; the findings above are based on the visible hunks, tx.go, mappers.go, lock.go, and the new test. The red go-test-acc is the primary blocker regardless.
Verdict: request_changes — at minimum the failing acceptance suite must be investigated and green before merging.
ExtractComponentsToNewIncident rebuilt the source incident from the caller's pre-transaction copy, so a component or status written in between could be dropped when the stale struct was saved back. The source incident is now locked with SELECT ... FOR UPDATE and re-read through the transaction, and the component list is refreshed the same way. The destination incident does not exist until the transaction creates it, so there is no second incident to lock.
ae50a67 to
a4432d3
Compare
currentComponentsTx queried components by id without a deleted_at filter, so a component soft-deleted between the caller's read and the extraction was reported as present with its stale attributes. The re-read now requires DeletedAtIsNil, so the extraction aborts with ErrDBComponentDSNotExist. Also documents that lockIncidentRows only locks the source incident row.
There was a problem hiding this comment.
Summary
Fixes the race in ExtractComponentsToNewIncident (closes #117): the source incident and the components to extract were read by the caller before the WithTx started, so concurrent writes in that window were reconciled away by the stale-copy write. The transaction now locks the source incident row (SELECT ... FOR UPDATE), re-reads the incident with its components and statuses (getIncidentTx), re-reads the components to extract (currentComponentsTx, caller order preserved, ErrDBComponentDSNotExist if one disappeared), and builds the new incident from the fresh state. GetIncident was refactored into a tx-aware getIncidentTx, and tests/extract_tx_test.go gains a fresh-read regression test plus an improvement to the rollback test (mutates the stored row instead of the caller's copy, which also proves the re-read happens).
The core locking + re-read logic is correct: the FOR UPDATE is taken inside the transaction before the re-read, lockIncidentRows locks in ascending id order so concurrent transactions touching the same rows cannot deadlock, and CI is green (build, go-test, go-test-acc, lint, CodeQL).
Findings
Warning
- Caller's incident pointer is mutated in place —
internal/db/db.go:938
*incOld = *freshOldoverwrites the contents of the*Incidentthe caller passed in. Any caller holding the pointer (e.g. to build an API response or to use the incident after the call returns) silently sees a different state than it passed in — status, timestamps, version, and theComponents/Statusesslices are all replaced. This is invisible in the function's doc.
Fix: don't write through the caller's pointer — use a local copy for the extraction (fresh := *freshOldand build/write from that), or, if mutating the caller's copy is intentional for all callers, say so explicitly in the function comment.
Suggestion
-
ID == 0pass-through incurrentComponentsTxkeeps stale caller data —internal/db/db.go:866-895
Entries withID == 0are returned untouched and end up associated with the new incident with no stored attributes. This matches the pre-change behavior, but since the function's whole purpose is to stop trusting caller-provided component state, consider rejectingID == 0entries with an explicit error instead of silently passing them through. -
Verify status ordering in
GetIncidentis unchanged —internal/db/db.go:285-296
The refactor replacedstatusesByIncident+attachStatuseswith a directIncidentStatusquery ordered byincidentstatus.ByID(entsql.OrderAsc()). If the old helper ordered differently (e.g. by timestamp),Incident.Statusesordering changes for every API consumer ofGetIncident. Please confirm the previous ordering was id-ascending, or restore it. -
Component existence check doesn't verify the association with the source incident —
internal/db/db.go:866-895
If a concurrent operation removes the component relation from the old incident (while the component row itself still exists),currentComponentsTxstill succeeds and the extraction re-associates the component with only the new incident. That is arguably the desired outcome (no data loss), but it's a semantic edge worth a comment or an explicit assertion.
Positives
- Fresh-read test (
TestExtractComponentsUsesFreshIncidentState) correctly simulates a concurrent writer between the caller's read and the extraction, and asserts the concurrent component/version survives. - Rolling back the old rollback-test trick (mutating the caller's copy) to a
UPDATEon the stored row makes the test actually exercise the re-read path. - Deadlock-safe lock ordering in
lockIncidentRows, and the re-reads reuse the existingclientFor(tx)plumbing consistently.
Verdict
approve — the fix is correct and well-tested; the warning (caller-pointer mutation) should be addressed either in this PR or a follow-up by using a local copy or documenting the mutation.
There was a problem hiding this comment.
Review: [Fix] Read extraction incidents inside the transaction
The change is directionally right: ExtractComponentsToNewIncident now locks the source incident row (SELECT ... FOR UPDATE via lockIncidentRows), re-reads the incident inside the transaction (getIncidentTx), and re-reads the components to extract (currentComponentsTx), so a component/status written between the caller's read and the transaction is no longer reconciled away by saveIncidentFull on a stale copy. CI (build, vet, unit tests, Postgres integration tests) is green.
Caveat: the file internal/db/db.go could not be read past ~line 330 in this environment (repeated truncation), so the body of ExtractComponentsToNewIncident was reviewed only through the patch. The findings below cover what is verifiable; please treat the open question below as the main thing to double-check.
Warning
GetIncidentno longer usesstatusesByIncident—internal/db/db.go(getIncidentTx, ~lines 265–300). The old code attached statuses viadb.statusesByIncident(ctx, []int{e.ID})+attachStatuses; the new code queriesIncidentStatusdirectly and orders byid ASC. This changes the status behavior of everyGetIncidentcaller, not just the extraction path. IfstatusesByIncidentever filtered, deduplicated, or ordered statuses differently than id-ascending (e.g., by timestamp), public API responses would change as a side effect of this fix. Please verify the two are equivalent — either confirmstatusesByIncidentis a plain id-ordered fetch (in which case fine), or route the tx path through the same helper by giving it a client/tx parameter, so the non-extraction read path stays untouched.
Suggestions
-
currentComponentsTxsilently passes through components withID == 0(internal/db/db.go, ~lines 866–903). A zero-ID (unsaved) component is kept in the returned slice, butreconcileIncidentComponents(internal/db/write.go) skips zero-ID components, so the extracted incident is created without it and no error is returned. If callers can pass unsaved components toExtractComponentsToNewIncident, this is a silent data drop; consider failing with a specific error or documenting that only existing components are supported. -
lockIncidentRowsdeadlocks are avoided by ascending-id ordering, but only one id is ever passed (internal/db/lock.go:56). The varargs + sort is correct as written; just be aware the ordering guarantee only matters if a future caller locks multiple incidents in one call — worth keeping, and the "shared component stays unserialized" scope note in the comment is good. -
Minor:
getIncidentTxbuildsinc.Statusesas a fresh slice (nevernil), whereas the oldattachStatusespath may have left it nil/empty — harmless, but worth confirming no caller distinguishes nil from empty.
Verdict
Approve, with the request to confirm finding 1 (status-fetch equivalence in GetIncident) before merging — if statusesByIncident had different filtering/ordering, that part of the change should be scoped back to the extraction path only.
…-fresh-read # Conflicts: # internal/db/db.go # internal/db/lock.go
There was a problem hiding this comment.
Review: Read extraction incidents inside the transaction (fix #117)
The fix is well-motivated and largely correct: ExtractComponentsToNewIncident now locks the source incident row (SELECT … FOR UPDATE via lockIncidentRows, internal/db/db.go:931), re-reads the incident with its components/statuses inside the transaction, and re-reads the components to extract (currentComponentsTx, internal/db/db.go:866) before reconciling. This closes the read-then-write race that let a concurrent component/version/status change be written back on a stale copy. CI is green including go-test-acc (Postgres), CodeQL, build and lint, and the new TestExtractComponentsUsesFreshIncidentState directly exercises the concurrent-write scenario.
No blocking correctness bugs found. A few things worth a look:
Warning
- Status ordering changed on the public
GetIncidentpath (internal/db/db.go:286-295). The refactor replaceddb.statusesByIncident(...)+attachStatuses(...)with an explicitincidentstatus.ByID(entsql.OrderAsc())query. IfstatusesByIncident/attachStatusespreviously ordered by timestamp (or any order other than primary-key ascending), the ordering ofIncident.Statusesreturned byGetIncident— and thus to API consumers — has silently changed. IDs are insertion-ordered, so this is usually equivalent to chronological order, but please confirm the two orderings match; if they differ, either preserve the original ordering or intentionally adopt the new one.
Suggestion
lockIncidentRowsmulti-id ordering is currently unexercised (internal/db/lock.go:56). The doc comment describes ascending-id ordering to prevent deadlocks when "transactions touch the same pair," but the only caller passes a single id (incOld.ID), so theslices.Sortpath is effectively dead for now. It's harmless and forward-looking, but the comment overstates the current guarantee; consider trimming it or adding a second call site if the pair case is actually planned.int(id)cast inlockIncidentRows(internal/db/lock.go:64) truncatesuinttoint. Fine for realistic incident IDs, but amath.MaxInt-style guard (similar to the pagination offset guard already indb.go) would keep it consistent with the defensive style elsewhere in the file.
Minor: currentComponentsTx treats a soft-deleted component (component.DeletedAtIsNil(), db.go:878) as "not exist" and aborts with ErrDBComponentDSNotExist, which is the right conservative behavior — just confirm that's the intended user-facing error for a concurrently-deleted component.
Overall: correct, well-tested fix for the reported race. Approve, with the status-ordering change being the one point I'd want confirmed before this ships.
ExtractComponentsToNewIncidentran in oneWithTx, but the source incident and the components were read by the caller before it started. A component or status written in that window was reconciled away bysaveIncidentFullon the stale copy, and the stale version was written back.The transaction now takes
SELECT id FROM incident WHERE id = $1 FOR UPDATEon the source incident and re-reads it with its components and statuses; the components to extract are re-read as well, preserving the caller's order and failing withErrDBComponentDSNotExistif one disappeared. The destination incident does not exist until the transaction inserts it, so only the source row needs locking.Verification:
go build ./...,go vet ./...,go test ./internal/....TestExtractComponentsUsesFreshIncidentStateintests/extract_tx_test.goapplies a concurrent component/version change between the caller's read and the extraction and asserts it survives; thetests/suite runs in CI against Postgres.Closes #117