Skip to content

[Fix] Read extraction incidents inside the transaction - #132

Merged
Aloento merged 3 commits into
mainfrom
fix/issue-117-extract-fresh-read
Dec 1, 2026
Merged

Aloento merged 3 commits into
mainfrom
fix/issue-117-extract-fresh-read

Conversation

@Aloento

@Aloento Aloento commented Dec 1, 2026

Copy link
Copy Markdown
Member

ExtractComponentsToNewIncident ran in one WithTx, 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 by saveIncidentFull on the stale copy, and the stale version was written back.

The transaction now takes SELECT id FROM incident WHERE id = $1 FOR UPDATE on 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 with ErrDBComponentDSNotExist if 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/.... TestExtractComponentsUsesFreshIncidentState in tests/extract_tx_test.go applies a concurrent component/version change between the caller's read and the extraction and asserts it survives; the tests/ suite runs in CI against Postgres.

Closes #117

@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

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-acc and the check run both failed on commit ae50a67 (CodeQL, build, unit go-test, and golangci-lint pass). The PR description explicitly says "the tests/ suite runs in CI against Postgres", and the new TestExtractComponentsUsesFreshIncidentState is 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-acc output for this commit — most likely the new test (or TestExtractComponentsRollsBackOnSecondPhaseFailure under the new lock ordering) is failing, e.g. because AddComponentToIncident between 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 what ExtractComponentsToNewIncident returns. 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 uses component.IDIn(ids...) with no DeletedAt filter, even though Component carries a DeletedAt field (see componentFromEnt, 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 with ErrDBComponentDSNotExist, which is the stated intent of the re-read ("a component that disappeared aborts the extraction"). If DeletedAt != nil means deleted here, add component.DeletedAtIsNil() to the query (and check how SaveComponent treats 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 in internal/db/lock.go). If this out-of-scope race is acceptable, worth a comment on lockIncidentRows noting the deliberate source-only locking.

Suggestion — minor

  • internal/db/lock.go:51: the signature takes ids ...uint and casts to int for 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.
@Aloento
Aloento force-pushed the fix/issue-117-extract-fresh-read branch from ae50a67 to a4432d3 Compare December 1, 2026 10:46
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.
ecosquad-autoreview[bot]
ecosquad-autoreview Bot previously approved these changes 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

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

  1. Caller's incident pointer is mutated in place — internal/db/db.go:938
    *incOld = *freshOld overwrites the contents of the *Incident the 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 the Components/Statuses slices 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 := *freshOld and build/write from that), or, if mutating the caller's copy is intentional for all callers, say so explicitly in the function comment.

Suggestion

  1. ID == 0 pass-through in currentComponentsTx keeps stale caller data — internal/db/db.go:866-895
    Entries with ID == 0 are 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 rejecting ID == 0 entries with an explicit error instead of silently passing them through.

  2. Verify status ordering in GetIncident is unchanged — internal/db/db.go:285-296
    The refactor replaced statusesByIncident + attachStatuses with a direct IncidentStatus query ordered by incidentstatus.ByID(entsql.OrderAsc()). If the old helper ordered differently (e.g. by timestamp), Incident.Statuses ordering changes for every API consumer of GetIncident. Please confirm the previous ordering was id-ascending, or restore it.

  3. 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), currentComponentsTx still 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 UPDATE on the stored row makes the test actually exercise the re-read path.
  • Deadlock-safe lock ordering in lockIncidentRows, and the re-reads reuse the existing clientFor(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.

@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.

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

  1. GetIncident no longer uses statusesByIncident — internal/db/db.go (getIncidentTx, ~lines 265–300). The old code attached statuses via db.statusesByIncident(ctx, []int{e.ID}) + attachStatuses; the new code queries IncidentStatus directly and orders by id ASC. This changes the status behavior of every GetIncident caller, not just the extraction path. If statusesByIncident ever 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 confirm statusesByIncident is 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

  1. currentComponentsTx silently passes through components with ID == 0 (internal/db/db.go, ~lines 866–903). A zero-ID (unsaved) component is kept in the returned slice, but reconcileIncidentComponents (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 to ExtractComponentsToNewIncident, this is a silent data drop; consider failing with a specific error or documenting that only existing components are supported.

  2. lockIncidentRows deadlocks 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.

  3. Minor: getIncidentTx builds inc.Statuses as a fresh slice (never nil), whereas the old attachStatuses path 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.

@Aloento Aloento closed this Dec 1, 2026
@Aloento Aloento reopened this Dec 1, 2026
…-fresh-read

# Conflicts:
#	internal/db/db.go
#	internal/db/lock.go

@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.

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 GetIncident path (internal/db/db.go:286-295). The refactor replaced db.statusesByIncident(...) + attachStatuses(...) with an explicit incidentstatus.ByID(entsql.OrderAsc()) query. If statusesByIncident/attachStatuses previously ordered by timestamp (or any order other than primary-key ascending), the ordering of Incident.Statuses returned by GetIncident — 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

  • lockIncidentRows multi-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 the slices.Sort path 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 in lockIncidentRows (internal/db/lock.go:64) truncates uint to int. Fine for realistic incident IDs, but a math.MaxInt-style guard (similar to the pagination offset guard already in db.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.

@Aloento
Aloento merged commit e435857 into main Dec 1, 2026
14 checks passed
@Aloento
Aloento deleted the fix/issue-117-extract-fresh-read branch December 1, 2026 11:14
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] Read incidents for extraction inside the transaction

1 participant