From a4432d300cc96d280bbfc7077db3d12376c992e6 Mon Sep 17 00:00:00 2001 From: Aloento <11802769+Aloento@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:38:53 +0100 Subject: [PATCH 1/2] [Fix] Read extraction incidents inside the transaction 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. --- internal/db/db.go | 147 +++++++++++++++++++++++++++++++-------- internal/db/lock.go | 19 +++++ tests/extract_tx_test.go | 79 +++++++++++++++++++-- 3 files changed, 213 insertions(+), 32 deletions(-) diff --git a/internal/db/db.go b/internal/db/db.go index 12d2ceb..7b695b0 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -261,7 +261,14 @@ func (db *DB) GetEventsInternal(ctx context.Context, params ...*IncidentsParams) } func (db *DB) GetIncident(ctx context.Context, id int) (*Incident, error) { - e, err := db.e.Incident.Query(). + return db.getIncidentTx(ctx, nil, id) +} + +// getIncidentTx reads an incident with its components and statuses through tx, +// or through the pool when tx is nil. +func (db *DB) getIncidentTx(ctx context.Context, tx *Tx, id int) (*Incident, error) { + c := db.clientFor(tx) + e, err := c.Incident.Query(). Where(incident.IDEQ(id)). WithComponents(func(q *ent.ComponentQuery) { q.Select(component.FieldID, component.FieldName) @@ -276,11 +283,17 @@ func (db *DB) GetIncident(ctx context.Context, id int) (*Incident, error) { } inc := incidentFromEnt(e) - grouped, err := db.statusesByIncident(ctx, []int{e.ID}) + statuses, err := c.IncidentStatus.Query(). + Where(incidentstatus.IncidentID(e.ID)). + Order(incidentstatus.ByID(entsql.OrderAsc())). + All(ctx) if err != nil { return nil, err } - attachStatuses([]*Incident{inc}, grouped) + inc.Statuses = make([]IncidentStatus, 0, len(statuses)) + for _, status := range statuses { + inc.Statuses = append(inc.Statuses, incidentStatusFromEnt(status)) + } return inc, nil } @@ -847,6 +860,49 @@ func (db *DB) MoveComponentFromOldToAnotherIncident( return incNew, nil } +// currentComponentsTx re-reads the components to extract inside the +// transaction, preserving the caller's order. A component that disappeared +// aborts the extraction instead of being reported with stale attributes. +func (db *DB) currentComponentsTx(ctx context.Context, tx *Tx, comps []Component) ([]Component, error) { + ids := make([]int, 0, len(comps)) + for i := range comps { + if comps[i].ID != 0 { + ids = append(ids, int(comps[i].ID)) + } + } + if len(ids) == 0 { + return comps, nil + } + + rows, err := db.clientFor(tx).Component.Query(). + Where(component.IDIn(ids...)). + WithAttributes(). + All(ctx) + if err != nil { + return nil, err + } + + byID := make(map[int]Component, len(rows)) + for _, row := range rows { + byID[row.ID] = componentFromEnt(row) + } + + out := make([]Component, len(comps)) + for i := range comps { + if comps[i].ID == 0 { + out[i] = comps[i] + continue + } + stored, ok := byID[int(comps[i].ID)] + if !ok { + return nil, ErrDBComponentDSNotExist + } + out[i] = stored + } + + return out, nil +} + func (db *DB) ExtractComponentsToNewIncident( ctx context.Context, comp []Component, incOld *Incident, impact int, text string, description *string, ) (*Incident, error) { @@ -870,38 +926,33 @@ func (db *DB) ExtractComponentsToNewIncident( } err := db.WithTx(ctx, func(tx *Tx) error { - if _, saveErr := db.SaveIncidentTx(ctx, tx, inc); saveErr != nil { - return saveErr + // The caller loaded the source incident before this transaction, so lock + // and re-read it: its components, statuses and version may have changed. + if lockErr := lockIncidentRows(ctx, db.rawFor(tx), incOld.ID); lockErr != nil { + return lockErr + } + freshOld, readErr := db.getIncidentTx(ctx, tx, int(incOld.ID)) + if readErr != nil { + return readErr } + *incOld = *freshOld - for _, c := range comp { - inc.Statuses = append(inc.Statuses, IncidentStatus{ - IncidentID: inc.ID, - Status: event.OutDatedSystem, - Text: fmt.Sprintf("%s moved from %s", c.PrintAttrs(), incOld.Link()), - Timestamp: timeNow, - }) + freshComps, readErr := db.currentComponentsTx(ctx, tx, comp) + if readErr != nil { + return readErr } + comp = freshComps + inc.Components = comp - for _, c := range comp { - incOld.Statuses = append(incOld.Statuses, IncidentStatus{ - IncidentID: incOld.ID, - Status: event.OutDatedSystem, - Text: fmt.Sprintf("%s moved to %s", c.PrintAttrs(), inc.Link()), - Timestamp: timeNow, - }) + if _, saveErr := db.SaveIncidentTx(ctx, tx, inc); saveErr != nil { + return saveErr } - client := db.clientFor(tx) + appendExtractionStatuses(inc, incOld, comp, timeNow) - for i := range comp { - if comp[i].ID == 0 { - continue - } - if errRemove := removeIncidentComponent(ctx, client, incOld.ID, comp[i].ID); errRemove != nil { - return errRemove - } - dropIncidentComponent(incOld, comp[i].ID) + client := db.clientFor(tx) + if errRemove := detachExtractedComponents(ctx, client, incOld, comp); errRemove != nil { + return errRemove } if errSave := saveIncidentFull(ctx, client, inc); errSave != nil { @@ -916,6 +967,46 @@ func (db *DB) ExtractComponentsToNewIncident( return inc, nil } +// appendExtractionStatuses records the move on both incidents; the following +// saveIncidentFull calls insert the rows. +func appendExtractionStatuses(inc, incOld *Incident, comp []Component, timeNow time.Time) { + for _, c := range comp { + inc.Statuses = append(inc.Statuses, IncidentStatus{ + IncidentID: inc.ID, + Status: event.OutDatedSystem, + Text: fmt.Sprintf("%s moved from %s", c.PrintAttrs(), incOld.Link()), + Timestamp: timeNow, + }) + } + + for _, c := range comp { + incOld.Statuses = append(incOld.Statuses, IncidentStatus{ + IncidentID: incOld.ID, + Status: event.OutDatedSystem, + Text: fmt.Sprintf("%s moved to %s", c.PrintAttrs(), inc.Link()), + Timestamp: timeNow, + }) + } +} + +// detachExtractedComponents removes the extracted components from the source +// incident and from its in-memory association list. +func detachExtractedComponents( + ctx context.Context, client *ent.Client, incOld *Incident, comp []Component, +) error { + for i := range comp { + if comp[i].ID == 0 { + continue + } + if err := removeIncidentComponent(ctx, client, incOld.ID, comp[i].ID); err != nil { + return err + } + dropIncidentComponent(incOld, comp[i].ID) + } + + return nil +} + func (db *DB) IncreaseIncidentImpact(ctx context.Context, inc *Incident, impact int) (*Incident, error) { timeNow := time.Now().UTC() text := fmt.Sprintf("impact changed from %d to %d", *inc.Impact, impact) diff --git a/internal/db/lock.go b/internal/db/lock.go index 6fdc0fb..f22e048 100644 --- a/internal/db/lock.go +++ b/internal/db/lock.go @@ -2,6 +2,7 @@ package db import ( "context" + "slices" entsql "entgo.io/ent/dialect/sql" ) @@ -46,3 +47,21 @@ func lockComponentName(ctx context.Context, raw entsql.ExecQuerier, name, region _, err := raw.ExecContext(ctx, "SELECT pg_advisory_xact_lock(hashtext($1))", name+"|"+region) return err } + +// lockIncidentRows takes row locks on the given incidents until the surrounding +// transaction ends. Rows are locked in ascending id order so transactions that +// touch the same pair cannot deadlock. +func lockIncidentRows(ctx context.Context, raw entsql.ExecQuerier, ids ...uint) error { + ordered := slices.Clone(ids) + slices.Sort(ordered) + + for _, id := range ordered { + if _, err := raw.ExecContext( + ctx, "SELECT id FROM incident WHERE id = $1 FOR UPDATE", int(id), + ); err != nil { + return err + } + } + + return nil +} diff --git a/tests/extract_tx_test.go b/tests/extract_tx_test.go index c2c2c2f..d359e2c 100644 --- a/tests/extract_tx_test.go +++ b/tests/extract_tx_test.go @@ -49,10 +49,12 @@ func TestExtractComponentsRollsBackOnSecondPhaseFailure(t *testing.T) { require.NoError(t, err) require.Len(t, incOld.Components, 1) - // An empty text fails saveIncidentFull after the new incident, its statuses - // and the association removal were written. - emptyText := "" - incOld.Text = &emptyText + // An empty stored text fails saveIncidentFull after the new incident, its + // statuses and the association removal were written. Updating the row rather + // than the caller's copy also proves the extraction re-reads it in the + // transaction. + _, err = g.Exec("UPDATE incident SET text = '' WHERE id = $1", oldID) + require.NoError(t, err) newText := "extracted incident " + uuid.NewString() description := "extract transaction probe" @@ -68,3 +70,72 @@ func TestExtractComponentsRollsBackOnSecondPhaseFailure(t *testing.T) { assert.Equal(t, int64(1), tableCount(t, g, "incident_component_relation", "incident_id = $1 AND component_id = $2", oldID, comp.ID)) } + +// TestExtractComponentsUsesFreshIncidentState changes the source incident after +// the caller has read it and checks that the extraction works from the stored +// row: a component and a version written by the concurrent change must survive. +func TestExtractComponentsUsesFreshIncidentState(t *testing.T) { + ctx := context.Background() + d, _ := newNotifDB(t) + + probes := make([]*db.Component, 3) + for i := range probes { + probes[i] = newProbeComponent("extract probe "+uuid.NewString(), "EU-DE") + _, err := d.SaveComponent(ctx, probes[i]) + require.NoError(t, err) + } + compA, compB, compC := probes[0], probes[1], probes[2] + + start := time.Now().UTC() + impact := 2 + oldText := "source incident " + uuid.NewString() + + oldID, err := d.SaveIncident(ctx, &db.Incident{ + Text: &oldText, + StartDate: &start, + Impact: &impact, + Status: event.OutDatedSystem, + Type: event.TypeIncident, + Components: []db.Component{*compA, *compB}, + }) + require.NoError(t, err) + + staleOld, err := d.GetIncident(ctx, int(oldID)) + require.NoError(t, err) + require.Len(t, staleOld.Components, 2) + + // The caller's copy is stale from here on: a concurrent writer adds a + // component and bumps the version before the extraction starts. + freshOld, err := d.GetIncident(ctx, int(oldID)) + require.NoError(t, err) + added := db.IncidentStatus{ + IncidentID: oldID, + Status: event.IncidentDetected, + Text: "concurrent update", + Timestamp: time.Now().UTC(), + } + require.NoError(t, d.AddComponentToIncident(ctx, freshOld, compC, added)) + + newText := "extracted incident " + uuid.NewString() + description := "fresh read probe" + inc, err := d.ExtractComponentsToNewIncident( + ctx, []db.Component{*compA}, staleOld, impact, newText, &description, + ) + require.NoError(t, err) + require.Len(t, inc.Components, 1) + assert.Equal(t, compA.ID, inc.Components[0].ID) + + after, err := d.GetIncident(ctx, int(oldID)) + require.NoError(t, err) + assert.ElementsMatch(t, []uint{compB.ID, compC.ID}, incidentComponentIDs(after)) + assert.Equal(t, *freshOld.Version, *after.Version, + "the extraction must keep the version written by the concurrent change") +} + +func incidentComponentIDs(inc *db.Incident) []uint { + ids := make([]uint, len(inc.Components)) + for i := range inc.Components { + ids[i] = inc.Components[i].ID + } + return ids +} From e132f18ac0296421a0ba3cf9cd0f7032bcb49100 Mon Sep 17 00:00:00 2001 From: Aloento <11802769+Aloento@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:54:20 +0100 Subject: [PATCH 2/2] [Fix] Reject soft-deleted components when re-reading extraction inputs 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. --- internal/db/db.go | 2 +- internal/db/lock.go | 4 +++- tests/extract_tx_test.go | 42 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/internal/db/db.go b/internal/db/db.go index 7b695b0..5a724de 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -875,7 +875,7 @@ func (db *DB) currentComponentsTx(ctx context.Context, tx *Tx, comps []Component } rows, err := db.clientFor(tx).Component.Query(). - Where(component.IDIn(ids...)). + Where(component.IDIn(ids...), component.DeletedAtIsNil()). WithAttributes(). All(ctx) if err != nil { diff --git a/internal/db/lock.go b/internal/db/lock.go index f22e048..ae0de24 100644 --- a/internal/db/lock.go +++ b/internal/db/lock.go @@ -50,7 +50,9 @@ func lockComponentName(ctx context.Context, raw entsql.ExecQuerier, name, region // lockIncidentRows takes row locks on the given incidents until the surrounding // transaction ends. Rows are locked in ascending id order so transactions that -// touch the same pair cannot deadlock. +// touch the same pair cannot deadlock. Only the named rows are locked: two +// extractions from different incidents that share a component stay unserialized, +// which is accepted and out of scope here. func lockIncidentRows(ctx context.Context, raw entsql.ExecQuerier, ids ...uint) error { ordered := slices.Clone(ids) slices.Sort(ordered) diff --git a/tests/extract_tx_test.go b/tests/extract_tx_test.go index d359e2c..2a652db 100644 --- a/tests/extract_tx_test.go +++ b/tests/extract_tx_test.go @@ -132,6 +132,48 @@ func TestExtractComponentsUsesFreshIncidentState(t *testing.T) { "the extraction must keep the version written by the concurrent change") } +// TestExtractComponentsAbortsOnSoftDeletedComponent soft-deletes a component +// between the caller's read and the extraction; the re-read must treat it as +// missing instead of extracting it with stale attributes. +func TestExtractComponentsAbortsOnSoftDeletedComponent(t *testing.T) { + ctx := context.Background() + d, g := newNotifDB(t) + + comp := newProbeComponent("extract probe "+uuid.NewString(), "EU-FR") + _, err := d.SaveComponent(ctx, comp) + require.NoError(t, err) + + start := time.Now().UTC() + impact := 2 + oldText := "source incident " + uuid.NewString() + oldID, err := d.SaveIncident(ctx, &db.Incident{ + Text: &oldText, + StartDate: &start, + Impact: &impact, + Status: event.OutDatedSystem, + Type: event.TypeIncident, + Components: []db.Component{*comp}, + }) + require.NoError(t, err) + + incOld, err := d.GetIncident(ctx, int(oldID)) + require.NoError(t, err) + + _, err = g.Exec("UPDATE component SET deleted_at = now() WHERE id = $1", comp.ID) + require.NoError(t, err) + + newText := "extracted incident " + uuid.NewString() + description := "soft delete probe" + _, err = d.ExtractComponentsToNewIncident( + ctx, []db.Component{*comp}, incOld, impact, newText, &description, + ) + require.ErrorIs(t, err, db.ErrDBComponentDSNotExist) + + assert.Equal(t, int64(0), tableCount(t, g, "incident", "text = $1", newText)) + assert.Equal(t, int64(1), tableCount(t, g, "incident_component_relation", + "incident_id = $1 AND component_id = $2", oldID, comp.ID)) +} + func incidentComponentIDs(inc *db.Incident) []uint { ids := make([]uint, len(inc.Components)) for i := range inc.Components {