diff --git a/cmd/fcd/review_wait_deadline_test.go b/cmd/fcd/review_wait_deadline_test.go index a5ac7de21..860b20089 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) } diff --git a/internal/backup/operation_list_index_test.go b/internal/backup/operation_list_index_test.go index d2ca46b9d..abba28cb5 100644 --- a/internal/backup/operation_list_index_test.go +++ b/internal/backup/operation_list_index_test.go @@ -116,3 +116,53 @@ func TestDraftProbeIndexBackupRejectsMissingOrChangedSchema(t *testing.T) { }) } } + +func TestReviewEventResourceIndexMigrationPreservesOrdinaryJournal(t *testing.T) { + ctx := t.Context() + f := newRestoreFixture(t) + if _, err := f.store.DB().Exec(`DROP INDEX review_event_resource; + DELETE FROM metadata WHERE key='schema:review_event_indexes'`); err != nil { + t.Fatal(err) + } + const journal = `SELECT * FROM events ORDER BY sequence` + before := restoreRows(t, f.store.DB(), journal) + if len(before) == 0 { + t.Fatal("ordinary predecessor retained no journal") + } + old := restoreBundle(t, f) + if _, err := Inspect(ctx, old.Path); err != nil { + t.Fatal("valid predecessor no longer inspectable", err) + } + destination := filepath.Join(t.TempDir(), "inactive-predecessor") + if _, err := Restore(ctx, old.Path, destination); err != nil { + t.Fatal("valid predecessor no longer restorable", err) + } + db, err := openSnapshot(ctx, filepath.Join(destination, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if err := validateReviewEventResourceIndex(ctx, db, 0); err != nil || + !reflect.DeepEqual(before, restoreRows(t, db, journal)) { + t.Fatal("inactive restore migrated or changed predecessor journal", err) + } + for range 2 { + if err := reviewexec.EnsureSchema(ctx, f.store); err != nil { + t.Fatal("production migration failed", err) + } + } + var version string + if err := f.store.DB().QueryRow(`SELECT value FROM metadata WHERE key='schema:review_event_indexes'`).Scan(&version); err != nil || version != "1" { + t.Fatal("production event lookup migration version", version, err) + } + if err := validateReviewEventResourceIndex(ctx, f.store.DB(), 1); err != nil { + t.Fatal("production resource index differs from backup contract", err) + } + if !reflect.DeepEqual(before, restoreRows(t, f.store.DB(), journal)) { + t.Fatal("index migration rewrote ordinary journal") + } + newBundle := restoreBundle(t, f) + if _, err := Inspect(ctx, newBundle.Path); err != nil { + t.Fatal("migrated journal no longer inspectable", err) + } +} diff --git a/internal/backup/physical_schema_test.go b/internal/backup/physical_schema_test.go index c72d5cb55..07b72dd76 100644 --- a/internal/backup/physical_schema_test.go +++ b/internal/backup/physical_schema_test.go @@ -2,8 +2,12 @@ package backup import ( "database/sql" + "fmt" "path/filepath" + "strings" "testing" + + "github.com/benhook1013/FireController/internal/reviewexec" ) func TestDomainPhysicalSchemaExactInventory(t *testing.T) { @@ -48,6 +52,58 @@ func TestDomainPhysicalSchemaExactInventory(t *testing.T) { } } +func TestSchedulingPhysicalSchemaExactInventory(t *testing.T) { + for _, version := range []int{1, 2} { + t.Run(fmt.Sprintf("v%d", version), func(t *testing.T) { + canonical := reviewexec.SchedulingSchemaSQL() + if version == 2 { + canonical = reviewexec.SchedulingSchemaV2SQL() + } + for _, tc := range []struct { + name, mutation string + valid bool + }{ + {"canonical", "", true}, + {"unrelated objects", `CREATE TABLE unrelated (id INTEGER); CREATE INDEX unrelated_id ON unrelated(id);`, true}, + {"missing table", `DROP TABLE review_pull_scheduling;`, false}, + {"missing index", `DROP INDEX review_automatic_selections_pull;`, false}, + {"changed index", `DROP INDEX review_automatic_selections_pull; CREATE INDEX review_automatic_selections_pull ON review_automatic_selections(project_id);`, false}, + {"weakened table", `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'revision>0','revision>=0') WHERE name='review_scheduling'; PRAGMA writable_schema=OFF;`, false}, + {"extra index", `CREATE INDEX scheduling_extra ON review_scheduling(revision);`, false}, + {"oversized name", `CREATE INDEX ` + strings.Repeat("x", 129) + ` ON review_scheduling(revision);`, false}, + {"oversized definition", `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=sql||' /*` + strings.Repeat("x", 16384) + `*/' WHERE name='review_scheduling'; PRAGMA writable_schema=OFF;`, false}, + } { + t.Run(tc.name, func(t *testing.T) { + db, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "schema.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + for _, statement := range canonical { + if _, err := db.ExecContext(t.Context(), statement); err != nil { + t.Fatal(err) + } + } + if tc.mutation != "" { + if _, err := db.ExecContext(t.Context(), tc.mutation); err != nil { + t.Fatal(err) + } + } + err = validateSchedulingPhysicalSchema(t.Context(), db, version) + if tc.valid { + if err != nil { + t.Fatal("canonical scheduling schema rejected", err) + } + backupCode(t, validateSchedulingPhysicalSchema(t.Context(), db, 3-version), "backup_invalid") + } else { + backupCode(t, err, "backup_invalid") + } + }) + } + }) + } +} + func TestDomainPhysicalSchemaRejectsInvalidCanonicalInputs(t *testing.T) { const table = `CREATE TABLE owned (id INTEGER);` for _, tc := range []struct { diff --git a/internal/backup/review_fronts_test.go b/internal/backup/review_fronts_test.go index 7995e641b..e90af049d 100644 --- a/internal/backup/review_fronts_test.go +++ b/internal/backup/review_fronts_test.go @@ -94,3 +94,37 @@ func TestFrontInventoryRejectsEmptyTableWithoutPrimaryKey(t *testing.T) { mutateBundleSQL(t, bundle.Path, `DROP TABLE review_front_frames;`+ddl) assertCurrentSummaryInventoryRefused(t, bundle, false) } + +func TestSchedulingUpgradePreservesExistingFrontInventory(t *testing.T) { + f, _ := selectionInventoryFixture(t, "held") + db := f.store.DB() + if _, err := db.Exec(` + DROP TABLE review_automatic_selections; + DROP TABLE review_pull_scheduling; + DROP TABLE review_scheduling; + DROP TABLE review_selection_quarantine; + UPDATE metadata SET value='1' WHERE key='schema:review_selection'; + DELETE FROM metadata WHERE key='schema:review_scheduling'; + `); err != nil { + t.Fatal(err) + } + var frontCount int + if err := db.QueryRow(`SELECT count(*) FROM review_front_frames`).Scan(&frontCount); err != nil || frontCount != 1 { + t.Fatal("predecessor front inventory", frontCount, err) + } + before := backupRows(t, db) + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal("front-aware predecessor refused", err) + } + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + after := backupRows(t, db) + if before["review_front_frames"] != after["review_front_frames"] { + t.Fatal("scheduling upgrade changed the retained front") + } + if err := reviewexec.ValidateFrontSnapshot(t.Context(), db); err != nil { + t.Fatal(err) + } +} 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 000000000..719317e65 --- /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/cli_recorded_publish_settlement_test.go b/internal/reviewexec/cli_recorded_publish_settlement_test.go new file mode 100644 index 000000000..1b39901ff --- /dev/null +++ b/internal/reviewexec/cli_recorded_publish_settlement_test.go @@ -0,0 +1,50 @@ +package reviewexec + +import ( + "errors" + "testing" +) + +func TestRecordedCLIPublishHandoffSettlesExactPositivePreflight(t *testing.T) { + f, a, observation := cliAllowanceFixture(t) + claim := roundOperation(t, f, a.OperationID) + original := claim + original.State, original.AttemptID, original.Revision = "queued", "", claim.Revision-1 + if err := f.e.RecordCLIAllowance(t.Context(), a.ProjectID, a.ID, a.Revision, observation); err != nil { + t.Fatal(err) + } + retired := false + refusal := newStoredUnavailable(storedPolicyHistory, "Prior local publication was deferred.") + err := CLIRecordedPreflightHandoff(refusal, observation, func() bool { + retired = true + return true + }, nil) + var handoff *CLIPreparationHandoff + if !retired || !errors.As(err, &handoff) || handoff.positive == nil || handoff.source != nil { + t.Fatal("recorded positive permit did not enter its distinct local handoff") + } + if err := f.e.settleCLIPreparationHandoff(t.Context(), original, a, handoff); err != nil { + t.Fatal(err) + } + queued := roundOperation(t, f, a.OperationID) + if queued.ID != original.ID || queued.Revision != claim.Revision+1 || queued.State != "queued" || queued.AttemptID != "" { + t.Fatal("settlement did not retain the original queued request", queued) + } + held, err := readAttempt(t.Context(), f.store.DB(), a.ProjectID, a.ID) + if err != nil || held.State != "held" || held.Revision != a.Revision+1 { + t.Fatal("exact unused attempt was not held", held, err) + } + retained, err := readCLIAllowanceRecord(t.Context(), f.store.DB(), claim, held) + if err != nil || retained.Observation != observation { + t.Fatal("original positive preflight was lost", err) + } + var receipts int + if err := f.store.DB().QueryRow("SELECT count(*) FROM events WHERE project_id=? AND resource_id=? AND event_type=?", a.ProjectID, a.ID, recordedCLIPublishSettlementEvent).Scan(&receipts); err != nil || receipts != 1 { + t.Fatal("expected exact recorded positive settlement receipt", receipts, err) + } + if attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != 0 { + t.Fatal("exact unused reservation was not released") + } + assertCLIWaitSnapshot(t, f) + assertCLIWaitNoCredit(t, f) +} diff --git a/internal/reviewexec/finish_front_local_test.go b/internal/reviewexec/finish_front_local_test.go new file mode 100644 index 000000000..c366281d9 --- /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 000000000..870311578 --- /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 000000000..8ca6a54d9 --- /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/live_cli_preparation_settlement_test.go b/internal/reviewexec/live_cli_preparation_settlement_test.go new file mode 100644 index 000000000..5a0ec54ba --- /dev/null +++ b/internal/reviewexec/live_cli_preparation_settlement_test.go @@ -0,0 +1,206 @@ +package reviewexec + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestLiveCLIPreparationRefusalSettlesOriginalClaim(t *testing.T) { + for _, existingAllowance := range []bool{false, true} { + t.Run(map[bool]string{false: "before-usage", true: "existing-allowance"}[existingAllowance], func(t *testing.T) { + f := supervisorFixture(t) + request := f.enqueue(t, attemptProject, "live-preparation-refusal", "cli", 2, 1) + released := false + d := &controlledDriver{prepare: func(ctx context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + if existingAllowance { + in := CLIAllowanceObservation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber), ObservedAt: stamp(), Remaining: 2, Limit: 5, RollingWindowMS: 3600000, ChangedFiles: 2} + if err := f.e.RecordCLIAllowance(ctx, o.ProjectID, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + } + return Preparation{}, CLIRefusalBeforeUsage(newStoredUnavailable(storedRoundHistory, "Synthetic round history refusal."), func() { released = true }) + }} + drivers := map[string]Driver{"test-capability": d} + err := f.e.processNext(t.Context(), drivers) + op := roundOperation(t, f, request.ID) + reservations := attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) + if d.prepares.Load() != 1 || d.calls.Load() != 0 || released != !existingAllowance { + t.Fatal("preparation refusal caused additional preparation or dispatch") + } + if existingAllowance { + var recovery *PreparationRecoveryError + if !errors.As(err, &recovery) || op.State != "preparing" || op.AttemptID == "" || reservations != 1 { + t.Fatal("existing allowance lost custody", op, reservations, err) + } + return + } + if err != nil || op.State != "queued" || op.Reason != "automatic_scheduling_unavailable" || op.AttemptID != "" || reservations != 0 { + t.Fatal("unused preparation failed to release the original reservation", op, reservations, err) + } + d.prepare = func(_ context.Context, _ Operation, _ Configuration, _ Attempt) (Preparation, error) { + return Preparation{}, sourceHold("allowance_unavailable") + } + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + if op = roundOperation(t, f, request.ID); d.prepares.Load() != 2 || d.calls.Load() != 0 || op.State != "held" || op.Reason != "allowance_unavailable" { + t.Fatal("running supervisor did not resume the original request", op) + } + }) + } +} + +type liveCLIExhaustionSource struct { + record CLIExhaustionRecovery + found bool +} + +func (source liveCLIExhaustionSource) LoadCLIExhaustion(context.Context, string) (CLIExhaustionRecovery, bool, error) { + return source.record, source.found, nil +} + +func TestLiveCLIPreparationReplaysOnlyRetainedExactZero(t *testing.T) { + for _, found := range []bool{true, false} { + t.Run(map[bool]string{true: "retained-zero", false: "missing-capture"}[found], func(t *testing.T) { + f := supervisorFixture(t) + request := f.enqueue(t, attemptProject, "live-preparation-exhaustion", "cli", 2, 1) + var originalAttempt string + released := false + d := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + originalAttempt = a.ID + record := CLIExhaustionRecovery{ + Operation: roundOperation(t, f, o.ID), + Attempt: a, + Observation: CLIAllowanceObservation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber), ObservedAt: stamp(), Remaining: 0, Limit: 5, RollingWindowMS: 3600000, ChangedFiles: 2}, + } + return Preparation{}, RetainedCLIExhaustionHandoff(errors.New("synthetic journal write unavailable"), liveCLIExhaustionSource{record: record, found: found}, func() { released = true }) + }} + err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": d}) + op := roundOperation(t, f, request.ID) + journaled := attemptCount(t, f.store, `SELECT count(*) FROM review_cli_preflight`) + reserved := attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) + if d.prepares.Load() != 1 || d.calls.Load() != 0 || !released { + t.Fatal("local replay performed provider work") + } + if !found { + var recovery *PreparationRecoveryError + if !errors.As(err, &recovery) || op.State != "preparing" || op.AttemptID != originalAttempt || reserved != 1 || journaled != 0 { + t.Fatal("missing capture lost custody", op, reserved, journaled, err) + } + return + } + if err != nil || op.State != "queued" || op.AttemptID != "" || op.Wait == nil || op.Wait.BaselineAttemptID != originalAttempt || + !cliWaitDue(t, op).After(time.Now()) || reserved != 0 || journaled != 1 { + t.Fatal("exact zero did not preserve the original retry baseline and backoff", op, reserved, journaled, err) + } + }) + } +} + +func TestLiveCLIPreparationRetainedHandoffTransfersToSameEngineRecovery(t *testing.T) { + f := supervisorFixture(t) + request := f.enqueue(t, attemptProject, "retained-handoff-transfers", "cli", 2, 1) + var originalAttempt string + loads := 0 + released := false + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + originalAttempt = a.ID + record := CLIExhaustionRecovery{ + Operation: roundOperation(t, f, o.ID), + Attempt: a, + Observation: CLIAllowanceObservation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber), ObservedAt: stamp(), Remaining: 0, Limit: 5, RollingWindowMS: 3600000, ChangedFiles: 2}, + } + source := exhaustionRecoverySourceFunc(func(_ context.Context, id string) (CLIExhaustionRecovery, bool, error) { + loads++ + if id != a.ID { + t.Fatalf("recovery requested a different attempt: %s", id) + } + if loads == 1 { + return CLIExhaustionRecovery{}, false, errors.New("temporary local capture read failure") + } + if !released { + t.Fatal("startup replay did not receive ownership") + } + return record, true, nil + }) + f.e.cliExhaustionRecovery = source + return Preparation{}, RetainedCLIExhaustionHandoff(errors.New("temporary local journal failure"), source, func() { released = true }) + }} + drivers := map[string]Driver{"test-capability": driver} + var recoverable *PreparationRecoveryError + if err := f.e.processNext(t.Context(), drivers); !errors.As(err, &recoverable) || !released { + t.Fatal("transient settlement did not hand durable recovery off", err) + } + pending := roundOperation(t, f, request.ID) + if pending.State != "preparing" || pending.AttemptID != originalAttempt { + t.Fatal("failed local settlement changed the accepted attempt", pending) + } + skipped, err := f.e.reconcilePreparingDrivers(t.Context(), drivers) + if err != nil || len(skipped) != 0 { + t.Fatal("same engine startup could not recover durable handoff", skipped, err) + } + got := roundOperation(t, f, request.ID) + if loads != 2 || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || + got.State != "queued" || got.AttemptID != "" || got.Wait == nil || got.Wait.BaselineAttemptID != originalAttempt || + !cliWaitDue(t, got).After(time.Now()) { + t.Fatal("startup recovery did not settle the sole original attempt", got) + } +} + +func TestUnusedCLIPreparationConfirmsExactCommittedSettlement(t *testing.T) { + f := supervisorFixture(t) + request := f.enqueue(t, attemptProject, "confirm-exact-cli-settlement", "cli", 2, 1) + original := roundOperation(t, f, request.ID) + a, err := f.e.startAttempt(t.Context(), original.ProjectID, original.ID, 0, original.Revision) + if err != nil || a.ID == "" { + t.Fatal("unused preparation did not reserve its attempt", err) + } + proposed := a + proposed.State, proposed.Revision = "held", a.Revision+1 + if err := f.e.settleUnusedCLIPreparation(t.Context(), original, a); err != nil { + t.Fatal("ordinary no-usage settlement failed", err) + } + if !f.e.unusedCLISettlementCommitted(t.Context(), original, a, proposed) { + t.Fatal("exact committed settlement could not be confirmed") + } + queued := roundOperation(t, f, request.ID) + successor, err := f.e.startAttempt(t.Context(), queued.ProjectID, queued.ID, 0, queued.Revision) + if err != nil || successor.ID == "" || successor.ID == a.ID { + t.Fatal("ordinary queued work did not receive its own claim", err) + } + if !f.e.unusedCLISettlementCommitted(t.Context(), original, a, proposed) { + t.Fatal("exact committed settlement could not be confirmed after the next normal claim") + } + current := roundOperation(t, f, request.ID) + if current.State != "preparing" || current.AttemptID != successor.ID || current.Revision != queued.Revision+1 { + t.Fatal("read-only proof changed the successor claim", current) + } + var sequence int64 + if err := f.store.DB().QueryRow(`SELECT sequence FROM events WHERE project_id=? AND resource_id=? AND event_type=?`, original.ProjectID, a.ID, unusedCLISettlementEvent).Scan(&sequence); err != nil { + t.Fatal(err) + } + anchor := attemptAnchor(original.ProjectID, original.PullNumber) + input := CLIAllowanceObservation{Anchor: anchor, ObservedAt: stamp(), Remaining: 2, Limit: 5, RollingWindowMS: 3600000, ChangedFiles: 2} + if err := f.e.RecordCLIAllowance(t.Context(), original.ProjectID, successor.ID, successor.Revision, input); err != nil { + t.Fatal(err) + } + admitted, err := f.e.Admit(t.Context(), original.ProjectID, successor.ID, successor.Revision, anchor, "") + if err != nil || admitted.State != "active" { + t.Fatal("ordinary successor did not reach admission", err) + } + before := roundOperation(t, f, request.ID) + if !f.e.readUnusedCLISettlementReceipt(t.Context(), original, a, proposed, sequence) || + f.e.readUnusedCLISettlementReceipt(t.Context(), original, a, proposed, sequence+1) { + t.Fatal("receipt did not uniquely confirm the original settlement after the next admission") + } + ack := unusedCLISettlementAck{attempt: proposed, sequence: sequence} + if err := f.e.settleUnusedCLIPreparationWithAck(t.Context(), original, a, &ack); err != nil { + t.Fatal("settlement retry could not confirm the prior exact acknowledgement", err) + } + after := roundOperation(t, f, request.ID) + if after.State != before.State || after.AttemptID != before.AttemptID || after.Revision != before.Revision { + t.Fatal("acknowledgement changed successor", after) + } +} diff --git a/internal/reviewexec/local_refusal_boundaries_test.go b/internal/reviewexec/local_refusal_boundaries_test.go new file mode 100644 index 000000000..3ca2cadad --- /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/owned_cli_settlement_retry_test.go b/internal/reviewexec/owned_cli_settlement_retry_test.go new file mode 100644 index 000000000..ad6adb917 --- /dev/null +++ b/internal/reviewexec/owned_cli_settlement_retry_test.go @@ -0,0 +1,40 @@ +package reviewexec + +import ( + "context" + "errors" + "testing" +) + +func TestOwnedCLISettlementUsesSecondLocalWindowForTimeout(t *testing.T) { + calls := 0 + var original context.Context + if err := settleOwnedCLIWithinWindows(t.Context(), func(ctx context.Context) error { + calls++ + if calls == 1 { + original = ctx + return context.DeadlineExceeded + } + if ctx == original || original.Err() == nil || ctx.Err() != nil { + t.Fatal("settlement did not enter a separate live recovery window") + } + if _, ok := ctx.Deadline(); !ok { + t.Fatal("missing recovery deadline") + } + return nil + }); err != nil || calls != 2 { + t.Fatalf("settlement calls=%d error=%v", calls, err) + } +} + +func TestOwnedCLISettlementDoesNotRetryUnclassifiedFailure(t *testing.T) { + calls := 0 + failure := errors.New("unclassified local failure") + err := settleOwnedCLIWithinWindows(t.Context(), func(context.Context) error { + calls++ + return failure + }) + if err != failure || calls != 1 { + t.Fatalf("settlement calls=%d error=%v", calls, err) + } +} diff --git a/internal/reviewexec/preferred_cli_wait_integrity_test.go b/internal/reviewexec/preferred_cli_wait_integrity_test.go new file mode 100644 index 000000000..d70010659 --- /dev/null +++ b/internal/reviewexec/preferred_cli_wait_integrity_test.go @@ -0,0 +1,52 @@ +package reviewexec + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestOperationWaitPreservesOperationalErrors(t *testing.T) { + f := schedulingFixture(t) + r := f.enqueue(t, attemptProject, "wait-read", "cli", 2, 1) + o, err := readOperationIdentity(t.Context(), f.store.DB(), attemptProject, r.ID) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := readOperationWait(ctx, f.store.DB(), o); !errors.Is(err, context.Canceled) || isWaitUnavailable(err) { + t.Fatalf("cancellation lost its classification: %v", err) + } + admissionSQL(t, f, `ALTER TABLE review_operation_waits RENAME TO test_unavailable_waits`) + if _, err := readOperationWait(t.Context(), f.store.DB(), o); err == nil || isWaitUnavailable(err) { + t.Fatalf("missing table was not an operational failure: %v", err) + } +} + +func TestCLICooldownChecksDetachedPreparationJournal(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", cliDraftWait} { + t.Run(reason, func(t *testing.T) { + f, baseline, _, now := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, baseline.ID, baseline.Revision); err != nil { + t.Fatal(err) + } + wait := cliWaitRead(t, f, baseline.OperationID).Wait + *now = mustWaitTime(wait.RetryNotBefore).Add(time.Minute) + retry := f.start(t, attemptProject, Receipt{ID: baseline.OperationID}) + if _, err := f.e.Advance(t.Context(), attemptProject, retry.ID, retry.Revision, "held", reason, ""); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, baseline.OperationID); got.Wait == nil || got.Wait.BaselineAttemptID != baseline.ID || got.Wait.RetryNotBefore != wait.RetryNotBefore { + t.Fatalf("unused retry lost the original cooldown: %+v", got.Wait) + } + // Preserve the detached attempt and its final hold, but invalidate the + // exact first transition that should prove it was only a preparation. + admissionSQL(t, f, `UPDATE review_execution_transitions SET reason='not_preparing' WHERE attempt_id=? AND revision=1`, retry.ID) + if _, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, baseline.OperationID); !isWaitUnavailable(err) { + t.Fatalf("accepted detached hold with an invalid earlier transition: %v", 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 000000000..11df22624 --- /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_admission0030_test.go b/internal/reviewexec/scheduling_admission0030_test.go new file mode 100644 index 000000000..cc781210d --- /dev/null +++ b/internal/reviewexec/scheduling_admission0030_test.go @@ -0,0 +1,121 @@ +package reviewexec + +import ( + "context" + "reflect" + "testing" +) + +func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, change := range []string{"explicit-pause", "malformed-state"} { + t.Run(channel+"/"+change, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.e.publishAttempt = publishAttemptTransition + id := f.enqueue(t, attemptProject, "late-explicit-pause", channel, 2, 1).ID + before := roundOperation(t, f, id) + attribution := snapshotTable(t, f, "review_automatic_selections") + waits := snapshotTable(t, f, "review_operation_waits") + const reason = "pull_scheduling_paused" + var preparedAttempt Attempt + driver := &controlledDriver{prepare: func(ctx context.Context, op Operation, _ Configuration, a Attempt) (Preparation, error) { + if _, err := f.e.ExecutionContext(ctx, op.ProjectID, op.ID); err != nil { + t.Fatal("preparation did not begin with valid controls", err) + } + preparedAttempt = a + switch change { + case "explicit-pause": + schedulingPause(t, f, 2, 0, true) + case "malformed-state": + admissionSQL(t, f, `UPDATE review_execution_config SET body_json='{' WHERE project_id=?`, attemptProject) + } + intent := "" + if channel == "hosted" { + intent = "unposted-preparation-intent" + } + return Preparation{Anchor: attemptAnchor(op.ProjectID, op.PullNumber), Intent: intent}, nil + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal("late control refusal became a worker failure", err) + } + after := roundOperation(t, f, id) + if change == "malformed-state" { + // Damaged retained configuration is not a proven scheduling-only + // refusal: preserve the unused preparation for explicit recovery. + if after.State != "preparing" || after.AttemptID != preparedAttempt.ID || after.ActorID != before.ActorID || after.WorkerID != before.WorkerID || after.HeadSHA != before.HeadSHA || after.ConfigurationRevision != before.ConfigurationRevision || after.Channel != before.Channel || driver.prepares.Load() != 1 || driver.calls.Load() != 0 { + t.Fatal("damaged configuration discarded preparation or dispatched", before, after) + } + if attribution != snapshotTable(t, f, "review_automatic_selections") || waits != snapshotTable(t, f, "review_operation_waits") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 1 { + t.Fatal("damaged configuration changed retained work or reservation") + } + var state, anchor, intent, external string + if err := f.store.DB().QueryRow(`SELECT state,anchor_json,intent,external_id FROM review_execution_attempts WHERE id=?`, preparedAttempt.ID).Scan(&state, &anchor, &intent, &external); err != nil || state != "preparing" || anchor != "null" || intent != "" || external != "" { + t.Fatal("damaged configuration recorded dispatch intent", state, anchor, intent, external, err) + } + return + } + if after.State != "queued" || after.Reason != reason || after.AttemptID != "" || after.ActorID != before.ActorID || after.WorkerID != before.WorkerID || after.HeadSHA != before.HeadSHA || after.ConfigurationRevision != before.ConfigurationRevision || after.Channel != before.Channel || driver.prepares.Load() != 1 || driver.calls.Load() != 0 { + t.Fatal("late refusal lost the request or dispatched", before, after) + } + if attribution != snapshotTable(t, f, "review_automatic_selections") || waits != snapshotTable(t, f, "review_operation_waits") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("late refusal changed attribution/waits, duplicated work or stranded capacity") + } + var state, anchor, intent, external string + if err := f.store.DB().QueryRow(`SELECT state,anchor_json,intent,external_id FROM review_execution_attempts WHERE id=?`, preparedAttempt.ID).Scan(&state, &anchor, &intent, &external); err != nil || state != "held" || anchor != "null" || intent != "" || external != "" { + t.Fatal("unused attempt recorded dispatch intent", state, anchor, intent, external, err) + } + if change == "explicit-pause" { + schedulingPause(t, f, 2, 1, false) + driver.prepare = nil + driver.dispatch = func(ctx context.Context, op Operation, _ Attempt, record func(context.Context, string) error) (Result, error) { + external := "" + if op.Channel == "hosted" { + external = "synthetic_resume_trigger" + if err := record(ctx, external); err != nil { + return Result{}, err + } + } + return Result{State: "completed", Reason: "synthetic_capture", ExternalID: external}, nil + } + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil || driver.calls.Load() != 1 || roundOperation(t, f, id).State != "completed" { + t.Fatal("resume did not finish the same queued operation", err) + } + } + }) + } + } +} + +func TestSchedulingAdmitRefusalLeavesPreparationUntouched(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + op := f.enqueue(t, attemptProject, "direct-late-pause", "cli", 2, 1) + a := f.start(t, attemptProject, op) + schedulingPause(t, f, 2, 0, true) + before := roundTables(t, f) + _, err := f.e.Admit(t.Context(), attemptProject, a.ID, a.Revision, attemptAnchor(attemptProject, 2), "") + attemptCode(t, err, "pull_scheduling_paused") + if !reflect.DeepEqual(before, roundTables(t, f)) { + t.Fatal("refused admission changed preparing state before supervisor settlement") + } + if err := f.e.finishPreparation(a, "held", "pull_scheduling_paused"); err != nil { + t.Fatal(err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("refused preparation retained capacity") + } +} + +func TestSchedulingAdmissionDatabaseFailureStillStopsWithReservation(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + op := f.enqueue(t, attemptProject, "admission-storage-failure", "cli", 2, 1) + driver := &controlledDriver{prepare: func(ctx context.Context, op Operation, _ Configuration, _ Attempt) (Preparation, error) { + admissionSQL(t, f, `ALTER TABLE review_execution_config RENAME TO unavailable_execution_config`) + return Preparation{Anchor: attemptAnchor(op.ProjectID, op.PullNumber)}, nil + }} + err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}) + attemptCode(t, err, "review_persistence_failed") + after := roundOperation(t, f, op.ID) + if after.State != "preparing" || after.AttemptID == "" || driver.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 1 { + t.Fatal("database failure was suppressed as a project-local refusal", after) + } +} diff --git a/internal/reviewexec/scheduling_ancestor_memo_test.go b/internal/reviewexec/scheduling_ancestor_memo_test.go new file mode 100644 index 000000000..02d58f01d --- /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_basis_contract_test.go b/internal/reviewexec/scheduling_basis_contract_test.go new file mode 100644 index 000000000..edd02a312 --- /dev/null +++ b/internal/reviewexec/scheduling_basis_contract_test.go @@ -0,0 +1,46 @@ +package reviewexec + +import ( + "context" + "database/sql" + "reflect" + "testing" +) + +func TestPlanningSnapshotPinsOrdinaryPullPauseRevisions(t *testing.T) { + f := schedulingFixture(t) + read := func() []int64 { + t.Helper() + var got []int64 + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + got, err = readAutomaticPullSchedulingRevisions(ctx, tx, attemptProject, []int64{2, 4}, false) + return err + }) + if err != nil { + t.Fatal(err) + } + return got + } + before := read() + schedulingPause(t, f, 2, 0, true) + paused := read() + schedulingPause(t, f, 2, 1, false) + resumed := read() + for _, c := range []struct{ got, want []int64 }{{before, []int64{0, 0}}, {paused, []int64{1, 0}}, {resumed, []int64{2, 0}}} { + if !reflect.DeepEqual(c.got, c.want) { + t.Fatalf("snapshot pin = %v; want %v", c.got, c.want) + } + } +} + +func TestSchedulingEventPayloadPreservesLegacyAndNativeBasis(t *testing.T) { + legacy, hosted, cli, ok := readSchedulingEventPayload(sql.NullString{String: `{"automatic_hosted":true}`, Valid: true}, 3) + if !ok || legacy.Hosted == nil || !*legacy.Hosted || legacy.CLI != nil || hosted != 3 || cli != 3 { + t.Fatalf("legacy scheduling payload lost its basis: %v %d %d %t", legacy, hosted, cli, ok) + } + native, hosted, cli, ok := readSchedulingEventPayload(sql.NullString{String: `{"automatic_hosted":false,"automatic_cli":true,"hosted_basis_revision":2,"cli_basis_revision":3}`, Valid: true}, 3) + if !ok || native.Hosted == nil || *native.Hosted || native.CLI == nil || !*native.CLI || hosted != 2 || cli != 3 { + t.Fatalf("native payload lost its channel basis: %v %d %d %t", native, hosted, cli, ok) + } +} diff --git a/internal/reviewexec/scheduling_cooldown_history_test.go b/internal/reviewexec/scheduling_cooldown_history_test.go new file mode 100644 index 000000000..007c69106 --- /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_historical_basis_test.go b/internal/reviewexec/scheduling_historical_basis_test.go new file mode 100644 index 000000000..cf3c4ca47 --- /dev/null +++ b/internal/reviewexec/scheduling_historical_basis_test.go @@ -0,0 +1,124 @@ +package reviewexec + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "errors" + "testing" +) + +func TestSchedulingSnapshotDiscoversDetachedNativeHoldWithoutJournalRow(t *testing.T) { + f := schedulingFixture(t) + receipt := f.enqueue(t, attemptProject, "detached-local-scheduling", "cli", 2, 1) + attempt := f.start(t, attemptProject, receipt) + if _, err := f.e.Advance(t.Context(), attemptProject, attempt.ID, attempt.Revision, "held", "pull_scheduling_paused", ""); err != nil { + t.Fatal(err) + } + if waits := attemptCount(t, f.store, `SELECT count(*) FROM review_operation_waits WHERE operation_id=?`, receipt.ID); waits != 0 { + t.Fatalf("detached preparation unexpectedly has a wait row: %d", waits) + } + assertCLIWaitSnapshot(t, f) + admissionSQL(t, f, "DELETE FROM review_execution_transitions WHERE attempt_id=? AND revision=2", attempt.ID) + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return ValidateOperationWaitsSnapshot(ctx, tx) + }) + if err == nil { + t.Fatal("snapshot accepted unverifiable detached history") + } +} + +func TestPausedPlanningBasisUsesDistinctIdentityOnlyForUnreadableLocalEvidence(t *testing.T) { + f, _, evidence := adjudicationFixture(t, 1, false) + adjudicationDecide(t, f, evidence, "paused-basis-decision", 0, 0, "rejected") + admissionSQL(t, f, `INSERT INTO workers(project_id,id,name) VALUES(?,'selection-worker','Selector')`, attemptProject) + schedulingPause(t, f, 2, 0, true) + var fullBasis, fullPullBasis, degradedBasis string + read := func(opaque bool) { + t.Helper() + 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("independent pull unavailable: %v %v", eligible, err) + } + neighbor, err := automaticPullBasisChannel(ctx, tx, attemptProject, 4, "hosted") + if err != nil { + return err + } + paused, err := automaticPullBasisChannel(ctx, tx, attemptProject, 2, "hosted") + var input any + if opaque { + degradedBasis = plan + if err == nil || paused != "" { + t.Fatal("unreadable pull acquired a per-pull digest") + } + input = []any{"planning_basis_degraded_paused_v1", []any{[]any{int64(2), nil, int64(1)}, []any{int64(4), neighbor}}, []int64{4}} + } else { + fullBasis, fullPullBasis = plan, paused + if err != nil { + return err + } + input = []any{[]any{[]any{int64(2), paused}, []any{int64(4), neighbor}}, []int64{4}} + } + expected := sha256.Sum256([]byte(encoded(input))) + if plan != hex.EncodeToString(expected[:]) { + t.Fatalf("unexpected planning identity: %q", plan) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + read(false) + admissionSQL(t, f, `UPDATE review_execution_evidence SET body_json=json_set(body_json,'$.capture.review.Findings',json('{}')) WHERE id=?`, evidence) + read(true) + old, _ := selectionEnqueue(t, f, "full-only-held-intent", "hosted", nil) + admissionSQL(t, f, `UPDATE review_selections SET state='held',reason='source_unavailable',revision=3 WHERE id=?`, old.ID) + admissionSQL(t, f, `INSERT INTO review_automatic_selections(selection_id,project_id,scheduling_revision,basis_sha256,actor_id,worker_id,credential_id) + SELECT id,project_id,1,?,actor_id,worker_id,'test-credential' FROM review_selections WHERE id=?`, fullBasis, old.ID) + 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 || plan != degradedBasis || plan == fullBasis { + t.Fatalf("old unattributed hold reached fresh planning: %q %v %v", plan, eligible, err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + // Exact per-pull custody on the different, paused PR no longer + // makes the old lane intent ambiguous relative to ready PR 4. + admissionSQL(t, f, `UPDATE review_automatic_selections SET pull_number=2,pull_basis_sha256=? WHERE selection_id=?`, fullPullBasis, old.ID) + read(true) + 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 pull != "" || !errors.As(err, &unreadable) { + t.Fatalf("active unreadable row received an exact per-pull basis: %q %v", pull, err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/reviewexec/scheduling_pause_history_test.go b/internal/reviewexec/scheduling_pause_history_test.go new file mode 100644 index 000000000..3bac26acd --- /dev/null +++ b/internal/reviewexec/scheduling_pause_history_test.go @@ -0,0 +1,47 @@ +package reviewexec + +import "testing" + +func TestSchedulingSnapshotRetainsPauseAuthority(t *testing.T) { + for _, corrupt := range []string{"", "unpaused-row", "missing-event", "duplicate-event", "malformed-event", "blob-event", "blob-actor", "wrong-pull", "wrong-actor", "newer-event"} { + t.Run(corrupt, func(t *testing.T) { + f := schedulingFixture(t) + schedulingPause(t, f, 2, 0, true) + switch corrupt { + case "unpaused-row": + admissionSQL(t, f, `UPDATE review_pull_scheduling SET paused=0,reason='' WHERE pull_number=2`) + case "missing-event": + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.pull_scheduling_updated'`) + case "duplicate-event": + admissionSQL(t, f, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) SELECT project_id,event_type,resource_id,revision,actor_id,payload_json,created_at FROM events WHERE event_type='review.pull_scheduling_updated'`) + case "malformed-event": + admissionSQL(t, f, `UPDATE events SET payload_json='{}' WHERE event_type='review.pull_scheduling_updated'`) + case "blob-event": + admissionSQL(t, f, `UPDATE events SET payload_json=CAST(payload_json AS BLOB) WHERE event_type='review.pull_scheduling_updated'`) + case "blob-actor": + admissionSQL(t, f, `UPDATE events SET actor_id=CAST(actor_id AS BLOB) WHERE event_type='review.pull_scheduling_updated'`) + case "wrong-pull": + admissionSQL(t, f, `UPDATE events SET payload_json='{"pull_number":4,"paused":true}' WHERE event_type='review.pull_scheduling_updated'`) + case "wrong-actor": + admissionSQL(t, f, `UPDATE events SET actor_id='exec-reader-principal' WHERE event_type='review.pull_scheduling_updated'`) + case "newer-event": + admissionSQL(t, f, `UPDATE events SET revision=2 WHERE event_type='review.pull_scheduling_updated'`) + } + err := validateSchedulingSnapshotForTest(t, f) + if corrupt != "" { + attemptCode(t, err, "storage_unavailable") + } else if err != nil { + t.Fatal(err) + } + }) + } +} + +func TestSchedulingSnapshotAcceptsPauseThenResumeHistory(t *testing.T) { + f := schedulingFixture(t) + schedulingPause(t, f, 2, 0, true) + schedulingPause(t, f, 2, 1, false) + if err := validateSchedulingSnapshotForTest(t, f); err != nil { + t.Fatal(err) + } +} 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 000000000..759b1c3de --- /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_quarantine0030_test.go b/internal/reviewexec/scheduling_quarantine0030_test.go new file mode 100644 index 000000000..430adb7f3 --- /dev/null +++ b/internal/reviewexec/scheduling_quarantine0030_test.go @@ -0,0 +1,109 @@ +package reviewexec + +import ( + "math" + "testing" +) + +// The choose/finish refusal paths pass the incremented in-memory run rather +// than the normalized SQL claim. Exercise that exact MaxInt64 boundary. +func TestRecovery0030QuarantinesInMemoryMaximumRevision(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + receipt, _ := selectionEnqueue(t, f, "max-claim", "hosted", nil) + r := selectionRead(t, f, receipt.ID) + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=? WHERE id=?`, int64(math.MaxInt64), r.ID) + r.State, r.Revision = "selecting", math.MaxInt64 + history := snapshotTable(t, f, "events") + attribution := snapshotTable(t, f, "review_automatic_selections") + waiter := &operationWaiter{changed: make(chan struct{}, 1)} + f.e.operationMu.Lock() + if f.e.operationWaiters == nil { + f.e.operationWaiters = map[string]map[*operationWaiter]struct{}{} + } + f.e.operationWaiters[r.ID] = map[*operationWaiter]struct{}{waiter: {}} + f.e.operationMu.Unlock() + worked, err := f.e.holdRunLocalRefusal(t.Context(), r) + if err != nil || !worked { + t.Fatal("in-memory max revision was not quarantined", worked, err) + } + got := selectionRead(t, f, r.ID) + if got.State != "held" || got.Reason != "local_read_unavailable" || got.Revision != math.MaxInt64 || got.OperationID != "" { + t.Fatal("quarantine rewrote retained evidence", got) + } + select { + case <-waiter.changed: + default: + t.Fatal("waiter not notified") + } + if worked, err = f.e.holdRunLocalRefusal(t.Context(), r); err != nil || worked { + t.Fatal("stale claim mutated quarantine", worked, err) + } + if history != snapshotTable(t, f, "events") || attribution != snapshotTable(t, f, "review_automatic_selections") { + t.Fatal("quarantine fabricated history or replaced authority") + } +} + +func TestRecovery0030MaximumRevisionQuarantinePreservesFailuresAndCAS(t *testing.T) { + for _, fault := range []string{"stale-revision", "write-failure"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + receipt, _ := selectionEnqueue(t, f, "max-claim-cas", "hosted", nil) + r := selectionRead(t, f, receipt.ID) + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=? WHERE id=?`, int64(math.MaxInt64), r.ID) + r.State, r.Revision = "selecting", math.MaxInt64 + if fault == "stale-revision" { + r.Revision-- + } else { + admissionSQL(t, f, `CREATE TRIGGER reject_quarantine0030 BEFORE UPDATE ON review_selections WHEN NEW.state='held' BEGIN SELECT RAISE(ABORT,'synthetic failure'); END`) + } + before := snapshotTable(t, f, "review_selections") + worked, err := f.e.holdRunLocalRefusal(t.Context(), r) + if worked || (err != nil) != (fault == "write-failure") { + t.Fatal("lost failure or compare-and-swap", worked, err) + } + if before != snapshotTable(t, f, "review_selections") { + t.Fatal("failed quarantine changed row") + } + }) + } +} + +func TestRecovery0030DamagedPendingClaimIsIsolated(t *testing.T) { + for _, state := range []string{"queued", "selecting"} { + for _, fault := range []string{"revision-type", "maximum-revision", "fingerprint-blob"} { + t.Run(state+"/"+fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + receipt, _ := selectionEnqueue(t, f, "damaged-claim", "hosted", nil) + admissionSQL(t, f, `UPDATE review_selections SET state=? WHERE id=?`, state, receipt.ID) + switch fault { + case "revision-type": + admissionSQL(t, f, `UPDATE review_selections SET revision='broken' WHERE id=?`, receipt.ID) + case "maximum-revision": + admissionSQL(t, f, `UPDATE review_selections SET revision=? WHERE id=?`, int64(math.MaxInt64), receipt.ID) + case "fingerprint-blob": + admissionSQL(t, f, `UPDATE review_selections SET capability_fingerprint=CAST(capability_fingerprint AS BLOB) WHERE id=?`, receipt.ID) + } + reader := &refreshTestReader{} + var err error + if state == "selecting" { + err = f.e.RecoverReviewRuns(t.Context()) + } else { + _, err = f.e.runNext(t.Context(), map[string]TargetReader{"test-capability": reader}) + } + if err != nil { + t.Fatal("damaged pending selection stopped recovery", err) + } + var gotState, reason string + if err = f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=?`, receipt.ID).Scan(&gotState, &reason); err != nil { + t.Fatal(err) + } + if gotState != "held" || reason != "local_read_unavailable" || reader.calls.Load() != 0 { + t.Fatal("damaged selection was not isolated before source I/O", gotState, reason) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("damaged selection created child") + } + }) + } + } +} diff --git a/internal/reviewexec/scheduling_recovery_regression_test.go b/internal/reviewexec/scheduling_recovery_regression_test.go new file mode 100644 index 000000000..69e5112fe --- /dev/null +++ b/internal/reviewexec/scheduling_recovery_regression_test.go @@ -0,0 +1,292 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestSupervisorIsolatesPullSchedulingRefusals(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, fault := range []string{"pull", "pending-prefix"} { + t.Run(channel+"/"+fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4}) + f.configure(t, otherAttemptProject, "other-account", 0, false) + bad := f.enqueue(t, attemptProject, "bad", channel, 2, 1) + if fault == "pending-prefix" { + f.enqueue(t, attemptProject, "bad-later", channel, 4, 1) + } + admissionSQL(t, f, `INSERT INTO review_pull_scheduling VALUES(?,2,1,0,'invalid unpaused reason','actor',?)`, attemptProject, stamp()) + healthy := f.enqueue(t, otherAttemptProject, "healthy", channel, 2, 1) + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + if o.ID != healthy.ID { + t.Error("wrong candidate reached provider", o.ID) + } + return Preparation{}, sourceHold("synthetic_stop") + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver, "other-account": driver}); err != nil { + t.Fatal("local scheduling refusal stopped supervisor", err) + } + if driver.prepares.Load() != 1 || driver.calls.Load() != 0 { + t.Fatal("healthy candidate not reached", driver.prepares.Load()) + } + if got := cliWaitRead(t, f, bad.ID); got.State != "queued" || got.AttemptID != "" { + t.Fatal("corrupt candidate changed", got) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts WHERE project_id=?`, attemptProject) != 0 { + t.Fatal("corrupt project reserved attempt") + } + }) + } + } +} + +func TestSelectionLocalRefusalKeepsExplicitAttribution(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + receipt, _ := selectionEnqueue(t, f, "explicit-attribution", "hosted", nil) + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=2 WHERE id=?`, receipt.ID) + r := selectionRead(t, f, receipt.ID) + admissionSQL(t, f, `UPDATE review_execution_config SET body_json='not-json' WHERE project_id=?`, r.ProjectID) + before := snapshotTable(t, f, "review_selections") + frames := snapshotTable(t, f, "review_front_frames") + _, err := f.e.finishRunChoice(t.Context(), r, 801, nil, runChoice{state: "held", reason: "source_fetch_timeout", sourceReason: "source_fetch_timeout"}) + if !automaticProjectRefused(err) || before != snapshotTable(t, f, "review_selections") { + t.Fatal("explicit request became an automatic hold instead of preserving its error path", err) + } + if frames != snapshotTable(t, f, "review_front_frames") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("refusal retained source or child writes") + } +} + +func TestRetainedReadersPreserveSQLFailures(t *testing.T) { + for _, table := range []string{"review_policy_config", "review_comparison_proofs", "review_round_controls", "review_route_policy_invalidations", "review_adoption_obligations"} { + t.Run(table, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + admissionSQL(t, f, `ALTER TABLE `+table+` RENAME TO unavailable_retained_table`) + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + switch table { + case "review_policy_config": + _, err = readPolicy(ctx, tx, attemptProject) + case "review_comparison_proofs": + _, err = channelProgress(ctx, tx, attemptProject, 801, 4, "hosted") + case "review_round_controls": + _, err = readRoundRecord(ctx, tx, attemptProject, 4, "hosted") + case "review_route_policy_invalidations": + _, err = pendingIncomingRoutes(ctx, tx, attemptProject, 4) + case "review_adoption_obligations": + _, err = sourceObligationCount(ctx, tx, attemptProject, 4) + } + return err + }) + if err == nil || automaticProjectRefused(err) { + t.Fatal("SQL failure hidden as project-local refusal", err) + } + }) + } +} + +func assertIndependentSelectionProgress(t *testing.T, f *attemptFixture, channel string) { + t.Helper() + raw, err := f.e.EnqueueRun(t.Context(), selectionScope(t, f, otherAttemptProject, f.admin, "write"), "healthy", RunRequest{Channel: channel}) + if err != nil { + t.Fatal(err) + } + var healthy Receipt + if err = json.Unmarshal(raw, &healthy); err != nil { + t.Fatal(err) + } + reader := &refreshTestReader{pull: func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{Number: n, RepositoryID: 802, State: "open", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }} + if worked, err := f.e.runNext(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}, "other-account": reader}); err != nil || !worked { + t.Fatal("healthy project stopped", worked, err) + } + var state string + if err = f.store.DB().QueryRow(`SELECT state FROM review_selections WHERE id=?`, healthy.ID).Scan(&state); err != nil || state != "selected" { + t.Fatal("healthy project not selected", state, err) + } +} + +func TestSelectionWorkerIsolatesRetainedRefusalsAtEveryStage(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, stage := range []string{"claim", "choose", "finish"} { + t.Run(channel+"/explicit/"+stage, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "other-account", 0, false) + bad, _ := selectionEnqueue(t, f, "bad", channel, nil) + switch stage { + case "claim": + admissionSQL(t, f, `UPDATE review_policy_config SET body_json='not-json' WHERE project_id=?`, attemptProject) + case "choose": + admissionSQL(t, f, `INSERT INTO review_pull_scheduling VALUES(?,2,1,0,'invalid unpaused reason','actor',?)`, attemptProject, stamp()) + case "finish": + admissionSQL(t, f, `CREATE TRIGGER corrupt_selection_finish AFTER INSERT ON review_front_frames WHEN NEW.project_id='exec-project-one' BEGIN INSERT INTO review_pull_scheduling VALUES(NEW.project_id,2,1,0,'invalid unpaused reason','actor',NEW.checked_at); END`) + } + beforeFrames := snapshotTable(t, f, "review_front_frames") + worked, err := f.e.runNext(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err != nil || !worked { + t.Fatal("local failure stopped worker", worked, err) + } + got := selectionRead(t, f, bad.ID) + if got.State != "held" || got.Reason != "local_read_unavailable" || got.OperationID != "" { + t.Fatal("incorrect refusal attribution", got) + } + if beforeFrames != snapshotTable(t, f, "review_front_frames") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("partial source or child retained") + } + assertIndependentSelectionProgress(t, f, channel) + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + if got = selectionRead(t, f, bad.ID); got.State != "held" { + t.Fatal("restart reopened poison selection", got) + } + }) + } + } +} + +func TestSelectionWorkerLocalHoldPreservesPersistenceFailuresAndRaces(t *testing.T) { + for _, fault := range []string{"hold-write", "concurrent-transition", "canceled"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + receipt, _ := selectionEnqueue(t, f, "local-hold", "cli", nil) + r := selectionRead(t, f, receipt.ID) + switch fault { + case "hold-write": + admissionSQL(t, f, `CREATE TRIGGER fail_local_hold BEFORE UPDATE ON review_selections WHEN NEW.reason='local_read_unavailable' BEGIN SELECT RAISE(ABORT,'synthetic persistence failure'); END`) + case "concurrent-transition": + admissionSQL(t, f, `UPDATE review_selections SET state='held',reason='configuration_changed',revision=revision+1 WHERE id=?`, r.ID) + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if fault == "canceled" { + cancel() + } + before := snapshotTable(t, f, "review_selections") + worked, err := f.e.holdRunLocalRefusal(ctx, r) + if worked { + t.Fatal("failed or stale hold reported progress") + } + if fault == "concurrent-transition" { + if err != nil { + t.Fatal(err) + } + } else if err == nil || automaticProjectRefused(err) { + t.Fatal("real failure hidden", err) + } + if before != snapshotTable(t, f, "review_selections") { + t.Fatal("failed or stale hold changed selection") + } + }) + } +} + +func TestStartupIsolatesDamagedFrontCacheButSnapshotsRejectIt(t *testing.T) { + for _, fault := range []string{"json", "oversized", "timestamp", "type"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "other-account", 0, false) + admissionSQL(t, f, `INSERT INTO review_front_frames VALUES(?,'hosted',801,1,?,'',0,'','[]')`, attemptProject, stamp()) + switch fault { + case "json": + admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json='not-json'`) + case "oversized": + // Whitespace around an array is valid JSON. Exercise only + // the physical bound here: full snapshot validation also + // requires canonical JSON and would reject either padded row. + bounded := strings.Repeat(" ", maxFrontPrefixBytes-2) + "[]" + admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json=?`, bounded) + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return validateFrontPhysical(ctx, tx) }); err != nil { + t.Fatalf("physical front prefix at limit was refused: %v", err) + } + admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json=?`, " "+bounded) + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return validateFrontPhysical(ctx, tx) }); err == nil { + t.Fatal("physical front prefix exceeded its size limit") + } + case "timestamp": + admissionSQL(t, f, `UPDATE review_front_frames SET checked_at='not-time'`) + case "type": + admissionSQL(t, f, `UPDATE review_front_frames SET repository_id='bad'`) + } + before := snapshotTable(t, f, "review_front_frames") + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal("one cache row blocked startup", err) + } + if before != snapshotTable(t, f, "review_front_frames") { + t.Fatal("startup rewrote retained cache") + } + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return ValidateFrontSnapshot(ctx, tx) }) + if err == nil { + t.Fatal("backup validation accepted damaged cache") + } + assertIndependentSelectionProgress(t, f, "hosted") + }) + } +} + +func TestStartupStillRejectsSharedFrontSchemaDamage(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + admissionSQL(t, f, `CREATE INDEX unexpected_front_index ON review_front_frames(repository_id)`) + if err := EnsureFrontSchema(t.Context(), f.store); err == nil { + t.Fatal("shared physical schema damage accepted") + } +} + +func TestDamagedPendingSelectionQuarantinesWithoutStoppingOtherProjects(t *testing.T) { + for _, state := range []string{"queued", "selecting"} { + for _, fault := range []string{"time", "revision-type", "revision-limit", "fingerprint-type", "write-failure"} { + t.Run(state+"/"+fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "other-account", 0, false) + bad, _ := selectionEnqueue(t, f, "damaged", "cli", nil) + admissionSQL(t, f, `UPDATE review_selections SET state=? WHERE id=?`, state, bad.ID) + switch fault { + case "revision-type": + admissionSQL(t, f, `UPDATE review_selections SET revision='broken' WHERE id=?`, bad.ID) + case "revision-limit": + admissionSQL(t, f, `UPDATE review_selections SET revision=9223372036854775807 WHERE id=?`, bad.ID) + case "fingerprint-type": + admissionSQL(t, f, `UPDATE review_selections SET capability_fingerprint=CAST(capability_fingerprint AS BLOB) WHERE id=?`, bad.ID) + default: + admissionSQL(t, f, `UPDATE review_selections SET updated_at='broken' WHERE id=?`, bad.ID) + } + if fault == "write-failure" { + admissionSQL(t, f, `CREATE TRIGGER refuse_quarantine BEFORE UPDATE ON review_selections WHEN NEW.state='held' BEGIN SELECT RAISE(ABORT,'synthetic failure'); END`) + } + before := snapshotTable(t, f, "review_selections") + var err error + if state == "selecting" { + err = f.e.RecoverReviewRuns(t.Context()) + } else { + _, err = f.e.runNext(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + } + if fault == "write-failure" { + if err == nil || automaticProjectRefused(err) || before != snapshotTable(t, f, "review_selections") { + t.Fatal("persistence failure suppressed or partially committed", err) + } + return + } + if err != nil { + t.Fatal("damaged row stopped workers", err) + } + var got, reason string + if err = f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=?`, bad.ID).Scan(&got, &reason); err != nil || got != "held" || reason != "local_read_unavailable" { + t.Fatal(got, reason, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("damaged row created child") + } + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal("restart failed", err) + } + assertIndependentSelectionProgress(t, f, "cli") + }) + } + } +} diff --git a/internal/reviewexec/scheduling_snapshot0030_test.go b/internal/reviewexec/scheduling_snapshot0030_test.go new file mode 100644 index 000000000..95b97b0e4 --- /dev/null +++ b/internal/reviewexec/scheduling_snapshot0030_test.go @@ -0,0 +1,56 @@ +package reviewexec + +import ( + "errors" + "testing" +) + +type schedulingSnapshot0030Row struct { + values []any + err error +} + +func (r schedulingSnapshot0030Row) Scan(destinations ...any) error { + if r.err != nil { + return r.err + } + for i, value := range r.values { + *destinations[i].(*any) = value + } + return nil +} + +func TestSchedulingSnapshot0030PreservesStoredTypes(t *testing.T) { + var text string + var revision int64 + var enabled bool + if err := scanSchedulingSnapshot(schedulingSnapshot0030Row{values: []any{"reason", int64(1), int64(1)}}, &text, &revision, &enabled); err != nil || text != "reason" || revision != 1 || !enabled { + t.Fatal("valid stored values refused", text, revision, enabled, err) + } + for _, tc := range []struct { + name string + value any + destination any + }{ + {"blob-string", []byte("reason"), &text}, + {"number-string", int64(1), &text}, + {"null-string", nil, &text}, + {"text-revision", "1", &revision}, + {"real-revision", float64(1), &revision}, + {"blob-revision", []byte("1"), &revision}, + {"null-revision", nil, &revision}, + {"text-enabled", "true", &enabled}, + {"real-enabled", float64(1), &enabled}, + {"invalid-enabled", int64(2), &enabled}, + {"negative-enabled", int64(-1), &enabled}, + {"null-enabled", nil, &enabled}, + } { + t.Run(tc.name, func(t *testing.T) { + attemptCode(t, scanSchedulingSnapshot(schedulingSnapshot0030Row{values: []any{tc.value}}, tc.destination), "storage_unavailable") + }) + } + failure := errors.New("synthetic query failure") + if got := scanSchedulingSnapshot(schedulingSnapshot0030Row{err: failure}, &text); got != failure { + t.Fatal("query failure reclassified as retained data", got) + } +} diff --git a/internal/reviewexec/scheduling_source_acceptance_test.go b/internal/reviewexec/scheduling_source_acceptance_test.go new file mode 100644 index 000000000..e2fb445c3 --- /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) + } +} diff --git a/internal/reviewexec/scheduling_source_hold_basis_test.go b/internal/reviewexec/scheduling_source_hold_basis_test.go new file mode 100644 index 000000000..72f0498e3 --- /dev/null +++ b/internal/reviewexec/scheduling_source_hold_basis_test.go @@ -0,0 +1,67 @@ +package reviewexec + +import ( + "context" + "database/sql" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestAutomaticSourceHoldRetainsOnlyItsBoundPullSchedulingBasis(t *testing.T) { + for _, edited := range []bool{false, true} { + name := "same-pull-revision" + if edited { + name = "lawful-pause-and-resume-during-source-read" + } + t.Run(name, func(t *testing.T) { + f := schedulingFixture(t) + scope := selectionScope(t, f, attemptProject, f.admin, "write") + var receipt Receipt + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var credential string + if err := tx.QueryRowContext(ctx, `SELECT id FROM credentials WHERE principal_id=? AND is_admin=1 AND revoked=0 ORDER BY id LIMIT 1`, scope.PrincipalID).Scan(&credential); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `INSERT INTO review_scheduling(project_id,revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at) VALUES(?,1,1,0,?,?,?,?)`, scope.ProjectID, scope.PrincipalID, scope.WorkerID, credential, stamp()); err != nil { + return err + } + if err := core.AppendEvent(ctx, tx, scope, "review.scheduling_updated", scope.ProjectID, 1, map[string]any{"automatic_hosted": true, "automatic_cli": false}); err != nil { + return err + } + var err error + receipt, err = f.e.enqueueRunTx(ctx, tx, scope, RunRequest{Channel: "hosted", origin: selectionOriginAutomatic}) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, `INSERT INTO review_automatic_selections(selection_id,project_id,scheduling_revision,basis_sha256,actor_id,worker_id,credential_id) VALUES(?,?,1,?,?,?,?)`, receipt.ID, scope.ProjectID, strings.Repeat("a", 64), scope.PrincipalID, scope.WorkerID, credential) + return err + }) + if err != nil { + t.Fatal(err) + } + reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + if edited { + schedulingPause(t, f, 2, 0, true) + schedulingPause(t, f, 2, 1, false) + } + return reviewprovider.Repository{}, context.DeadlineExceeded + }} + selectionNext(t, f, reader) + got := selectionRead(t, f, receipt.ID) + if got.State != "held" || got.Reason != "source_fetch_timeout" || got.OperationID != "" || reader.calls.Load() != 1 { + t.Fatalf("source hold changed: %+v; reads=%d", got, reader.calls.Load()) + } + var accepted, settled, pullBasis string + var pull int64 + if err := f.store.DB().QueryRow(`SELECT basis_sha256,settled_basis_sha256,pull_number,pull_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, receipt.ID).Scan(&accepted, &settled, &pull, &pullBasis); err != nil { + t.Fatal(err) + } + if accepted != strings.Repeat("a", 64) || settled != "" || pull != 0 || pullBasis != "" { + t.Fatalf("unverified source hold did not retain only accepted basis: edited=%v accepted=%q settled=%q pull=%d pullBasis=%q", edited, accepted, settled, pull, pullBasis) + } + }) + } +} diff --git a/internal/reviewexec/selection_native_key_test.go b/internal/reviewexec/selection_native_key_test.go new file mode 100644 index 000000000..90a4878be --- /dev/null +++ b/internal/reviewexec/selection_native_key_test.go @@ -0,0 +1,106 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "testing" +) + +func TestSelectionNativeBlobKeyDoesNotStopRecovery(t *testing.T) { + for _, tc := range []struct{ state, key string }{ + {"queued", "id"}, + {"selecting", "id"}, + {"selecting", "project_id"}, + } { + t.Run(tc.state+"/"+tc.key, func(t *testing.T) { + f := selectionFixture(t) + corrupt, _ := selectionEnqueue(t, f, "blob-selection", "hosted", nil) + healthy, _ := selectionEnqueue(t, f, "healthy-selection", "cli", nil) + // Queued scans order by age. Recovery orders by id, where SQLite + // sorts text before blobs. Use a malformed project key as well so + // a healthy selection can follow a malformed key in that scan. + const corruptID = "review_selection_00000000000000000000000000000000" + healthyID := healthy.ID + admissionSQL(t, f, `UPDATE review_selections SET id=?,state=?,created_at=? WHERE id=?`, corruptID, tc.state, "2000-01-01T00:00:00Z", corrupt.ID) + admissionSQL(t, f, `UPDATE review_selections SET state=?,created_at=? WHERE id=?`, tc.state, "2000-01-02T00:00:00Z", healthyID) + var corruptKey any = []byte(corruptID) + if tc.key == "id" { + admissionSQL(t, f, `UPDATE review_selections SET id=CAST(id AS BLOB) WHERE id=?`, corruptID) + } else { + corruptKey = corruptID + corruptSelectionProjectKey(t, f, corruptID) + } + + if tc.state == "selecting" { + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + if got := selectionRead(t, f, healthyID); got.State != "queued" || got.Revision != 2 { + t.Fatalf("healthy selection was not recovered: %+v", got) + } + } else if worked, err := f.e.runNext(t.Context(), nil); err != nil || !worked { + t.Fatal("malformed key did not complete an isolating worker pass", worked, err) + } + + var state, reason string + if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=?`, corruptKey).Scan(&state, &reason); err != nil { + t.Fatal(err) + } + if state != "held" || reason != "local_read_unavailable" { + t.Fatal(state, reason) + } + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, healthyID); got.State != "selected" || got.OperationID == "" { + t.Fatalf("healthy selection did not progress: %+v", got) + } + }) + } +} + +func corruptSelectionProjectKey(t *testing.T, f *attemptFixture, id string) { + t.Helper() + conn, err := f.store.DB().Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if _, err := conn.ExecContext(t.Context(), `PRAGMA foreign_keys=OFF`); err != nil { + t.Fatal(err) + } + defer func() { + if _, err := conn.ExecContext(t.Context(), `PRAGMA foreign_keys=ON`); err != nil { + t.Error(err) + } + }() + if _, err := conn.ExecContext(t.Context(), `UPDATE review_selections SET project_id=CAST(project_id AS BLOB) WHERE id=?`, id); err != nil { + t.Fatal(err) + } +} + +func TestQueuedBlobSelectionWithChildDoesNotStopIndependentSelection(t *testing.T) { + f := selectionFixture(t) + broken, _ := selectionEnqueue(t, f, "linked-blob-selection", "hosted", nil) + healthy, _ := selectionEnqueue(t, f, "healthy-linked-blob-neighbor", "cli", nil) + child := f.enqueue(t, attemptProject, "retained-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 id=CAST(id AS BLOB),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=?`, []byte(broken.ID)).Scan(&state, &linkedID); err != nil || state != "queued" || linkedID != child.ID { + t.Fatalf("unproved custody was rewritten: %q %q %v", state, linkedID, err) + } +} diff --git a/internal/reviewexec/supervisor_classification_test.go b/internal/reviewexec/supervisor_classification_test.go new file mode 100644 index 000000000..1efa0eda6 --- /dev/null +++ b/internal/reviewexec/supervisor_classification_test.go @@ -0,0 +1,40 @@ +package reviewexec + +import ( + "context" + "fmt" + "testing" +) + +func TestSupervisorTypedPreparationRefusals(t *testing.T) { + for _, tc := range []struct { + name, wantState, wantReason string + refusal func() error + reservations int + }{ + {"scheduling", "queued", "automatic_scheduling_unavailable", schedulingRecordUnavailable, 0}, + {"round-history", "queued", "automatic_scheduling_unavailable", roundUnavailable, 0}, + {"retained-history", "preparing", "", func() error { + return automaticProjectStateFailure("storage_unavailable", "Synthetic retained history unavailable.", 503) + }, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + f := supervisorFixture(t) + receipt := f.enqueue(t, attemptProject, "typed-refusal", "cli", 2, 1) + driver := &controlledDriver{prepare: func(context.Context, Operation, Configuration, Attempt) (Preparation, error) { + return Preparation{}, fmt.Errorf("adapter context: %w", tc.refusal()) + }} + if err := f.e.processNext(context.Background(), map[string]Driver{"test-capability": driver, "other-account": driver}); err != nil { + t.Fatal(err) + } + var state, reason, attemptID string + if err := f.store.DB().QueryRow("SELECT state,reason,attempt_id FROM review_operations WHERE id=?", receipt.ID).Scan(&state, &reason, &attemptID); err != nil { + t.Fatal(err) + } + if state != tc.wantState || reason != tc.wantReason || (attemptID != "") != (tc.reservations > 0) || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || + attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != tc.reservations { + t.Fatalf("state=%q reason=%q attempt=%q prepares=%d dispatches=%d", state, reason, attemptID, driver.prepares.Load(), driver.calls.Load()) + } + }) + } +}