Skip to content

Commit 70aab5e

Browse files
AgentWrapperclaude
andcommitted
feat(backend): atomic PR-observation write + CDC on check status updates
Addresses review on PR-observation persistence: - pr_checks now has an AFTER UPDATE CDC trigger (guarded on status change), so a check flipping in_progress->failed on the same commit emits change_log instead of updating silently. Restores symmetry with the sessions/pr triggers. - writePR persists scalar facts + checks + comments in ONE transaction via Store.WritePRObservation, so a mid-write failure can't leave the pr row (and its CDC event) committed while checks/comments are partial. Collapses the PRWriter port's three write methods into one WritePR. - db.go: record why modernc.org/sqlite (pure-Go, CGO-free static binary) at the import site. Regression tests for both the update-trigger (emit on change, suppress no-op re-poll) and the transactional write. go test -race ./... green. Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 0dbd304 commit 70aab5e

8 files changed

Lines changed: 212 additions & 57 deletions

File tree

‎backend/internal/lifecycle/manager.go‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -176,27 +176,31 @@ func (m *Manager) ApplyPRObservation(ctx context.Context, id domain.SessionID, o
176176
return m.runReactions(ctx, id, prContent(o))
177177
}
178178

179-
// writePR upserts the scalar facts, records each check run, and replaces the
180-
// comment set. PR-table CDC is emitted by the DB triggers.
179+
// writePR persists the observation's scalar facts, check runs, and comment set
180+
// in one atomic store call. PR-table CDC is emitted by the DB triggers.
181181
func (m *Manager) writePR(ctx context.Context, id domain.SessionID, o ports.PRObservation) error {
182182
now := m.clock()
183-
if err := m.pr.UpsertPR(ctx, ports.PRRow{
183+
row := ports.PRRow{
184184
URL: o.URL, SessionID: string(id), Number: o.Number,
185185
Draft: o.Draft, Merged: o.Merged, Closed: o.Closed,
186186
CI: o.CI, Review: o.Review, Mergeability: o.Mergeability, UpdatedAt: now,
187-
}); err != nil {
188-
return err
189187
}
190-
for _, c := range o.Checks {
188+
checks := make([]ports.PRCheckRow, len(o.Checks))
189+
for i, c := range o.Checks {
191190
c.PRURL = o.URL
192191
if c.CreatedAt.IsZero() {
193192
c.CreatedAt = now
194193
}
195-
if err := m.pr.RecordCheck(ctx, c); err != nil {
196-
return err
194+
checks[i] = c
195+
}
196+
comments := make([]ports.PRComment, len(o.Comments))
197+
for i, c := range o.Comments {
198+
if c.CreatedAt.IsZero() {
199+
c.CreatedAt = now
197200
}
201+
comments[i] = c
198202
}
199-
return m.pr.ReplacePRComments(ctx, o.URL, o.Comments)
203+
return m.pr.WritePR(ctx, row, checks, comments)
200204
}
201205

202206
// ---- mutation commands from the Session Manager ----

‎backend/internal/lifecycle/manager_test.go‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,10 @@ func (f *fakeStore) PRFactsForSession(_ context.Context, id domain.SessionID) (d
8282
}
8383
return facts, nil
8484
}
85-
func (f *fakeStore) UpsertPR(_ context.Context, r ports.PRRow) error {
86-
f.pr[domain.SessionID(r.SessionID)] = r
87-
return nil
88-
}
89-
func (f *fakeStore) RecordCheck(_ context.Context, r ports.PRCheckRow) error {
90-
f.checks = append(f.checks, r)
85+
func (f *fakeStore) WritePR(_ context.Context, pr ports.PRRow, checks []ports.PRCheckRow, comments []ports.PRComment) error {
86+
f.pr[domain.SessionID(pr.SessionID)] = pr
87+
f.checks = append(f.checks, checks...)
88+
f.comments[pr.URL] = comments
9189
return nil
9290
}
9391
func (f *fakeStore) RecentCheckStatuses(_ context.Context, url, name string, limit int) ([]string, error) {
@@ -99,10 +97,6 @@ func (f *fakeStore) RecentCheckStatuses(_ context.Context, url, name string, lim
9997
}
10098
return out, nil
10199
}
102-
func (f *fakeStore) ReplacePRComments(_ context.Context, url string, cs []ports.PRComment) error {
103-
f.comments[url] = cs
104-
return nil
105-
}
106100

107101
type fakeNotifier struct{ events []ports.Event }
108102

‎backend/internal/ports/outbound.go‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,12 @@ type SessionStore interface {
2424
// PRWriter records the PR facts a PR observation carries. The pr table's own DB
2525
// triggers emit the CDC; this just writes the rows.
2626
type PRWriter interface {
27-
UpsertPR(ctx context.Context, r PRRow) error
28-
RecordCheck(ctx context.Context, r PRCheckRow) error
27+
// WritePR persists a full PR observation — scalar facts, check runs, and the
28+
// replacement comment set — in one transaction, so the rows and the CDC
29+
// events they emit are all-or-nothing.
30+
WritePR(ctx context.Context, pr PRRow, checks []PRCheckRow, comments []PRComment) error
31+
// RecentCheckStatuses reads the last `limit` runs of a check (the CI brake).
2932
RecentCheckStatuses(ctx context.Context, prURL, name string, limit int) ([]string, error)
30-
ReplacePRComments(ctx context.Context, prURL string, comments []PRComment) error
3133
}
3234

3335
// Notifier delivers an event to the human (desktop/Slack later). Push, never poll.

‎backend/internal/storage/sqlite/db.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ import (
1111
"path/filepath"
1212

1313
"github.com/pressly/goose/v3"
14+
// modernc.org/sqlite is the pure-Go (CGO-free) SQLite driver — chosen so the
15+
// daemon cross-compiles and ships as a static binary with no libsqlite/CGO
16+
// toolchain dependency, at the cost of some raw throughput vs a C-backed driver.
1417
_ "modernc.org/sqlite"
1518
)
1619

‎backend/internal/storage/sqlite/migrations/0001_init.sql‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,25 @@ BEGIN
202202
END;
203203
-- +goose StatementEnd
204204

205+
-- A re-polled check can change status on the same commit (in_progress -> failed)
206+
-- via UpsertPRCheck's ON CONFLICT DO UPDATE. Without this trigger that status
207+
-- transition would update the row silently, so CDC consumers would never see it.
208+
-- Guarded on the status so a no-op re-poll emits nothing.
209+
-- +goose StatementBegin
210+
CREATE TRIGGER pr_checks_cdc_update
211+
AFTER UPDATE ON pr_checks
212+
WHEN OLD.status <> NEW.status
213+
BEGIN
214+
INSERT INTO change_log (project_id, session_id, event_type, payload, created_at)
215+
VALUES (
216+
(SELECT s.project_id FROM pr p JOIN sessions s ON s.id = p.session_id WHERE p.url = NEW.pr_url),
217+
(SELECT session_id FROM pr WHERE url = NEW.pr_url),
218+
'pr_check_recorded',
219+
json_object('pr', NEW.pr_url, 'name', NEW.name, 'commit', NEW.commit_hash, 'status', NEW.status),
220+
NEW.created_at);
221+
END;
222+
-- +goose StatementEnd
223+
205224
-- +goose Down
206225
-- +goose StatementBegin
207226
DROP TABLE change_log;
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package sqlite
2+
3+
import (
4+
"context"
5+
"strings"
6+
"testing"
7+
"time"
8+
)
9+
10+
// A check can change status on the same commit (in_progress -> failed) via
11+
// UpsertPRCheck's ON CONFLICT DO UPDATE. CDC must emit on that transition, not
12+
// only on the first insert — otherwise live clients never see the status change.
13+
func TestPRChecksCDC_EmitsOnInsertAndStatusUpdate(t *testing.T) {
14+
s := newTestStore(t)
15+
ctx := context.Background()
16+
seedProject(t, s, "mer")
17+
rec, err := s.CreateSession(ctx, sampleRecord("mer"))
18+
if err != nil {
19+
t.Fatal(err)
20+
}
21+
url := "https://example/pr/1"
22+
if err := s.UpsertPR(ctx, PRRow{URL: url, SessionID: string(rec.ID), Number: 1}); err != nil {
23+
t.Fatal(err)
24+
}
25+
26+
now := time.Now()
27+
mustCheck := func(status string) {
28+
if err := s.RecordCheck(ctx, PRCheckRow{PRURL: url, Name: "build", CommitHash: "c1", Status: status, CreatedAt: now}); err != nil {
29+
t.Fatal(err)
30+
}
31+
}
32+
mustCheck("in_progress") // insert -> event
33+
mustCheck("failed") // status change on same commit (update) -> event
34+
mustCheck("failed") // no-op re-poll (status unchanged) -> NO event
35+
36+
rows, err := s.ReadChangeLogAfter(ctx, 0, 100)
37+
if err != nil {
38+
t.Fatal(err)
39+
}
40+
var checkEvents []ChangeLogRow
41+
for _, r := range rows {
42+
if r.EventType == "pr_check_recorded" {
43+
checkEvents = append(checkEvents, r)
44+
}
45+
}
46+
if len(checkEvents) != 2 {
47+
t.Fatalf("want 2 check CDC events (insert + status change, no-op suppressed), got %d", len(checkEvents))
48+
}
49+
if !strings.Contains(checkEvents[1].Payload, `"status":"failed"`) {
50+
t.Fatalf("the update event should carry the new status, got %q", checkEvents[1].Payload)
51+
}
52+
}
53+
54+
// WritePRObservation persists scalar facts, checks, and comments in one tx; all
55+
// three should be queryable afterward.
56+
func TestWritePRObservation_PersistsScalarsChecksAndComments(t *testing.T) {
57+
s := newTestStore(t)
58+
ctx := context.Background()
59+
seedProject(t, s, "mer")
60+
rec, err := s.CreateSession(ctx, sampleRecord("mer"))
61+
if err != nil {
62+
t.Fatal(err)
63+
}
64+
url := "https://example/pr/7"
65+
now := time.Now()
66+
67+
err = s.WritePRObservation(ctx,
68+
PRRow{URL: url, SessionID: string(rec.ID), Number: 7, CIState: "failing", UpdatedAt: now},
69+
[]PRCheckRow{{PRURL: url, Name: "build", CommitHash: "c1", Status: "failed", CreatedAt: now}},
70+
[]PRCommentRow{{PRURL: url, CommentID: "1", Author: "reviewer", Body: "use a const", CreatedAt: now}},
71+
)
72+
if err != nil {
73+
t.Fatal(err)
74+
}
75+
76+
pr, ok, err := s.GetPR(ctx, url)
77+
if err != nil || !ok || pr.CIState != "failing" {
78+
t.Fatalf("scalar facts not persisted: ok=%v ci=%q err=%v", ok, pr.CIState, err)
79+
}
80+
if checks, _ := s.ListChecks(ctx, url); len(checks) != 1 || checks[0].Status != "failed" {
81+
t.Fatalf("check not persisted: %+v", checks)
82+
}
83+
if comments, _ := s.ListPRComments(ctx, url); len(comments) != 1 || comments[0].Body != "use a const" {
84+
t.Fatalf("comment not persisted: %+v", comments)
85+
}
86+
}

‎backend/internal/storage/sqlite/pr_store.go‎

Lines changed: 62 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,7 @@ type PRRow struct {
2727
// fields default to their "nothing known yet" value so a partial row is valid
2828
// against the CHECK constraints (matches the domain zero values none/unknown).
2929
func (s *Store) UpsertPR(ctx context.Context, r PRRow) error {
30-
if r.State == "" {
31-
r.State = "open"
32-
}
33-
if r.ReviewDecision == "" {
34-
r.ReviewDecision = "none"
35-
}
36-
if r.CIState == "" {
37-
r.CIState = "unknown"
38-
}
39-
if r.Mergeability == "" {
40-
r.Mergeability = "unknown"
41-
}
30+
r = r.withDefaults()
4231
s.writeMu.Lock()
4332
defer s.writeMu.Unlock()
4433
return s.qw.UpsertPR(ctx, gen.UpsertPRParams{
@@ -53,6 +42,67 @@ func (s *Store) UpsertPR(ctx context.Context, r PRRow) error {
5342
})
5443
}
5544

45+
// WritePRObservation persists a full PR observation — scalar facts, check runs,
46+
// and the replacement comment set — in one write transaction, so the rows and
47+
// the change_log events their triggers emit are committed all-or-nothing. The
48+
// scalar PR upsert runs first so the checks'/comments' CDC triggers can resolve
49+
// the session id from the pr row within the same transaction.
50+
func (s *Store) WritePRObservation(ctx context.Context, pr PRRow, checks []PRCheckRow, comments []PRCommentRow) error {
51+
pr = pr.withDefaults()
52+
s.writeMu.Lock()
53+
defer s.writeMu.Unlock()
54+
return s.inTx(ctx, "write pr observation", func(q *gen.Queries) error {
55+
if err := q.UpsertPR(ctx, gen.UpsertPRParams{
56+
Url: pr.URL, SessionID: pr.SessionID, Number: pr.Number,
57+
PrState: pr.State, ReviewDecision: pr.ReviewDecision,
58+
CiState: pr.CIState, Mergeability: pr.Mergeability, UpdatedAt: pr.UpdatedAt,
59+
}); err != nil {
60+
return err
61+
}
62+
for _, c := range checks {
63+
if c.Status == "" {
64+
c.Status = "unknown"
65+
}
66+
if err := q.UpsertPRCheck(ctx, gen.UpsertPRCheckParams{
67+
PrUrl: c.PRURL, Name: c.Name, CommitHash: c.CommitHash,
68+
Status: c.Status, Url: c.URL, LogTail: c.LogTail, CreatedAt: c.CreatedAt,
69+
}); err != nil {
70+
return err
71+
}
72+
}
73+
if err := q.DeletePRComments(ctx, pr.URL); err != nil {
74+
return err
75+
}
76+
for _, cm := range comments {
77+
if err := q.UpsertPRComment(ctx, gen.UpsertPRCommentParams{
78+
PrUrl: pr.URL, CommentID: cm.CommentID, Author: cm.Author, File: cm.File,
79+
Line: cm.Line, Body: cm.Body, Resolved: boolToInt(cm.Resolved), CreatedAt: cm.CreatedAt,
80+
}); err != nil {
81+
return fmt.Errorf("comment %q: %w", cm.CommentID, err)
82+
}
83+
}
84+
return nil
85+
})
86+
}
87+
88+
// withDefaults fills empty enum fields with their "nothing known yet" value so a
89+
// partial row satisfies the CHECK constraints (matches UpsertPR).
90+
func (r PRRow) withDefaults() PRRow {
91+
if r.State == "" {
92+
r.State = "open"
93+
}
94+
if r.ReviewDecision == "" {
95+
r.ReviewDecision = "none"
96+
}
97+
if r.CIState == "" {
98+
r.CIState = "unknown"
99+
}
100+
if r.Mergeability == "" {
101+
r.Mergeability = "unknown"
102+
}
103+
return r
104+
}
105+
56106
// GetPR returns the PR facts for a URL, or ok=false if absent.
57107
func (s *Store) GetPR(ctx context.Context, url string) (PRRow, bool, error) {
58108
p, err := s.qr.GetPR(ctx, url)

‎backend/lifecycle_wiring.go‎

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -87,33 +87,30 @@ func (a storeAdapter) PRFactsForSession(ctx context.Context, id domain.SessionID
8787
return facts, nil
8888
}
8989

90-
func (a storeAdapter) UpsertPR(ctx context.Context, r ports.PRRow) error {
91-
return a.Store.UpsertPR(ctx, sqlite.PRRow{
92-
URL: r.URL, SessionID: r.SessionID, Number: int64(r.Number),
93-
State: prState(r),
94-
ReviewDecision: string(r.Review),
95-
CIState: string(r.CI),
96-
Mergeability: string(r.Mergeability),
97-
UpdatedAt: r.UpdatedAt,
98-
})
99-
}
100-
101-
func (a storeAdapter) RecordCheck(ctx context.Context, r ports.PRCheckRow) error {
102-
return a.Store.RecordCheck(ctx, sqlite.PRCheckRow{
103-
PRURL: r.PRURL, Name: r.Name, CommitHash: r.CommitHash,
104-
Status: r.Status, URL: r.URL, LogTail: r.LogTail, CreatedAt: r.CreatedAt,
105-
})
106-
}
107-
108-
func (a storeAdapter) ReplacePRComments(ctx context.Context, prURL string, comments []ports.PRComment) error {
109-
rows := make([]sqlite.PRCommentRow, len(comments))
90+
func (a storeAdapter) WritePR(ctx context.Context, pr ports.PRRow, checks []ports.PRCheckRow, comments []ports.PRComment) error {
91+
row := sqlite.PRRow{
92+
URL: pr.URL, SessionID: pr.SessionID, Number: int64(pr.Number),
93+
State: prState(pr),
94+
ReviewDecision: string(pr.Review),
95+
CIState: string(pr.CI),
96+
Mergeability: string(pr.Mergeability),
97+
UpdatedAt: pr.UpdatedAt,
98+
}
99+
checkRows := make([]sqlite.PRCheckRow, len(checks))
100+
for i, c := range checks {
101+
checkRows[i] = sqlite.PRCheckRow{
102+
PRURL: c.PRURL, Name: c.Name, CommitHash: c.CommitHash,
103+
Status: c.Status, URL: c.URL, LogTail: c.LogTail, CreatedAt: c.CreatedAt,
104+
}
105+
}
106+
commentRows := make([]sqlite.PRCommentRow, len(comments))
110107
for i, c := range comments {
111-
rows[i] = sqlite.PRCommentRow{
112-
PRURL: prURL, CommentID: c.ID, Author: c.Author, File: c.File,
108+
commentRows[i] = sqlite.PRCommentRow{
109+
PRURL: pr.URL, CommentID: c.ID, Author: c.Author, File: c.File,
113110
Line: int64(c.Line), Body: c.Body, Resolved: c.Resolved, CreatedAt: c.CreatedAt,
114111
}
115112
}
116-
return a.Store.ReplacePRComments(ctx, prURL, rows)
113+
return a.Store.WritePRObservation(ctx, row, checkRows, commentRows)
117114
}
118115

119116
// prState collapses the PR's bools into the single pr.state column value.

0 commit comments

Comments
 (0)