Repository navigation
[Fix] Version-check the impact bump on system incidents - #135
Conversation
IncreaseIncidentImpact rewrote the incident with no version predicate and without bumping the version, so a stale copy could overwrite a concurrent change and later optimistic updates kept matching the old version. The update now matches the loaded version, sets version+1 in the same statement, and returns ErrVersionConflict when it affects no row; the appended status row stays in the same transaction and is not written on conflict. The incident creation handler maps the conflict to 409.
8df55db to
3dd809a
Compare
There was a problem hiding this comment.
Summary
Good fix for #119. IncreaseIncidentImpact now guards the update with Where(incident.IDEQ(id), incident.VersionEQ(expectedVersion)), bumps version in the same statement (SetVersion(newVersion)), uses update.Save()'s affected-row count to detect conflicts, rolls back the transaction (so the status row is never written on conflict), and returns db.ErrVersionConflict. The new Version == nil guard, the extracted recordImpactIncrease helper, and the integration test in tests/impact_version_test.go (stale version → no row changes, no status row; current version → impact+version updated, exactly one status row) all look correct. CI is green (build, go-test, go-test-acc, golangci-lint; CodeQL is neutral due to a pre-existing config issue).
No blocking issues — verdict approve. One warning and two suggestions below.
Warning
In-memory incident is mutated before the guarded update succeeds — internal/db/db.go, IncreaseIncidentImpact (call at ~line 928).
recordImpactIncrease(inc, impact, timeNow) runs before update.Save(ctx) and mutates the caller's object: it appends a status entry to inc.Statuses, sets inc.Impact = &impact and inc.ModifiedAt. If the update fails with a version conflict (or any DB error), the function returns an error but the caller's inc is left with Impact already bumped and a status entry appended, while Version still holds the stale value (only inc.Version = &newVersion is assigned on success). A caller that reuses the object afterwards (the call site at internal/api/v2/v2.go:719, or any retry/response built from oldInc) would see an inconsistent in-memory state that does not match the database.
Fix: compute the status text first, and perform the inc.Statuses/inc.Impact/inc.ModifiedAt mutations only after affected == 1 is confirmed — or revert them in the conflict/error paths. E.g., keep recordImpactIncrease's pure text computation early, and split the object mutation into a second step after the successful Save.
Suggestions
Possible dead 409 mapping in PostIncidentHandler — internal/api/v2/v2.go (~lines 400–407).
The new errors.Is(err, db.ErrVersionConflict) check sits in the "incident creation failed" error path. The creation path (SaveIncidentTx, a plain INSERT) never returns db.ErrVersionConflict — grep shows the error originates only from the version-guarded updates in db.go (~lines 424, 498, 981), and the impact-bump call site is at v2.go:719 (different handler; the update handler already maps the conflict at v2.go:1101). This is harmless if it's intentional defensive coding, but if the check was meant to cover the impact bump, it's in the wrong handler — worth confirming.
Nil dereference in recordImpactIncrease — internal/db/db.go (~line 1007).
fmt.Sprintf("impact changed from %d to %d", *inc.Impact, impact) panics if inc.Impact is nil. This is pre-existing (the old inline code dereferenced it too), but since the new helper now owns this logic, it would be cheap to return an error for inc.Impact == nil alongside the new Version guard.
Verification note
I could not run the suite here; the tests/ suite is reported to run against Postgres in CI and go-test-acc is green, which covers the new test.
There was a problem hiding this comment.
Summary
Fixes #119: IncreaseIncidentImpact now runs its update with Where(incident.IDEQ(id), incident.VersionEQ(expectedVersion)), sets version+1 in the same statement, and returns db.ErrVersionConflict when zero rows match (rolling back the transaction). PostIncidentHandler maps the conflict to a 409, and a new integration test covers the stale-version case. The core fix is correct and the change is small and focused.
CI: build, go-test, and check are green; go-test-acc (the Postgres suite that runs tests/impact_version_test.go) is still in progress — please confirm it passes before merging.
Findings
Warning — incident object is mutated before the version check succeeds
internal/db/db.go, IncreaseIncidentImpact (around lines 920–930): recordImpactIncrease(inc, impact, timeNow) is called before the guarded Save. On a version conflict the DB is untouched and the transaction is rolled back, but the caller's *Incident has already been modified: inc.Impact is set to the new value, inc.ModifiedAt is advanced, and a phantom status entry is appended to inc.Statuses.
Today this is contained because the only caller (moveComponentFromToSystemIncidents, internal/api/v2/v2.go:719) propagates the error to the 409 path, so the mutated object is never persisted or returned. But any caller that reuses the object after a failed bump (retry logic, logging that serializes it, a response built from it) would carry state that no longer matches the DB — the same class of bug this PR is fixing.
Fix: build the status row/text from a snapshot first, and only apply recordImpactIncrease (or the inc.Version = &newVersion update) after Save reports affected > 0. E.g.:
text := fmt.Sprintf("impact changed from %d to %d", *inc.Impact, impact)
// ... guarded update ...
if affected == 0 { _ = tx.Rollback(); return nil, ErrVersionConflict }
// only mutate on success:
inc.Statuses = append(inc.Statuses, IncidentStatus{... Text: text ...})
inc.Impact = &impact
inc.Version = &newVersion
inc.ModifiedAt = &timeNowSuggestion — missing version surfaces as a 500
internal/db/db.go (~line 920): the new guard if inc.Version == nil { return nil, errors.New("version is required for incident modification") } returns an ad-hoc error. In v2.go's error handling this falls through to apiErrors.RaiseInternalErr → 500, which is the wrong status for a client-supplied incident without a version. Consider a sentinel (e.g. ErrVersionMissing) and mapping it to 400, or at least 409, in the handler.
Suggestion (verification) — confirm the conflict error is not swallowed mid-flow
I couldn't read the full body of moveComponentFromToSystemIncidents (internal/api/v2/v2.go:674), and line 735 shows oldInc being passed to something after the IncreaseIncidentImpact call at line 719. Please verify the error from line 719 propagates unmodified up through handleSystemIncidentCreation → routeIncidentCreation to the new errors.Is(err, db.ErrVersionConflict) check at v2.go:403. If it is logged-and-continued at any point, the client would receive a 2xx while the impact was not actually raised and the in-memory oldInc has been mutated (see warning above) — that combination would be a correctness bug.
Suggestion — deleted incident reports 409 instead of 404
internal/db/db.go: affected == 0 is used for both "version changed" and "row no longer exists". A concurrent delete now yields 409 Conflict rather than 404 Not Found. Defensible for optimistic locking, but worth a code comment (or a follow-up existence check) so future readers don't assume the row must exist.
What looks good
- Version predicate +
version+1in a single statement is the right optimistic-locking pattern; the status row is only written after the update succeeds and shares the transaction. recordImpactIncreaseextraction is behavior-preserving (identical to the old inline code).- Test in
tests/impact_version_test.gocorrectly asserts, on a stale version: impact and version unchanged and zeroincident_statusrows; and on the fresh version: exactly one status row andversion+1. PostIncidentHandleris the right place for the 409 mapping since the impact bump happens inside the system-incident creation path.
Verdict: approve — the fix is correct as it stands; the warning is a robustness issue worth fixing in a follow-up (or a small follow-up commit) rather than a merge blocker.
IncreaseIncidentImpactrewrote the incident without a version predicate and kept the old version, so a stale copy could overwrite a concurrent change and later optimistic updates kept matching the old version.The update now runs
Where(incident.IDEQ(id), incident.VersionEQ(*inc.Version)), setsversion+1in the same statement and returnsErrVersionConflictwhen no row matches. The appended status row stays in the same transaction and is rolled back on conflict.PostIncidentHandlermapsErrVersionConflictto 409 using the shared conflict helper.Verification:
go build ./...,go vet ./...,go test ./internal/....TestIncreaseIncidentImpactVersionPredicateintests/impact_version_test.gochecks that a stale version changes neither impact nor version and writes no status row, while a current version updates both and appends exactly one status row; thetests/suite runs in CI against Postgres.Closes #119