feat(tasks): attribute events, changes and config to the attempt that produced them
The events table had no attempt column, so two attempts of the same task were indistinguishable: a retried task's stage events interleaved into one timeline and nothing could say which run produced a given result. - events gains an `attempt` column through the existing presence-gated migrateTasks loop rather than a version bump, so user_version stays 3 and an existing archie.db is migrated in place. A legacy-database test builds the pre-change schema and proves both that existing rows survive unattributed (attempt = 0) and that a new value round-trips. - Event.attempt = 11 and ReadTaskLogRequest.stage = 9 are field additions to existing messages: no new RPC, no new table, and no change to any canonical error message that crosses the state-store wire. - Every task event the workflow engine emits now carries the attempt. Producers that have no attempt yet (task_queued, binding_dispatch_failure) stay unattributed rather than guessing one. - Changed files are captured as a durable changes_captured event at commit and push time, reusing the existing three-dot diff primitive: paths from FilePatches(), counts from Stats(), base_sha recorded as the merge base actually diffed rather than the base tip, a 200-file cap with totals kept complete. Consumption goes through an unexported optional interface so workflow.Trees -- the yaegi capability surface for interpreted stage plugins -- is not widened. A capture is also taken once the pull request exists, so the capture can link it. - The per-attempt configuration is captured as a durable config_captured event carrying the non-secret config.TaskConfig, instead of a new table plus two new state-store RPCs: events are already this system's per-attempt provenance stream, so a table would have given one feature two provenance mechanisms. Redaction is proven against canary secrets. Measured payload: 539 bytes typical, 2333 bytes at 20 models. - Captures carry a schema marker and are refused unless their key set matches the declared payload shape, so drift surfaces as "recorded but could not be read" rather than as a capture of zeroes. - Three read endpoints serve the attempt rail, the changed-file captures and a raw debug view, mapping to UI-owned response types rather than dumping store types. - The task-log read gains a stage filter, bound to the stage logger for that stage's own lines; agent and tool output records no stage. A task-scoped grant may already insert events on its own task, so this provenance is exactly as trustworthy as the rest of that task's event stream. That limit is documented rather than papered over.
This commit is contained in:
1 parent
14e7512d14
commit
2c09f42ff4
39 files changed
+4264
-83
No files matched your search
@@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS events (
|
||||
issue INTEGER NOT NULL DEFAULT 0,
|
||||
workflow TEXT NOT NULL DEFAULT '',
|
||||
stage TEXT NOT NULL DEFAULT '',
|
||||
attempt INTEGER NOT NULL DEFAULT 0,
|
||||
detail TEXT NOT NULL DEFAULT '',
|
||||
data TEXT NOT NULL DEFAULT '{}'
|
||||
);
|
||||
@@ -47,10 +48,10 @@ func insertEvent(ctx context.Context, execer eventExecer, e events.Event) (int64
|
||||
data = fmt.Appendf(nil, `{"marshal_error":%q}`, err.Error())
|
||||
}
|
||||
res, err := execer.ExecContext(ctx, `
|
||||
INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, detail, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, attempt, detail, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
e.At.UTC().Format(time.RFC3339Nano), e.Kind, e.TaskID, e.Repo, e.Issue,
|
||||
e.Workflow, e.Stage, clip(e.Detail, 4000), string(data))
|
||||
e.Workflow, e.Stage, e.Attempt, clip(e.Detail, 4000), string(data))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -65,7 +66,7 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) {
|
||||
var e events.Event
|
||||
var at, data string
|
||||
if err := rows.Scan(&e.ID, &at, &e.Kind, &e.TaskID, &e.Repo, &e.Issue,
|
||||
&e.Workflow, &e.Stage, &e.Detail, &data); err != nil {
|
||||
&e.Workflow, &e.Stage, &e.Attempt, &e.Detail, &data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.At, _ = time.Parse(time.RFC3339Nano, at)
|
||||
@@ -75,7 +76,7 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) {
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, detail, data"
|
||||
const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, attempt, detail, data"
|
||||
|
||||
// EventsSince returns up to limit events with id > sinceID, oldest
|
||||
// first -- SSE catch-up and the live feed.
|
||||
|
||||
+21
-3
@@ -95,6 +95,15 @@ func migrateTasks(ctx context.Context, db *sql.DB) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// events is created by `CREATE TABLE IF NOT EXISTS` (eventsSchema), which
|
||||
// is a no-op against a database that already has the table. On an existing
|
||||
// archie.db this read plus the `events` arm below is therefore the ONLY
|
||||
// thing that adds events.attempt; without it the first insert fails with
|
||||
// `table events has no column named attempt`.
|
||||
eventsColumns, err := tableColumns(ctx, tx, "events")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
migrations := []struct {
|
||||
table string
|
||||
@@ -109,11 +118,15 @@ func migrateTasks(ctx context.Context, db *sql.DB) error {
|
||||
{"tasks", "binding_version", `ALTER TABLE tasks ADD COLUMN binding_version INTEGER NOT NULL DEFAULT 0`},
|
||||
{"bindings", "owner", `ALTER TABLE bindings ADD COLUMN owner TEXT NOT NULL DEFAULT ''`},
|
||||
{"bindings", "repo", `ALTER TABLE bindings ADD COLUMN repo TEXT NOT NULL DEFAULT ''`},
|
||||
{"events", "attempt", `ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`},
|
||||
}
|
||||
for _, migration := range migrations {
|
||||
present := columns
|
||||
if migration.table == "bindings" {
|
||||
switch migration.table {
|
||||
case "bindings":
|
||||
present = bindingColumns
|
||||
case "events":
|
||||
present = eventsColumns
|
||||
}
|
||||
if present[migration.column] {
|
||||
continue
|
||||
@@ -544,9 +557,14 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
|
||||
}
|
||||
|
||||
// OpenPRs returns tasks whose PR state should be reconciled with GitHub.
|
||||
//
|
||||
// It carries attempt deliberately: the reconcile loop attributes pr_merged and
|
||||
// pr_rejected to the attempt that opened the PR, and it reaches the state store
|
||||
// over the wire, so the row must carry the value for taskProto to publish it.
|
||||
// Narrowing this projection back silently sends those events out unattributed.
|
||||
func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, owner, repo, issue_number, pr_number, status, source, identity
|
||||
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt
|
||||
FROM tasks WHERE status=?`, workflow.StatusPROpen)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -557,7 +575,7 @@ func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr erro
|
||||
for rows.Next() {
|
||||
var t workflow.Task
|
||||
if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.PRNumber,
|
||||
&t.Status, &t.Source, &t.Identity); err != nil {
|
||||
&t.Status, &t.Source, &t.Identity, &t.Attempt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tasks = append(tasks, t)
|
||||
|
||||
@@ -111,6 +111,85 @@ func TestOpenMigratesUnversionedTaskSchemas(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenMigratesLegacyEventsAttemptColumn covers the highest-risk step in
|
||||
// attempt provenance: adding events.attempt to a database that predates it.
|
||||
// eventsSchema is CREATE TABLE IF NOT EXISTS, so against an existing
|
||||
// archie.db that statement is a no-op and the migrator arm is the ONLY thing
|
||||
// that adds the column. A test that opens a fresh tempdir passes whether or
|
||||
// not the arm exists, so the failure this pins is the one production would
|
||||
// hit: `table events has no column named attempt`.
|
||||
func TestOpenMigratesLegacyEventsAttemptColumn(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "legacy.db")
|
||||
raw, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = raw.ExecContext(t.Context(), `
|
||||
CREATE TABLE events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
task_id INTEGER NOT NULL DEFAULT 0,
|
||||
repo TEXT NOT NULL DEFAULT '',
|
||||
issue INTEGER NOT NULL DEFAULT 0,
|
||||
workflow TEXT NOT NULL DEFAULT '',
|
||||
stage TEXT NOT NULL DEFAULT '',
|
||||
detail TEXT NOT NULL DEFAULT '',
|
||||
data TEXT NOT NULL DEFAULT '{}'
|
||||
);
|
||||
INSERT INTO events (at, kind, task_id, stage, detail)
|
||||
VALUES ('2026-01-01T00:00:00Z', 'stage_start', 7, 'prepare', 'pre-existing row');
|
||||
PRAGMA user_version = 3`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := raw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s, err := Open(t.Context(), path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
// The row written before the column existed survives and reads as
|
||||
// unattributed -- zero is not a first attempt.
|
||||
legacy, err := s.TaskEvents(t.Context(), 7)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents after legacy migration: %v", err)
|
||||
}
|
||||
if len(legacy) != 1 || legacy[0].Detail != "pre-existing row" {
|
||||
t.Fatalf("legacy events = %+v, want the preserved row", legacy)
|
||||
}
|
||||
if legacy[0].Attempt != 0 {
|
||||
t.Errorf("legacy event attempt = %d, want 0 (unattributed)", legacy[0].Attempt)
|
||||
}
|
||||
|
||||
// Writing the new column is what actually fails in production when the
|
||||
// migrator arm is missing.
|
||||
if _, err := s.InsertEvent(t.Context(), events.Event{
|
||||
Kind: "stage_finish", TaskID: 7, Stage: "prepare", Attempt: 2,
|
||||
Data: map[string]any{"duration_ms": 1200},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEvent with attempt after legacy migration: %v", err)
|
||||
}
|
||||
|
||||
timeline, err := s.TaskEvents(t.Context(), 7)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents after insert: %v", err)
|
||||
}
|
||||
if len(timeline) != 2 {
|
||||
t.Fatalf("TaskEvents = %d events, want 2", len(timeline))
|
||||
}
|
||||
if got := timeline[1].Attempt; got != 2 {
|
||||
t.Errorf("attempt round-trip after legacy migration = %d, want 2", got)
|
||||
}
|
||||
if got := timeline[0].Attempt; got != 0 {
|
||||
t.Errorf("legacy row attempt changed to %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenRejectsNewerSchemaVersion(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "tasks.db")
|
||||
db, err := sql.Open("sqlite", path)
|
||||
@@ -526,12 +605,12 @@ func TestEventLogRoundTrip(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
id1, err := s.InsertEvent(ctx, events.Event{Kind: "stage_start", TaskID: 1, Stage: "plan"})
|
||||
id1, err := s.InsertEvent(ctx, events.Event{Kind: "stage_start", TaskID: 1, Stage: "plan", Attempt: 1})
|
||||
if err != nil || id1 == 0 {
|
||||
t.Fatalf("insert = (%d, %v)", id1, err)
|
||||
}
|
||||
id2, err := s.InsertEvent(ctx, events.Event{
|
||||
Kind: "stage_finish", TaskID: 1, Workflow: "implement", Stage: "plan",
|
||||
Kind: "stage_finish", TaskID: 1, Workflow: "implement", Stage: "plan", Attempt: 2,
|
||||
Data: map[string]any{"duration_ms": 1200},
|
||||
})
|
||||
if err != nil || id2 <= id1 {
|
||||
@@ -545,11 +624,18 @@ func TestEventLogRoundTrip(t *testing.T) {
|
||||
if evs[0].Data["duration_ms"] != float64(1200) {
|
||||
t.Fatalf("data round-trip = %v", evs[0].Data)
|
||||
}
|
||||
if evs[0].Attempt != 2 {
|
||||
t.Fatalf("EventsSince attempt round-trip = %d, want 2", evs[0].Attempt)
|
||||
}
|
||||
|
||||
timeline, err := s.TaskEvents(ctx, 1)
|
||||
if err != nil || len(timeline) != 2 {
|
||||
t.Fatalf("TaskEvents = (%d, %v)", len(timeline), err)
|
||||
}
|
||||
// Two attempts of one task must stay distinguishable in its timeline.
|
||||
if timeline[0].Attempt != 1 || timeline[1].Attempt != 2 {
|
||||
t.Fatalf("TaskEvents attempts = (%d, %d), want (1, 2)", timeline[0].Attempt, timeline[1].Attempt)
|
||||
}
|
||||
|
||||
stats, err := s.StageStats(ctx)
|
||||
if err != nil || len(stats) != 1 || stats[0].AvgMs != 1200 || stats[0].Stage != "plan" {
|
||||
|
||||
Reference in new issue
Block a user