From 2a2c78d2fbdb23b701abc4328706be570eb54944 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 22:43:06 +1300 Subject: [PATCH 1/3] Add retained review custody and compatibility qualification --- ...ission_binding_boundary_regression_test.go | 67 +++++++ .../reviewexec/finish_front_local_test.go | 23 +++ .../hosted_control_batch_regression_test.go | 165 ++++++++++++++++++ ...hosted_detached_preflight_snapshot_test.go | 63 +++++++ .../local_refusal_boundaries_test.go | 48 +++++ .../run_selection_claim_read_test.go | 105 +++++++++++ .../scheduling_ancestor_memo_test.go | 50 ++++++ .../scheduling_cooldown_history_test.go | 69 ++++++++ .../scheduling_paused_grant_basis_test.go | 31 ++++ .../scheduling_source_acceptance_test.go | 69 ++++++++ 10 files changed, 690 insertions(+) create mode 100644 internal/reviewexec/admission_binding_boundary_regression_test.go create mode 100644 internal/reviewexec/finish_front_local_test.go create mode 100644 internal/reviewexec/hosted_control_batch_regression_test.go create mode 100644 internal/reviewexec/hosted_detached_preflight_snapshot_test.go create mode 100644 internal/reviewexec/local_refusal_boundaries_test.go create mode 100644 internal/reviewexec/run_selection_claim_read_test.go create mode 100644 internal/reviewexec/scheduling_ancestor_memo_test.go create mode 100644 internal/reviewexec/scheduling_cooldown_history_test.go create mode 100644 internal/reviewexec/scheduling_paused_grant_basis_test.go create mode 100644 internal/reviewexec/scheduling_source_acceptance_test.go diff --git a/internal/reviewexec/admission_binding_boundary_regression_test.go b/internal/reviewexec/admission_binding_boundary_regression_test.go new file mode 100644 index 00000000..719317e6 --- /dev/null +++ b/internal/reviewexec/admission_binding_boundary_regression_test.go @@ -0,0 +1,67 @@ +package reviewexec + +import ( + "context" + "testing" +) + +func TestAdmitReleasesOnlyMalformedSelectionLink(t *testing.T) { + for _, outcome := range []string{"malformed-link", "proved-custody"} { + t.Run(outcome, func(t *testing.T) { + f := selectionFixtureWithQueue(t, []int64{2}) + r, _ := selectionEnqueue(t, f, "prepare-boundary", "hosted", nil) + selectionNext(t, f, &refreshTestReader{}) + id := selectionRead(t, f, r.ID).OperationID + if id == "" { + t.Fatal("fixture did not retain a selected child") + } + before := roundOperation(t, f, id) + var prep Attempt + driver := &controlledDriver{prepare: func(ctx context.Context, op Operation, _ Configuration, a Attempt) (Preparation, error) { + if op.ID != id { + t.Fatal("unrelated operation entered fixture", op.ID) + } + if _, err := f.e.ExecutionContext(ctx, op.ProjectID, op.ID); err != nil { + t.Fatal("expected valid preflight before controlled state change", err) + } + prep = a + if outcome == "malformed-link" { + admissionSQL(t, f, "UPDATE review_selections SET worker_id=? WHERE id=?", "different-fixture-worker", r.ID) + } else { + admissionSQL(t, f, "UPDATE review_selections SET state='held',reason='linked_selection_quarantined',operation_id=NULL,revision=3 WHERE id=?", r.ID) + admissionSQL(t, f, "INSERT INTO review_selection_quarantine (selection_id,project_id,original_operation_id,original_state,observed_revision) VALUES(?,?,?,'selecting',2)", r.ID, attemptProject, id) + if err := requireUnquarantinedSelectionLink(ctx, f.store.DB(), attemptProject, id); !isLinkedSelectionCustodyHeld(err) { + t.Fatal("fixture has no proved custody", err) + } + } + return Preparation{Anchor: attemptAnchor(op.ProjectID, op.PullNumber), Intent: "unposted-boundary-intent"}, nil + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal("local refusal became a worker-wide error", err) + } + after := roundOperation(t, f, id) + if prep.ID == "" || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || + after.ID != before.ID || after.HeadSHA != before.HeadSHA || after.ActorID != before.ActorID || + after.WorkerID != before.WorkerID || after.ConfigurationRevision != before.ConfigurationRevision { + t.Fatal("preparation changed original operation or dispatched", before, after) + } + expectedAttempt := "preparing" + expectedReservations := 1 + if outcome == "malformed-link" { + expectedAttempt, expectedReservations = "held", 0 + if after.State != "queued" || after.Reason != "automatic_scheduling_unavailable" || after.AttemptID != "" { + t.Fatal("malformed direct link did not release unused preparation", after) + } + } else if after.State != "preparing" || after.AttemptID != prep.ID { + t.Fatal("proved custody was treated as malformed direct link", after) + } + if n := attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations"); n != expectedReservations { + t.Fatal("unexpected reservation count", n, expectedReservations) + } + var state, intent, external string + if err := f.store.DB().QueryRow("SELECT state,intent,external_id FROM review_execution_attempts WHERE id=?", prep.ID).Scan(&state, &intent, &external); err != nil || state != expectedAttempt || intent != "" || external != "" { + t.Fatal("refusal recorded external state or unexpected attempt lifecycle", state, intent, external, err) + } + }) + } +} diff --git a/internal/reviewexec/finish_front_local_test.go b/internal/reviewexec/finish_front_local_test.go new file mode 100644 index 00000000..c366281d --- /dev/null +++ b/internal/reviewexec/finish_front_local_test.go @@ -0,0 +1,23 @@ +package reviewexec + +import ( + "errors" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +// The final recheck distinguishes a bounded local read refusal from a store +// failure without needing to alter any retained project data. +func TestFinishFrontLocalReadAttribution(t *testing.T) { + r := Run{ProjectID: "test-project"} + local := core.Fail("local_read_unavailable", "Local read unavailable.", 503) + var held *finishFrontLocalRefusal + if !errors.As(finishFrontReadError(r, local), &held) { + t.Fatal("bounded local read did not use the guarded hold path") + } + shared := errors.New("shared store failure") + if finishFrontReadError(r, shared) != shared { + t.Fatal("shared store failure must retain normal fatal handling") + } +} diff --git a/internal/reviewexec/hosted_control_batch_regression_test.go b/internal/reviewexec/hosted_control_batch_regression_test.go new file mode 100644 index 00000000..87031157 --- /dev/null +++ b/internal/reviewexec/hosted_control_batch_regression_test.go @@ -0,0 +1,165 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "testing" +) + +func TestHostedExplicitSelectionSkipsPausedQueuedNeighbor(t *testing.T) { + f := selectionFixture(t) + paused := f.enqueue(t, attemptProject, "paused-hosted-neighbor", "hosted", 2, 1) + schedulingPause(t, f, 2, 0, true) + independent := int64(4) + healthy, _ := selectionEnqueue(t, f, "explicit-independent-hosted", "hosted", &independent) + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, healthy.ID); got.State != "selected" || got.OperationID == "" { + t.Fatalf("explicit selection did not progress: %+v", got) + } + var state string + if err := f.store.DB().QueryRow(`SELECT state FROM review_operations WHERE id=?`, paused.ID).Scan(&state); err != nil || state != "queued" { + t.Fatalf("paused operation no longer queued: %q %v", state, err) + } +} + +func TestQueuedNativeSelectionWithUnprovedChildDoesNotStopIndependentSelection(t *testing.T) { + f := selectionFixture(t) + broken, _ := selectionEnqueue(t, f, "linked-native-selection", "hosted", nil) + healthy, _ := selectionEnqueue(t, f, "healthy-linked-native-neighbor", "cli", nil) + child := f.enqueue(t, attemptProject, "retained-native-hosted-child", "hosted", 4, 1) + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `PRAGMA ignore_check_constraints=ON`); err != nil { + return err + } + _, corruptErr := tx.ExecContext(ctx, `UPDATE review_selections + SET operation_id=?,created_at='2000-01-01T00:00:00Z' WHERE id=?`, child.ID, broken.ID) + _, resetErr := tx.ExecContext(ctx, `PRAGMA ignore_check_constraints=OFF`) + return errors.Join(corruptErr, resetErr) + }) + if err != nil { + t.Fatal(err) + } + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, healthy.ID); got.State != "selected" || got.OperationID == "" { + t.Fatalf("independent selection did not progress: %+v", got) + } + var state, linkedID string + if err := f.store.DB().QueryRowContext(t.Context(), `SELECT state,operation_id FROM review_selections WHERE id=?`, broken.ID).Scan(&state, &linkedID); err != nil || state != "queued" || linkedID != child.ID { + t.Fatalf("unproved custody was rewritten: %q %q %v", state, linkedID, err) + } +} + +func TestSourceRecoveryRefusesUnknownEventlessAcceptanceOrder(t *testing.T) { + for _, tc := range []struct { + name, createdAt string + keepEvent, want bool + }{ + {"eventless-earlier", "2001-01-01T00:00:00Z", false, false}, + {"eventless-unknown", "unknown", false, true}, + {"later-event-authoritative", "2001-01-01T00:00:00Z", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + f := selectionFixture(t) + base, _ := selectionEnqueue(t, f, "recovery-target", "hosted", nil) + neighbor := f.enqueue(t, attemptProject, "retained-intent", "hosted", 2, 1) + run := selectionRead(t, f, base.ID) + admissionSQL(t, f, `UPDATE review_operations SET created_at=? WHERE id=?`, tc.createdAt, neighbor.ID) + if !tc.keepEvent { + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.requested' AND resource_id=?`, neighbor.ID) + } + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + got, err := automaticSourceSuperseded(ctx, tx, run) + if err != nil || got != tc.want { + t.Fatalf("superseded: got %v want %v: %v", got, tc.want, err) + } + return err + }) + if err != nil { + t.Fatal(err) + } + }) + } +} + +func TestNativeCustodyRejectsConflictingLiveSelectionLink(t *testing.T) { + f := selectionFixture(t) + original, _ := selectionEnqueue(t, f, "original-with-child", "hosted", nil) + selectionNext(t, f, &refreshTestReader{}) + child := selectionRead(t, f, original.ID).OperationID + if child == "" { + t.Fatal("missing child") + } + admissionSQL(t, f, `UPDATE review_selections SET state='held',reason='linked_selection_quarantined',operation_id=NULL,revision=3 WHERE id=?`, original.ID) + admissionSQL(t, f, `INSERT INTO review_selection_quarantine (selection_id,project_id,original_operation_id,original_state,observed_revision) VALUES(?,?,?,'selecting',2)`, original.ID, attemptProject, child) + if err := requireUnquarantinedSelectionLink(t.Context(), f.store.DB(), attemptProject, child); !isLinkedSelectionCustodyHeld(err) { + t.Fatal("expected proved hold", err) + } + live, _ := selectionEnqueue(t, f, "different-live-selector", "hosted", nil) + admissionSQL(t, f, `UPDATE review_selections SET state='selected',operation_id=? WHERE id=?`, child, live.ID) + if err := requireUnquarantinedSelectionLink(t.Context(), f.store.DB(), attemptProject, child); err == nil || isLinkedSelectionCustodyHeld(err) { + t.Fatal("conflicting live attribution was considered proved", err) + } +} + +func TestSelectionSnapshotDistinguishesLegacyEventFromMissingPinnedEvent(t *testing.T) { + for _, tc := range []struct { + name string + pin *int64 + missing bool + }{ + {"legacy-real", nil, false}, + {"pin-missing", new(int64), true}, + } { + t.Run(tc.name, func(t *testing.T) { + f := selectionFixture(t) + if tc.pin != nil { + *tc.pin = 2 + } + r, _ := selectionEnqueue(t, f, "requested-event-control", "hosted", tc.pin) + if tc.missing { + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.selection_requested' AND resource_id=?`, r.ID) + } else { + admissionSQL(t, f, `UPDATE events SET payload_json='{"channel":"hosted"}' WHERE event_type='review.selection_requested' AND resource_id=?`, r.ID) + } + err := ValidateSelectionSnapshot(t.Context(), f.store.DB()) + if (err != nil) != tc.missing { + t.Fatalf("validate snapshot missing=%t: %v", tc.missing, err) + } + }) + } +} + +func TestContinuityValidatesCurrentBasisAndNativeProjectActor(t *testing.T) { + for _, tc := range []struct { + name, payload string + actor any + valid bool + }{ + {"legacy-hosted", `{"automatic_hosted":true}`, "test-actor", true}, + {"invalid-basis", `{"automatic_hosted":true,"hosted_basis_revision":"bad","cli_basis_revision":1}`, "test-actor", false}, + {"same-value-blob", `{"automatic_hosted":true}`, []byte("test-actor"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + _, err := tx.ExecContext(t.Context(), `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json) VALUES + ('test-project','test-project','review.scheduling_updated',1,'test-actor','{"automatic_hosted":true}'), + ('test-project','test-project','review.scheduling_updated',2,?,?)`, tc.actor, tc.payload) + if err != nil { + t.Fatal(err) + } + current := schedulingRecord{Scheduling: Scheduling{ProjectID: "test-project", Revision: 2, AutomaticHosted: true}, actor: "test-actor"} + ok, err := automaticChannelContinuous(t.Context(), tx, Run{ProjectID: "test-project", Channel: "hosted", State: "selected", OperationID: "review_operation_legacy"}, 1, "test-actor", current) + if ok != tc.valid || tc.valid != (err == nil) { + t.Fatalf("continuity: got %v %v; expected valid=%v", ok, err, tc.valid) + } + if tc.name == "legacy-hosted" { + queued := Run{ProjectID: "test-project", Channel: "hosted", State: "queued"} + allowed, err := automaticChannelContinuous(t.Context(), tx, queued, 1, "test-actor", current) + if allowed || err != nil { + t.Fatalf("unselected legacy history must not grant continuity: %v %v", allowed, err) + } + } + }) + } +} diff --git a/internal/reviewexec/hosted_detached_preflight_snapshot_test.go b/internal/reviewexec/hosted_detached_preflight_snapshot_test.go new file mode 100644 index 00000000..8ca6a54d --- /dev/null +++ b/internal/reviewexec/hosted_detached_preflight_snapshot_test.go @@ -0,0 +1,63 @@ +package reviewexec + +import ( + "testing" +) + +func TestHostedSnapshotRetainsUnusedSchedulingPreflight(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_scheduling_unavailable"} { + t.Run(reason, func(t *testing.T) { + f, first, _, input := hostedAllowanceFixture(t) + if err := f.e.RecordHostedAllowance(t.Context(), attemptProject, first.ID, first.Revision, input); err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(t.Context(), attemptProject, first.ID, first.Revision, "held", reason, ""); err != nil { + t.Fatal(err) + } + check := func() { + t.Helper() + tables := []string{"review_hosted_preflight", "review_hosted_allowance_queries", "review_operations", "review_operation_waits"} + before := make([]string, len(tables)) + for i, table := range tables { + before[i] = snapshotTable(t, f, table) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if err := ValidateAllowanceSnapshot(t.Context(), tx, 10); err != nil { + t.Fatalf("valid detached Hosted preflight refused: %v", err) + } + if err := ValidateOperationWaitsSnapshot(t.Context(), tx); err != nil { + t.Fatalf("valid detached Hosted preflight wait history refused: %v", err) + } + for i, table := range tables { + if after := snapshotTableThrough(t, tx, table); before[i] != after { + t.Fatalf("snapshot wrote to %s inside inspection", table) + } + } + } + check() + next := f.start(t, attemptProject, Receipt{ID: first.OperationID}) + if next.ID == "" || next.ID == first.ID { + t.Fatal("new attempt not independently attached", next) + } + check() + o, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, first.OperationID) + if err != nil { + t.Fatal(err) + } + if o.AttemptID != next.ID { + t.Fatal("snapshot rebound the current operation", o.AttemptID) + } + detached, err := readAttempt(t.Context(), f.store.DB(), attemptProject, first.ID) + if err != nil { + t.Fatal(err) + } + if _, err := readHostedAllowanceRecord(t.Context(), f.store.DB(), o, detached); err == nil { + t.Fatal("live allowance lookup accepted detached scheduling history") + } + }) + } +} diff --git a/internal/reviewexec/local_refusal_boundaries_test.go b/internal/reviewexec/local_refusal_boundaries_test.go new file mode 100644 index 00000000..3ca2cada --- /dev/null +++ b/internal/reviewexec/local_refusal_boundaries_test.go @@ -0,0 +1,48 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func TestAutomaticAdoptionCountRetainsLocalRepositoryRefusal(t *testing.T) { + f := selectionFixture(t) + retainObligationSource(t, f, attemptProject, "local-refusal-importer", "local-refusal-source", strings.Repeat("c", 64), 0) + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if count, err := sourceObligationCount(ctx, tx, attemptProject, 2); count != 1 || err != nil { + t.Fatalf("valid retained source count=%d err=%v", count, err) + } + repositoryChanged := core.Fail("repository_changed", "Synthetic retained source bound to a different repository.", 409) + for _, tt := range []struct { + failure error + local bool + }{ + {repositoryChanged, true}, + {errors.New("synthetic shared SQL failure"), false}, + {context.Canceled, false}, + {context.DeadlineExceeded, false}, + } { + count, err := sourceObligationCount(ctx, admissionObligationFailure{Tx: tx, failure: tt.failure}, attemptProject, 2) + if count != 0 || err == nil || automaticProjectRefused(err) != tt.local || isSourceObligationProjectStateError(err) { + t.Errorf("automatic read count=%d local=%t ordinary-admission marker=%t err=%v", count, automaticProjectRefused(err), isSourceObligationProjectStateError(err), err) + } + if tt.local { + attemptCode(t, err, "review_held") + attemptCode(t, sourceObligationReadError(tt.failure), "review_held") + if preparationReason(err) != "repository_changed" || automaticProjectRefused(sourceObligationReadError(tt.failure)) { + t.Errorf("public reason/ordinary admission changed: %v", err) + } + } else if !errors.Is(err, tt.failure) { + t.Errorf("shared error lost: got %v want %v", err, tt.failure) + } + } + return nil + }); err != nil { + t.Fatal(err) + } +} diff --git a/internal/reviewexec/run_selection_claim_read_test.go b/internal/reviewexec/run_selection_claim_read_test.go new file mode 100644 index 00000000..11df2262 --- /dev/null +++ b/internal/reviewexec/run_selection_claim_read_test.go @@ -0,0 +1,105 @@ +package reviewexec + +import ( + "context" + "testing" + "time" +) + +func TestRunSelectionClaimedExplicitReadContention(t *testing.T) { + for _, tc := range []struct { + name, state, reason string + calls, children int + }{ + {name: "brief", state: "selected", calls: 3, children: 1}, + {name: "exhausted", state: "held", reason: "local_read_unavailable"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := selectionFixture(t) + receipt, _ := selectionEnqueue(t, f, "post-claim-reader", "cli", nil) + r := &refreshTestReader{} + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + defer cancel() + + // Pause at the existing post-commit notification, not at the + // provider callback (which would exercise the later prefix read). + f.e.operationMu.Lock() + unlocked := false + defer func() { + if !unlocked { + f.e.operationMu.Unlock() + } + }() + type result struct { + worked bool + err error + } + done := make(chan result, 1) + go func() { + worked, err := f.e.runNext(ctx, map[string]TargetReader{"test-capability": r}) + done <- result{worked, err} + }() + claimDeadline := time.Now().Add(4 * time.Second) + for { + var state string + var revision int64 + err := f.store.DB().QueryRowContext(ctx, "SELECT state,revision FROM review_selections WHERE id=?", receipt.ID).Scan(&state, &revision) + if err != nil { + t.Fatal(err) + } + if state == "selecting" && revision == 2 { + break + } + if time.Now().After(claimDeadline) { + t.Fatal("selection claim did not commit", state, revision) + } + time.Sleep(5 * time.Millisecond) + } + db := f.store.DB() + db.SetMaxOpenConns(1) + conn, err := db.Conn(ctx) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + waitCount := db.Stats().WaitCount + f.e.operationMu.Unlock() + unlocked = true + + if tc.name == "brief" { + // A second wait proves the first bounded admission expired. + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(5 * time.Millisecond) + defer tick.Stop() + for db.Stats().WaitCount < waitCount+2 { + select { + case result := <-done: + t.Fatalf("claimed selection stopped instead of retrying: %+v", result) + case <-deadline.C: + t.Fatal("no second read admission after expiry") + case <-tick.C: + } + } + if r.calls.Load() != 0 { + t.Fatal("provider called before local admission") + } + conn.Close() + } + select { + case result := <-done: + if result.err != nil || !result.worked { + t.Fatalf("claimed selection did not finish locally: %+v", result) + } + case <-ctx.Done(): + t.Fatal("claimed selection did not finish", ctx.Err()) + } + conn.Close() + got := selectionContentionRead(t, f, receipt.ID) + if got.State != tc.state || got.Reason != tc.reason || got.Revision != 3 || + int(r.calls.Load()) != tc.calls || attemptCount(t, f.store, "SELECT count(*) FROM review_operations") != tc.children { + t.Fatal("unexpected state or duplicate work", got, r.calls.Load()) + } + }) + } +} diff --git a/internal/reviewexec/scheduling_ancestor_memo_test.go b/internal/reviewexec/scheduling_ancestor_memo_test.go new file mode 100644 index 00000000..02d58f01 --- /dev/null +++ b/internal/reviewexec/scheduling_ancestor_memo_test.go @@ -0,0 +1,50 @@ +package reviewexec + +import ( + "context" + "database/sql" + "fmt" + "testing" +) + +func TestAutomaticDependenciesReuseSharedAncestorWithinSnapshot(t *testing.T) { + f := schedulingFixture(t) + frame := frontFrame{repository: 1, prefix: []frontPull{{Number: 2, HeadSHA: "parent"}, {Number: 4, HeadSHA: "intermediate", ParentPullNumber: 2}}} + for pull := int64(10); pull < 60; pull++ { + parent := int64(2) + if pull%2 == 0 { + parent = 4 + } + frame.prefix = append(frame.prefix, frontPull{Number: pull, ParentPullNumber: parent}) + } + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + memo := make(map[int64][]any) + index := frontPullIndex(frame) + reads := 0 + for pull := int64(10); pull < 60; pull++ { + direct, err := automaticDependenciesWithFrame(ctx, tx, attemptProject, pull, "hosted", frame, true, nil, nil) + if err != nil { + return err + } + cached, err := automaticDependenciesWithAncestorRead(pull, frame, true, index, memo, func(p frontPull) ([]any, error) { + reads++ + return readAutomaticAncestorFacts(ctx, tx, attemptProject, "hosted", frame.repository, p) + }) + if err != nil { + return err + } + if encoded(direct) != encoded(cached) { + return fmt.Errorf("pull %d: planning facts changed: direct %v, memo %v", pull, direct, cached) + } + } + if reads != 2 { + return fmt.Errorf("evaluated %d ancestors, want exactly two across all siblings", reads) + } + if len(memo) != 2 { + return fmt.Errorf("memo has %d entries, want exactly two shared ancestors", len(memo)) + } + return nil + }); err != nil { + t.Fatal(err) + } +} diff --git a/internal/reviewexec/scheduling_cooldown_history_test.go b/internal/reviewexec/scheduling_cooldown_history_test.go new file mode 100644 index 00000000..007c6910 --- /dev/null +++ b/internal/reviewexec/scheduling_cooldown_history_test.go @@ -0,0 +1,69 @@ +package reviewexec + +import ( + "reflect" + "testing" +) + +func TestSchedulingHoldKeepsCooldownHistoryStrict(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_scheduling_unavailable"} { + for _, damage := range []string{"none", "first-reason", "missing-first", "extra-transition", "intent", "reservation", "evidence"} { + t.Run(channel+"/"+reason+"/"+damage, func(t *testing.T) { + f, original, now := deadlineRuntimeFixture(t, channel) + before := cliWaitRead(t, f, original.OperationID) + *now = cliWaitDue(t, before) + retry := f.start(t, attemptProject, Receipt{ID: original.OperationID}) + if _, err := f.e.Advance(t.Context(), attemptProject, retry.ID, retry.Revision, "held", reason, ""); err != nil { + t.Fatal(err) + } + after := cliWaitRead(t, f, original.OperationID) + if after.State != "queued" || after.AttemptID != "" || !reflect.DeepEqual(before.Wait, after.Wait) { + t.Fatal("lost original timer", after) + } + switch damage { + case "first-reason": + admissionSQL(t, f, `UPDATE review_execution_transitions SET reason='not-preparing' WHERE attempt_id=? AND revision=1`, retry.ID) + case "missing-first": + admissionSQL(t, f, `DELETE FROM review_execution_transitions WHERE attempt_id=? AND revision=1`, retry.ID) + case "extra-transition": + admissionSQL(t, f, `INSERT INTO review_execution_transitions SELECT attempt_id,3,state,reason,external_id,created_at FROM review_execution_transitions WHERE attempt_id=? AND revision=2`, retry.ID) + case "intent": + admissionSQL(t, f, `UPDATE review_execution_attempts SET intent='issued' WHERE id=?`, retry.ID) + case "reservation": + admissionSQL(t, f, `INSERT INTO review_execution_reservations VALUES(?,901,2,?,?,?)`, retry.Provider, channel, retry.Account, retry.ID) + case "evidence": + admissionSQL(t, f, `INSERT INTO review_execution_evidence VALUES('bad-evidence',?,?,?,'{}','bad')`, attemptProject, retry.ID, after.ID) + } + state := deadlineRuntimeState(t, f) + wait, err := readOperationWait(t.Context(), f.store.DB(), after) + if damage == "none" { + if err != nil || !reflect.DeepEqual(wait, before.Wait) { + t.Fatal("valid history refused", wait, err) + } + } else if err == nil || wait != nil { + t.Fatal("runtime accepted corruption", wait, err) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + err = ValidateOperationWaitsSnapshot(t.Context(), tx) + if state != deadlineRuntimeStateThrough(t, tx) { + t.Fatal("validation wrote inside the retained-history transaction") + } + if rollbackErr := tx.Rollback(); rollbackErr != nil { + t.Fatal(rollbackErr) + } + if (err == nil) != (damage == "none") { + t.Fatal("snapshot history classification", err) + } + if state != deadlineRuntimeState(t, f) { + t.Fatal("validation mutated retained history") + } + }) + } + } + } +} diff --git a/internal/reviewexec/scheduling_paused_grant_basis_test.go b/internal/reviewexec/scheduling_paused_grant_basis_test.go new file mode 100644 index 00000000..759b1c3d --- /dev/null +++ b/internal/reviewexec/scheduling_paused_grant_basis_test.go @@ -0,0 +1,31 @@ +package reviewexec + +import ( + "context" + "database/sql" + "slices" + "testing" +) + +func TestAutomaticGrantBasisOmitsPausedPullAndIncludesItAfterResume(t *testing.T) { + f := schedulingFixture(t) + roundGrant(t, f, 2, "hosted", 0, 1, 2, "paused-basis-grant") + roundGrant(t, f, 4, "hosted", 0, 1, 2, "neighbor-basis-grant") + schedulingPause(t, f, 2, 0, true) + check := func(want []int64) { + t.Helper() + err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + got, err := readAutomaticGrantRevisions(ctx, tx, attemptProject, "hosted", []int64{2, 4}) + if err == nil && !slices.Equal(got, want) { + t.Errorf("grant revisions = %v, want %v", got, want) + } + return err + }) + if err != nil { + t.Fatal(err) + } + } + check([]int64{-2, 1}) + schedulingPause(t, f, 2, 1, false) + check([]int64{1, 1}) +} diff --git a/internal/reviewexec/scheduling_source_acceptance_test.go b/internal/reviewexec/scheduling_source_acceptance_test.go new file mode 100644 index 00000000..e2fb445c --- /dev/null +++ b/internal/reviewexec/scheduling_source_acceptance_test.go @@ -0,0 +1,69 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" + "time" +) + +func TestInitialAutomaticSourceAcceptanceRequiresCanonicalEvidence(t *testing.T) { + f := selectionFixture(t) + accepted, _ := selectionEnqueue(t, f, "acceptance-contract-fixture", "hosted", nil) + selection := selectionRead(t, f, accepted.ID) + var missing Run = selection + missing.ID = "no-retained-acceptance" + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + check := func(r Run, expected bool, expectError bool) { + t.Helper() + got, err := verifiedInitialAutomaticSourceAcceptance(ctx, tx, r) + if got != expected || (err != nil) != expectError { + t.Fatalf("canonical automatic acceptance = %v (%v), want %v (error=%v)", got, err, expected, expectError) + } + } + check(missing, false, false) + check(selection, false, false) // An explicit receipt is not an automatic grant. + automatic := encoded(selectionRequestedEvent{Channel: selection.Channel, Origin: selectionOriginAutomatic, WorkerID: selection.WorkerID}) + if _, err := tx.ExecContext(ctx, `UPDATE events SET payload_json=? WHERE project_id=? AND resource_id=? AND event_type='review.selection_requested' AND revision=1`, automatic, selection.ProjectID, selection.ID); err != nil { + return err + } + check(selection, true, false) + other := selection + other.WorkerID = "different-test-worker" + check(other, false, true) + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +// A valid restart's retained revision order follows journal append order. +func TestInitialAutomaticSourceAcceptsOrderedRestartJournal(t *testing.T) { + f := selectionFixture(t) + accepted, _ := selectionEnqueue(t, f, "restart-journal-order", "hosted", nil) + selection := selectionRead(t, f, accepted.ID) + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + for _, state := range []string{"selecting", "queued", "selecting"} { + run, err := readRun(ctx, tx, selection.ProjectID, accepted.ID) + if err != nil { + return err + } + if err := updateRunAt(ctx, tx, run, state, "", "", time.Now()); err != nil { + return err + } + } + run, err := readRun(ctx, tx, selection.ProjectID, accepted.ID) + if err != nil { + return err + } + valid, err := automaticSourceInitialRead(ctx, tx, run) + if !valid || err != nil { + t.Fatalf("classify canonical restart journal: got %v (%v), want true", valid, err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} From d34f42cab17628a1ea814b5540543aa0f1954a76 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 02:03:50 +1300 Subject: [PATCH 2/3] Qualify isolated unreadable planning without blocking healthy PRs --- .../scheduling_historical_basis_test.go | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/internal/reviewexec/scheduling_historical_basis_test.go b/internal/reviewexec/scheduling_historical_basis_test.go index b6ccb2f4..cf3c4ca4 100644 --- a/internal/reviewexec/scheduling_historical_basis_test.go +++ b/internal/reviewexec/scheduling_historical_basis_test.go @@ -95,9 +95,26 @@ func TestPausedPlanningBasisUsesDistinctIdentityOnlyForUnreadableLocalEvidence(t schedulingPause(t, f, 2, 1, false) err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { plan, eligible, err := automaticPlanningBasisForPrefix(ctx, tx, attemptProject, []int64{2, 4}, "", "hosted") + if err != nil || !eligible { + t.Fatalf("unreadable evidence on PR 2 blocked independent PR 4: %q %v %v", plan, eligible, err) + } + neighbor, err := automaticPullBasisChannel(ctx, tx, attemptProject, 4, "hosted") + if err != nil { + return err + } + input := []any{"planning_basis_degraded_paused_v1", []any{[]any{int64(2), nil, int64(2)}, []any{int64(4), neighbor}}, []int64{4}} + expected := sha256.Sum256([]byte(encoded(input))) + if plan != hex.EncodeToString(expected[:]) || plan == degradedBasis { + t.Fatalf("active unreadable row changed eligibility or lost its distinct control revision: %q", plan) + } + only, eligible, err := automaticPlanningBasisForPrefix(ctx, tx, attemptProject, []int64{2}, "", "hosted") + if err != nil || eligible || !hash.MatchString(only) { + t.Fatalf("active unreadable row received eligibility by itself: %q %v %v", only, eligible, err) + } + pull, err := automaticPullBasisChannel(ctx, tx, attemptProject, 2, "hosted") var unreadable *automaticPullAdjudicationUnavailable - if plan != "" || eligible || !errors.As(err, &unreadable) { - t.Fatalf("active unreadable row was not refused: %q %v %v", plan, eligible, err) + if pull != "" || !errors.As(err, &unreadable) { + t.Fatalf("active unreadable row received an exact per-pull basis: %q %v", pull, err) } return nil }) From 886f76cdf29fa4e4f42b16017b5ef80b303d9710 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 02:29:18 +1300 Subject: [PATCH 3/3] Accept redacted revocation during selection wait shutdown --- cmd/fcd/review_wait_deadline_test.go | 39 ++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/cmd/fcd/review_wait_deadline_test.go b/cmd/fcd/review_wait_deadline_test.go index a5ac7de2..860b2008 100644 --- a/cmd/fcd/review_wait_deadline_test.go +++ b/cmd/fcd/review_wait_deadline_test.go @@ -291,10 +291,45 @@ func TestHTTPShutdownDetachesSelectionWaitsAndKeepsAcceptedWork(t *testing.T) { case result := <-done: var accepted reviewexec.Receipt postAccepted := index == 0 && result.status == http.StatusAccepted && json.Unmarshal([]byte(result.body), &accepted) == nil && accepted.State == "queued" && accepted.Revision == 1 && strings.HasPrefix(accepted.ID, "review_selection_") && !strings.Contains(result.body, "outcome_unknown") + safeError := func(code string) bool { + var envelope, failure map[string]json.RawMessage + var gotCode string + if strings.Contains(result.body, "review_selection_") || + json.Unmarshal([]byte(result.body), &envelope) != nil || + json.Unmarshal(envelope["error"], &failure) != nil || + json.Unmarshal(failure["code"], &gotCode) != nil || gotCode != code { + return false + } + for field := range envelope { + if field != "error" && field != "request_id" { + return false + } + } + for field := range failure { + if field != "code" && field != "message" && field != "details" { + return false + } + } + if raw := failure["details"]; raw != nil { + var details map[string]json.RawMessage + if json.Unmarshal(raw, &details) != nil { + return false + } + for field := range details { + if field != "reason" && field != "outcome_unknown" { + return false + } + } + } + return true + } + unauthorized := revoked && result.status == http.StatusUnauthorized && safeError("unauthorized") if revoked && index == 0 { - postAccepted = result.status == http.StatusUnauthorized && accepted.ID == "" && !strings.Contains(result.body, "review_selection_") + postAccepted = unauthorized } - getCanceled := index == 1 && result.status == http.StatusServiceUnavailable && strings.Contains(result.body, `"code":"overloaded"`) && !strings.Contains(result.body, `"state":"completed"`) + // A read may observe revocation during authorization before + // it observes lifetime cancellation. Neither may expose state. + getCanceled := index == 1 && (unauthorized || result.status == http.StatusServiceUnavailable && safeError("overloaded")) if !postAccepted && !getCanceled { t.Fatal("accepted wait returned unsafe shutdown response", result.status, result.body) }