From b3ed133e8fd470e07284e9032e865a1bbd20e665 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 20:35:26 +1300 Subject: [PATCH 01/34] Preserve accepted review work and add per-PR pauses --- docs/README.md | 1 + docs/review-scheduling.md | 29 + internal/adoptionholds/read.go | 53 +- internal/adoptionholds/read_errors_test.go | 46 +- internal/adoptionholds/retarget.go | 16 +- internal/backup/inventory.go | 60 +- internal/backup/physical_schema_test.go | 56 ++ internal/backup/restore.go | 11 + internal/backup/review_fronts_test.go | 34 + internal/backup/review_selection_test.go | 138 ++++- internal/backup/scheduling_test.go | 121 ++++ internal/core/auth.go | 9 + internal/core/mutation.go | 8 +- internal/core/project_automation.go | 52 ++ internal/core/project_automation_test.go | 210 +++++++ internal/core/types.go | 23 +- .../adoption_holds_integration_test.go | 76 ++- internal/reviewexec/allowance_observation.go | 31 +- internal/reviewexec/attempt_projection.go | 2 +- internal/reviewexec/attempts.go | 27 +- internal/reviewexec/carried_obligations.go | 26 +- internal/reviewexec/cli_coverage.go | 2 +- internal/reviewexec/cli_draft_wait.go | 39 +- internal/reviewexec/front_evaluator.go | 14 + ...hosted_detached_preflight_snapshot_test.go | 60 ++ internal/reviewexec/hosted_priority.go | 8 + internal/reviewexec/hosted_priority_test.go | 33 + internal/reviewexec/hosted_wait.go | 11 +- internal/reviewexec/hosted_wait_test.go | 11 +- internal/reviewexec/hosted_wait_validation.go | 12 +- internal/reviewexec/http.go | 2 + .../local_refusal_boundaries_test.go | 48 ++ internal/reviewexec/policy.go | 10 +- internal/reviewexec/policy_admission.go | 6 + .../preferred_cli_wait_integrity_test.go | 52 ++ internal/reviewexec/queued_diagnostic.go | 16 + internal/reviewexec/requests.go | 5 +- internal/reviewexec/round_controls.go | 49 +- internal/reviewexec/routes.go | 4 +- internal/reviewexec/run_http.go | 1 + internal/reviewexec/run_selection.go | 177 +++++- .../run_selection_claim_read_test.go | 105 ++++ internal/reviewexec/run_selection_origin.go | 217 +++++++ internal/reviewexec/run_selection_schema.go | 55 +- internal/reviewexec/run_selection_snapshot.go | 117 ++++ internal/reviewexec/run_selection_worker.go | 230 ++++++- internal/reviewexec/scheduling.go | 308 +++++++++ .../scheduling_admission0030_test.go | 121 ++++ .../scheduling_authorization_continuity.go | 71 +++ internal/reviewexec/scheduling_automatic.go | 582 ++++++++++++++++++ .../scheduling_cooldown_history_test.go | 69 +++ internal/reviewexec/scheduling_http.go | 87 +++ .../scheduling_pause_history_test.go | 45 ++ .../scheduling_quarantine0030_test.go | 109 ++++ .../scheduling_recovery_regression_test.go | 281 +++++++++ internal/reviewexec/scheduling_schema.go | 34 + internal/reviewexec/scheduling_snapshot.go | 353 +++++++++++ .../scheduling_snapshot0030_test.go | 56 ++ ...cheduling_snapshot_event_integrity_test.go | 176 ++++++ .../reviewexec/scheduling_source_retry.go | 105 ++++ internal/reviewexec/scheduling_test.go | 508 +++++++++++++++ internal/reviewexec/schema.go | 5 +- .../reviewexec/selection_native_key_test.go | 106 ++++ internal/reviewexec/supervisor.go | 64 +- .../supervisor_classification_test.go | 40 ++ internal/reviewexec/wait_deadline.go | 22 +- .../reviewexec/wait_deadline_runtime_test.go | 7 +- 67 files changed, 5298 insertions(+), 164 deletions(-) create mode 100644 docs/review-scheduling.md create mode 100644 internal/backup/scheduling_test.go create mode 100644 internal/core/project_automation.go create mode 100644 internal/core/project_automation_test.go create mode 100644 internal/reviewexec/hosted_detached_preflight_snapshot_test.go create mode 100644 internal/reviewexec/local_refusal_boundaries_test.go create mode 100644 internal/reviewexec/preferred_cli_wait_integrity_test.go create mode 100644 internal/reviewexec/run_selection_claim_read_test.go create mode 100644 internal/reviewexec/run_selection_origin.go create mode 100644 internal/reviewexec/scheduling.go create mode 100644 internal/reviewexec/scheduling_admission0030_test.go create mode 100644 internal/reviewexec/scheduling_authorization_continuity.go create mode 100644 internal/reviewexec/scheduling_automatic.go create mode 100644 internal/reviewexec/scheduling_cooldown_history_test.go create mode 100644 internal/reviewexec/scheduling_http.go create mode 100644 internal/reviewexec/scheduling_pause_history_test.go create mode 100644 internal/reviewexec/scheduling_quarantine0030_test.go create mode 100644 internal/reviewexec/scheduling_recovery_regression_test.go create mode 100644 internal/reviewexec/scheduling_schema.go create mode 100644 internal/reviewexec/scheduling_snapshot.go create mode 100644 internal/reviewexec/scheduling_snapshot0030_test.go create mode 100644 internal/reviewexec/scheduling_snapshot_event_integrity_test.go create mode 100644 internal/reviewexec/scheduling_source_retry.go create mode 100644 internal/reviewexec/scheduling_test.go create mode 100644 internal/reviewexec/selection_native_key_test.go create mode 100644 internal/reviewexec/supervisor_classification_test.go diff --git a/docs/README.md b/docs/README.md index e794c7122..6632d7bfb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,6 +41,7 @@ The [Hosted source foundation](delivery.md#hosted-source-foundation) records the - [Hosted capacity settlement](hosted-settlement.md): guarded administrator recovery after verified external termination, preserving evidence and preventing automatic reposts. - [Per-PR review rounds](review-round-controls.md): explicit native grants, close, taper, cumulative accounting and bound-client contracts. - [Retained review operations](review-operations.md): provider-free discovery, compact status and original Hosted observer diagnostics. +- [Review scheduling](review-scheduling.md): per-PR pauses, accepted review work and retained-state recovery. - [Native review execution](review-execution.md): durable operations, provider adapters, isolated workspaces and the remaining dispatch/cutover boundary. - [Source refresh and observed policy](review-source.md): explicit background source reads, retained observations and provider-free policy assessment. - [Job checkpoints](job-checkpoints.md): immutable progress records, guarded appends, explicit latest/archive reads and integration status. diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md new file mode 100644 index 000000000..108d5c918 --- /dev/null +++ b/docs/review-scheduling.md @@ -0,0 +1,29 @@ +# Review scheduling + +## Pause a PR + +A project writer can pause new reviews for a PR before its first review intent or while it has queued work. The pause covers undispatched Hosted and CLI work. It preserves accepted operation identities and their cooldown deadlines, and collection of an already issued review can continue. An optional reason explains the pause. Resuming clears that reason. + +Draft eligibility, [round settings](review-round-controls.md), earned taper, channel closure and operation controls remain separate. To resume an individually paused operation, use its [operation control](retained-review-quota-controls.md). + +Use `GET` and `POST /api/v1/projects/{project_id}/reviews/pulls/{number}/scheduling` to read or update the pause. A write supplies `expected_revision`, `paused` and an optional `reason`, with the normal explicit idempotency key. An unconfigured PR reads as revision zero and unpaused. Keep the original request and key when a mutation result is uncertain. + +Project scheduling is read-only. `GET /api/v1/projects/{project_id}/reviews/scheduling` shows the retained revision, settings, authorizing worker and pauses for currently queued PRs. It reports unavailable authorization and provider holds without exposing credentials. The per-PR read can find controls outside the queue. + +## Accepted work + +Explicit selection uses the existing durable queue. Automatic origin in retained state requires matching attribution, an authorized original worker and complete relevant scheduling history. Queued or selecting work retains its original authorizer. An already selected operation can retain that original authorizer through a manager change when both authorizers remain valid and the intervening history proves continuous enablement of its channel. Missing or conflicting attribution and ambiguous legacy selections hold for operator investigation. Legacy explicit origin can be proven by an exact retained mutation receipt, a caller-supplied PR pin or complete history from before automatic scheduling for that channel. + +Current queued diagnostics identify an earlier accepted Hosted request before the later request's independent cooldown. The bounded local read uses compatible active queue and quota bindings. A paused, cancelled or invalid earlier request releases that turn. CLI shared-account quota diagnostics retain the original deadline while the accepted account and current configuration still agree. + +Version 5 of `X-FC-Operation-Wait` extends version 3 with optional `queue_ahead_pull_number` in the round-progress read. Older response versions omit it. It reports the accepted predecessor without changing allowance or deadlines. + +## Backup and restore + +Backups retain scheduling settings, PR pauses, acceptance events and automatic attribution. Inspection checks their consistency. Older bundles may omit the optional domain. Version-one Hosted-only settings migrate with automatic CLI off. Restore lands in an inactive destination with provider execution held. Historical authorizers remain evidence after revocation or retirement. + +A legacy bundle can omit a PR control when its unique latest canonical event proves an unpaused resume. Restore retains that event's actor, revision and time in the destination control and preserves the journal. A missing paused control or ambiguous history blocks restore. + +A linked selection with proven custody retains its original child identifier and observed revision in a diagnostic record. Quarantine preserves the child, authorizer, retained evidence and any existing provider action. A held child cannot obtain new admission or reserve a queued turn. Ambiguous provenance holds for investigation. + +The active selection custody migration is forward-only. Retain a verified version-one backup before upgrading. For binary rollback, restore the verified bundle to a separate inactive destination and use the [backup recovery procedure](backups.md). Version-two bundles require compatible readers and retain custody records pending an explicit retention policy. diff --git a/internal/adoptionholds/read.go b/internal/adoptionholds/read.go index bc30d3f36..f7b4f2839 100644 --- a/internal/adoptionholds/read.go +++ b/internal/adoptionholds/read.go @@ -18,6 +18,23 @@ type Facts struct { Open int64 `json:"open"` } +// projectStateError marks validated corruption in retained project records. +// Shared schema failures and operational database errors must remain unmarked. +type projectStateError struct{ error } + +func (e *projectStateError) Unwrap() error { return e.error } + +// IsProjectStateError reports a validated project-local retained-data failure. +// Public status codes alone do not distinguish it from shared storage failures. +func IsProjectStateError(err error) bool { + var local *projectStateError + return errors.As(err, &local) +} + +func projectStateUnavailable() error { + return &projectStateError{unavailable()} +} + func validTime(s string) bool { v, e := time.Parse(time.RFC3339Nano, s) return e == nil && !v.IsZero() && len(s) <= 64 @@ -65,14 +82,14 @@ func readSourceWithVersion(ctx context.Context, q Query, project, namespace stri return out, err } if !retainedInteger(repositoryValue, &out.Source.RepositoryID) || !retainedText(snapshotValue, &out.Source.SnapshotSHA256) || !retainedInteger(revisionValue, &out.Revision) || !validSource(out.Source) || out.Revision < 1 { - return out, unavailable() + return out, projectStateUnavailable() } var repository int64 if err = q.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, project).Scan(&repositoryValue); err != nil { return out, err } if !retainedInteger(repositoryValue, &repository) || repository < 1 { - return out, unavailable() + return out, projectStateUnavailable() } if repository != out.Source.RepositoryID { return out, core.Fail("repository_changed", "The retained source belongs to a different repository.", 409) @@ -109,15 +126,15 @@ func VerifyRetainedSource(ctx context.Context, q Query, project string, source m return retainedSourceReadError(err) } if !retainedText(bodyValue, &body) || !retainedText(shaValue, &sha) { - return unavailable() + return projectStateUnavailable() } var batch m.Batch if digest([]byte(body)) != sha || strictjson.Decode([]byte(body), &batch) != nil { - return unavailable() + return projectStateUnavailable() } normalized, canonical, err := NormalizeBatch(batch) if err != nil || string(canonical) != body || normalized.Source != source || *normalized.ExpectedRevision != revision-1 { - return unavailable() + return projectStateUnavailable() } return nil } @@ -149,14 +166,14 @@ func readDetailWithSources(ctx context.Context, q Query, project, id string, sou return d, err } if !retainedText(idValue, &d.ID) || !retainedText(projectValue, &d.ProjectID) || !retainedText(namespaceValue, &namespace) || !retainedInteger(sourceRevisionValue, &d.SourceRevision) || !retainedText(bodyValue, &body) || !retainedText(shaValue, &sha) || !retainedText(statusValue, &d.Status) || !retainedInteger(revisionValue, &d.Revision) || !retainedText(actorValue, &d.ActorID) || !retainedText(workerValue, &d.WorkerID) || !retainedText(createdValue, &d.CreatedAt) { - return d, unavailable() + return d, projectStateUnavailable() } if !identifier.MatchString(d.ID) || d.ProjectID != project || !sourceKey(namespace) || !identifier.MatchString(d.ActorID) || !identifier.MatchString(d.WorkerID) || !validTime(d.CreatedAt) || digest([]byte(body)) != sha || strictjson.Decode([]byte(body), &d.Original) != nil { - return d, unavailable() + return d, projectStateUnavailable() } normalized, err := NormalizeObligation(d.Original) if err != nil || string(encode(normalized)) != body { - return d, unavailable() + return d, projectStateUnavailable() } state, found := sources[namespace] if !found { @@ -171,7 +188,7 @@ func readDetailWithSources(ctx context.Context, q Query, project, id string, sou } d.Source = state.Source if d.SourceRevision < 1 || d.SourceRevision > state.Revision { - return d, unavailable() + return d, projectStateUnavailable() } var key string var keyValue any @@ -179,7 +196,7 @@ func readDetailWithSources(ctx context.Context, q Query, project, id string, sou return d, retainedSourceReadError(err) } if !retainedText(keyValue, &key) || key != d.Original.SourceKey { - return d, unavailable() + return d, projectStateUnavailable() } rows, err := q.QueryContext(ctx, `SELECT project_id,pull_number FROM review_adoption_targets WHERE obligation_id=? ORDER BY pull_number LIMIT 102`, id) if err != nil { @@ -196,7 +213,7 @@ func readDetailWithSources(ctx context.Context, q Query, project, id string, sou } if !retainedText(ownerValue, &owner) || !retainedInteger(numberValue, &n) || owner != project || !pull(n) || len(numbers) >= 101 { rows.Close() - return d, unavailable() + return d, projectStateUnavailable() } numbers = append(numbers, n) } @@ -216,7 +233,7 @@ func readDetailWithSources(ctx context.Context, q Query, project, id string, sou err = q.QueryRowContext(ctx, `SELECT revision,reason,evidence_json,actor_id,worker_id,resolved_at FROM review_adoption_resolutions WHERE obligation_id=?`, id).Scan(&revisionValue, &reasonValue, &refsValue, &actorValue, &workerValue, &resolvedValue) if errors.Is(err, sql.ErrNoRows) { if d.Status != "open" || d.Revision != latestRevision { - return d, unavailable() + return d, projectStateUnavailable() } return d, nil } @@ -224,14 +241,14 @@ func readDetailWithSources(ctx context.Context, q Query, project, id string, sou return d, err } if !retainedInteger(revisionValue, &resolution.Revision) || !retainedText(reasonValue, &resolution.Reason) || !retainedText(refsValue, &refs) || !retainedText(actorValue, &resolution.ActorID) || !retainedText(workerValue, &resolution.WorkerID) || !retainedText(resolvedValue, &resolution.ResolvedAt) { - return d, unavailable() + return d, projectStateUnavailable() } if d.Status != "resolved" || d.Revision != latestRevision+1 || resolution.Revision != d.Revision || !text(resolution.Reason, 4096) || !identifier.MatchString(resolution.ActorID) || !identifier.MatchString(resolution.WorkerID) || !validTime(resolution.ResolvedAt) || strictjson.Decode([]byte(refs), &resolution.Evidence) != nil || !m.ValidResolutionEvidence(resolution.Evidence) || string(encode(resolution.Evidence)) != refs { - return d, unavailable() + return d, projectStateUnavailable() } previous := resolution.Revision - 1 if _, err := m.NormalizeResolution(m.ResolveRequest{ExpectedRevision: &previous, Reason: resolution.Reason, Evidence: resolution.Evidence}); err != nil { - return d, unavailable() + return d, projectStateUnavailable() } d.Resolution = &resolution return d, nil @@ -259,7 +276,7 @@ func readFacts(ctx context.Context, q Query, project string, number int64, stopA break } if !retainedText(idValue, &id) || !identifier.MatchString(id) { - err = unavailable() + err = projectStateUnavailable() break } ids = append(ids, id) @@ -282,7 +299,7 @@ func readFacts(ctx context.Context, q Query, project string, number int64, stopA return facts, nil } if facts.Open > 1<<53-1 { - return facts, unavailable() + return facts, projectStateUnavailable() } } after = id @@ -321,7 +338,7 @@ func readFactsIfPresent(ctx context.Context, q Query, project string, number int func retainedSourceReadError(err error) error { var failure *core.Error if errors.Is(err, sql.ErrNoRows) || errors.As(err, &failure) && failure.Code == "not_found" { - return unavailable() + return projectStateUnavailable() } return err } diff --git a/internal/adoptionholds/read_errors_test.go b/internal/adoptionholds/read_errors_test.go index e79ab1061..5e6afd27b 100644 --- a/internal/adoptionholds/read_errors_test.go +++ b/internal/adoptionholds/read_errors_test.go @@ -43,7 +43,7 @@ func TestReadFactsMissingRetainedRowsRemainProtective(t *testing.T) { q := obligationQueryFailure{Query: f.store.DB(), match: stage, row: true, missing: true} _, err := h.ReadFacts(t.Context(), q, "project_one", 3251) var failure *core.Error - if !errors.As(err, &failure) || failure.Code != "storage_unavailable" { + if !errors.As(err, &failure) || failure.Code != "storage_unavailable" || !h.IsProjectStateError(err) { t.Fatal("missing retained row escaped protection", stage, err) } } @@ -60,7 +60,7 @@ func TestReadFactsPreservesOperationalErrors(t *testing.T) { for _, stage := range []string{"SELECT obligation_id", "SELECT project_id,pull_number"} { for _, failure := range []error{obligationStorageCode(5), obligationStorageCode(6), context.Canceled, context.DeadlineExceeded, core.Fail("overloaded", "Safe transient failure.", 503), errors.New("private unknown SQL failure")} { q := obligationQueryFailure{Query: f.store.DB(), match: stage, err: failure} - if _, err := h.ReadFacts(t.Context(), q, "project_one", 3251); !errors.Is(err, failure) { + if _, err := h.ReadFacts(t.Context(), q, "project_one", 3251); !errors.Is(err, failure) || h.IsProjectStateError(err) { t.Fatalf("%s erased %T: %v", stage, failure, err) } } @@ -70,7 +70,7 @@ func TestReadFactsPreservesOperationalErrors(t *testing.T) { q := obligationQueryFailure{Query: f.store.DB(), match: stage, row: true} _, err := h.ReadFacts(t.Context(), q, "project_one", 3251) var code interface{ Code() int } - if !errors.As(err, &code) || code.Code()&255 != 1 { + if !errors.As(err, &code) || code.Code()&255 != 1 || h.IsProjectStateError(err) { t.Fatal("query failure became a retained-data hold", err) } }) @@ -103,7 +103,7 @@ func TestReadFactsPreservesIterationFailure(t *testing.T) { rows.Close() _, err = h.ReadFacts(t.Context(), q, "project_one", 3251) var code interface{ Code() int } - if !errors.As(err, &code) || code.Code()&255 != 1 { + if !errors.As(err, &code) || code.Code()&255 != 1 || h.IsProjectStateError(err) { t.Fatal("partial row list concealed iteration failure", err) } } @@ -125,6 +125,7 @@ func TestReadFactsStoredValueCorruptionRemainsProtective(t *testing.T) { {"oversized-original", `DROP TRIGGER review_adoption_originals_immutable; UPDATE review_adoption_obligations SET original_json=?`, []any{strings.Repeat("x", 65537)}}, {"nonnumeric-source-epoch", `UPDATE review_adoption_sources SET revision='broken'`, nil}, {"nonnumeric-domain-version", `UPDATE metadata SET value='broken' WHERE key='schema:review_adoption_obligations'`, nil}, + {"missing-domain-table", `ALTER TABLE review_adoption_retargets RENAME TO missing_adoption_retargets`, nil}, {"noncanonical-domain-version", `UPDATE metadata SET value='01' WHERE key='schema:review_adoption_obligations'`, nil}, } { t.Run(tc.name, func(t *testing.T) { @@ -142,6 +143,10 @@ func TestReadFactsStoredValueCorruptionRemainsProtective(t *testing.T) { if !errors.As(err, &failure) || failure.Code != "storage_unavailable" { t.Fatal("malformed stored value escaped protective classification", err) } + wantLocal := !strings.Contains(tc.name, "domain") + if h.IsProjectStateError(err) != wantLocal { + t.Fatal("project corruption and shared schema failure were conflated", err) + } }) } } @@ -156,13 +161,13 @@ func TestVerifyRetainedSourceSeparatesQueryFailureAndOversizedBody(t *testing.T) q := obligationQueryFailure{Query: f.store.DB(), match: "CASE WHEN length(CAST(batch_json", row: true} err = h.VerifyRetainedSource(t.Context(), q, "project_one", state.Source, state.Revision) var code interface{ Code() int } - if !errors.As(err, &code) || code.Code()&255 != 1 { + if !errors.As(err, &code) || code.Code()&255 != 1 || h.IsProjectStateError(err) { t.Fatal("retained provenance query failure became corruption", err) } f.exec(`DROP TRIGGER review_adoption_imports_immutable; UPDATE review_adoption_imports SET batch_json=?`, strings.Repeat("x", 262145)) err = h.VerifyRetainedSource(t.Context(), f.store.DB(), "project_one", state.Source, state.Revision) var failure *core.Error - if !errors.As(err, &failure) || failure.Code != "storage_unavailable" { + if !errors.As(err, &failure) || failure.Code != "storage_unavailable" || !h.IsProjectStateError(err) { t.Fatal("oversized retained provenance lost protective classification", err) } } @@ -196,7 +201,7 @@ func TestRetargetAggregateStoredTypesRemainProtective(t *testing.T) { } { t.Run(read.name, func(t *testing.T) { var failure *core.Error - if err := read.call(); !errors.As(err, &failure) || failure.Code != "storage_unavailable" { + if err := read.call(); !errors.As(err, &failure) || failure.Code != "storage_unavailable" || !h.IsProjectStateError(err) { t.Fatal("corrupt aggregate escaped protective classification", err) } }) @@ -215,8 +220,33 @@ func TestRetargetAggregatePreservesQueryFailure(t *testing.T) { func() error { _, err := h.HasOpen(t.Context(), q, "project_one", 3341); return err }, } { var code interface{ Code() int } - if err := read(); !errors.As(err, &code) || code.Code()&255 != 1 { + if err := read(); !errors.As(err, &code) || code.Code()&255 != 1 || h.IsProjectStateError(err) { t.Fatal("aggregate query failure became a retained-data hold", err) } } } + +func TestProjectStateMarkerPreservesContextAndTransactionFailures(t *testing.T) { + f := fresh(t) + f.apply(batch(), "project-marker-operational-errors") + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := h.ReadFacts(ctx, f.store.DB(), "project_one", 3251); !errors.Is(err, context.Canceled) || h.IsProjectStateError(err) { + t.Fatal("cancelled SQLite read became project corruption", err) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + if err := tx.Rollback(); err != nil { + t.Fatal(err) + } + if _, err := h.ReadFacts(t.Context(), tx, "project_one", 3251); !errors.Is(err, sql.ErrTxDone) || h.IsProjectStateError(err) { + t.Fatal("completed SQLite transaction became project corruption", err) + } + for _, err := range []error{nil, core.Fail("storage_unavailable", "Shared storage failure.", 500), core.Fail("not_found", "Unrelated missing resource.", 404), context.DeadlineExceeded, sql.ErrTxDone} { + if h.IsProjectStateError(err) { + t.Fatal("unvalidated failure received project classification", err) + } + } +} diff --git a/internal/adoptionholds/retarget.go b/internal/adoptionholds/retarget.go index d35354389..eafa41805 100644 --- a/internal/adoptionholds/retarget.go +++ b/internal/adoptionholds/retarget.go @@ -25,11 +25,11 @@ func readRetargetRecord(row rowScanner, original m.Obligation) (m.Retarget, stri return result, targets, err } if !retainedInteger(revisionValue, &result.Revision) || !retainedInteger(targetValue, &result.TargetPullNumber) || !retainedText(targetsValue, &targets) || !retainedText(reasonValue, &result.Reason) || !retainedText(actorValue, &result.ActorID) || !retainedText(workerValue, &result.WorkerID) || !retainedText(changedValue, &result.ChangedAt) || original.Kind != "route" || result.Revision < 2 || !identifier.MatchString(result.ActorID) || !identifier.MatchString(result.WorkerID) || !validTime(result.ChangedAt) { - return result, targets, unavailable() + return result, targets, projectStateUnavailable() } previous := result.Revision - 1 if _, err := m.NormalizeRetarget(m.RetargetRequest{ExpectedRevision: &previous, TargetPullNumber: &result.TargetPullNumber, Reason: result.Reason}); err != nil || string(encode(m.RouteAffectedPullNumbers(original, result.TargetPullNumber))) != targets { - return result, targets, unavailable() + return result, targets, projectStateUnavailable() } return result, targets, nil } @@ -37,7 +37,7 @@ func readRetargetRecord(row rowScanner, original m.Obligation) (m.Retarget, stri func readRetargetState(ctx context.Context, q Query, detail *m.Detail, version string) (int64, error) { if version == "1" { if !slices.Equal(detail.AffectedPullNumbers, detail.Original.AffectedPullNumbers) { - return 0, unavailable() + return 0, projectStateUnavailable() } return 1, nil } @@ -50,25 +50,25 @@ func readRetargetState(ctx context.Context, q Query, detail *m.Detail, version s return 0, err } if !retainedInteger(countValue, &count) || !retainedInteger(firstValue, &first) || !retainedInteger(lastValue, &last) { - return 0, unavailable() + return 0, projectStateUnavailable() } if count == 0 { if !slices.Equal(detail.AffectedPullNumbers, detail.Original.AffectedPullNumbers) { - return 0, unavailable() + return 0, projectStateUnavailable() } return 1, nil } if first != 2 || count != last-1 { - return 0, unavailable() + return 0, projectStateUnavailable() } latest, targets, err := readRetargetRecord(q.QueryRowContext(ctx, `SELECT `+retargetColumns+` FROM review_adoption_retargets WHERE obligation_id=? ORDER BY revision DESC LIMIT 1`, detail.ID), detail.Original) if err != nil { - return 0, err + return 0, retainedSourceReadError(err) } created, _ := time.Parse(time.RFC3339Nano, detail.CreatedAt) changed, _ := time.Parse(time.RFC3339Nano, latest.ChangedAt) if latest.Revision != last || targets != string(encode(detail.AffectedPullNumbers)) || changed.Before(created) { - return 0, unavailable() + return 0, projectStateUnavailable() } detail.Retarget = &latest return latest.Revision, nil diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index 5915d4b23..f8b9637c2 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -233,11 +233,15 @@ type tableVersion struct { // Fixed application schema bounds are intentionally independent of migration // execution. Inspection never opens a Store or installs/rewrites a schema. -var supportedDomains = map[string]int{"review_fronts": 1, "project_management": 1, "worker_retirements": 1, "review_selection": 1, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 4, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} +var supportedDomains = map[string]int{"review_scheduling": 2, "review_fronts": 1, "project_management": 1, "worker_retirements": 1, "review_selection": 2, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 4, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} var tables = map[string]tableVersion{ + "review_scheduling": {"review_scheduling", 1, "project_id revision automatic_hosted actor_id worker_id credential_id updated_at"}, + "review_pull_scheduling": {"review_scheduling", 1, "project_id pull_number revision paused reason actor_id updated_at"}, + "review_automatic_selections": {"review_scheduling", 1, "selection_id project_id scheduling_revision basis_sha256 settled_basis_sha256 pull_number pull_basis_sha256 actor_id worker_id credential_id"}, "review_front_frames": {"review_fronts", 1, "project_id channel repository_id configuration_revision checked_at source_observed_at complete source_reason prefix_json"}, "review_operation_waits": {"review_execution", 9, "operation_id baseline_attempt_id retry_not_before paused"}, "worker_retirements": {"worker_retirements", 1, "project_id worker_id retired_at actor_id"}, + "review_selection_quarantine": {"review_selection", 2, "selection_id project_id original_operation_id original_state observed_revision"}, "review_selections": {"review_selection", 1, "id project_id actor_id worker_id channel configuration_revision policy_revision capability_fingerprint expected_pull_number state reason revision operation_id created_at updated_at"}, "review_hosted_discovery_state": {"reviews", 11, "project_id repository_id pull_number cutoff_at initialized_at"}, "review_pull_versions": {"reviews", 4, "project_id number version_revision title state head_sha base_ref base_sha ci_state mergeability complete run_count attempt_count recent_runs_json latest_attempts_json"}, @@ -618,6 +622,17 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ return nil, invalid() } } + if versions["review_scheduling"] > 0 { + if versions["review_selection"] == 0 || versions["review_execution"] == 0 { + return nil, invalid() + } + if err = validateSchedulingPhysicalSchema(ctx, db, versions["review_scheduling"]); err != nil { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, err + } + } if versions["worker_retirements"] > 0 { if err := validatePhysicalSchemaObjects(ctx, db, map[string]physicalSchemaObject{"worker_retirements": {"table", `CREATE TABLE worker_retirements(project_id TEXT NOT NULL REFERENCES projects(id),worker_id TEXT NOT NULL,retired_at TEXT NOT NULL,actor_id TEXT NOT NULL,PRIMARY KEY(project_id,worker_id),FOREIGN KEY(project_id,worker_id) REFERENCES workers(project_id,id))`}}, []string{"worker_retirements"}); err != nil { if contextErr := checkContext(ctx); contextErr != nil { @@ -688,6 +703,9 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ continue } columns := spec.columns + if name == "review_scheduling" && versions["review_scheduling"] >= 2 { + columns += " automatic_cli" + } if name == "grants" && versions["project_management"] > 0 { columns += " can_manage" } @@ -1075,6 +1093,25 @@ func validateSnapshotContent(ctx context.Context, dataDir string, m Manifest, al return invalid() } } + if versions["review_scheduling"] == 0 { + // An optional predecessor domain may be absent only before it has + // produced durable controls. Dropping tables cannot erase that history. + var used bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events WHERE event_type IN ('review.scheduling_updated','review.pull_scheduling_updated'))`).Scan(&used); err != nil { + return err + } + if used { + return invalid() + } + } + if versions["review_scheduling"] > 0 { + if err = reviewexec.ValidateSchedulingSnapshot(ctx, tx); err != nil { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + } if versions["review_fronts"] > 0 { if err = reviewexec.ValidateFrontSnapshot(ctx, tx); err != nil { if checkContext(ctx) != nil { @@ -1281,8 +1318,12 @@ func canonicalFK(table, from, to, onDelete string) foreignKey { } var canonicalForeignKeys = map[string][]foreignKey{ + "review_scheduling": {canonicalFK("projects", "project_id", "id", "NO ACTION")}, + "review_pull_scheduling": {canonicalFK("projects", "project_id", "id", "NO ACTION")}, + "review_automatic_selections": {canonicalFK("review_selections", "selection_id", "id", "NO ACTION"), canonicalFK("projects", "project_id", "id", "NO ACTION")}, "review_front_frames": {canonicalFK("projects", "project_id", "id", "NO ACTION"), canonicalFK("review_execution_config", "project_id,configuration_revision", "project_id,revision", "NO ACTION")}, "review_operation_waits": {canonicalFK("review_operations", "operation_id", "id", "NO ACTION"), canonicalFK("review_execution_attempts", "baseline_attempt_id", "id", "NO ACTION")}, + "review_selection_quarantine": {canonicalFK("review_selections", "selection_id", "id", "NO ACTION"), canonicalFK("projects", "project_id", "id", "NO ACTION")}, "review_selections": {canonicalFK("projects", "project_id", "id", "NO ACTION"), canonicalFK("review_operations", "operation_id", "id", "NO ACTION"), canonicalFK("review_execution_config", "project_id,configuration_revision", "project_id,revision", "NO ACTION"), canonicalFK("review_policy_config", "project_id,policy_revision", "project_id,revision", "NO ACTION")}, "review_hosted_discovery_state": {canonicalFK("projects", "project_id", "id", "CASCADE")}, "review_pull_versions": {canonicalFK("review_snapshots", "project_id,version_revision", "project_id,revision", "NO ACTION")}, @@ -1659,6 +1700,23 @@ func validateExternalHostedEvidenceIndexes(ctx context.Context, db sqlReader, ve return nil } +func validateSchedulingPhysicalSchema(ctx context.Context, db sqlReader, version int) error { + expected := map[string]physicalSchemaObject{} + statements := reviewexec.SchedulingSchemaSQL() + if version >= 2 { + statements = reviewexec.SchedulingSchemaV2SQL() + } + for _, statement := range statements { + fields := strings.Fields(statement) + if len(fields) < 4 || fields[0] != "CREATE" || fields[1] != "TABLE" && fields[1] != "INDEX" { + return invalid() + } + name, _, _ := strings.Cut(fields[2], "(") + expected[name] = physicalSchemaObject{strings.ToLower(fields[1]), historyDefinitionSQL(statement)} + } + return validatePhysicalSchemaObjects(ctx, db, expected, []string{"review_scheduling", "review_pull_scheduling", "review_automatic_selections"}) +} + func validateAdministrationContent(ctx context.Context, db sqlReader, versions map[string]int) error { if versions["project_management"] > 0 { var bad int 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/restore.go b/internal/backup/restore.go index ce5d2af9d..cd8549ef2 100644 --- a/internal/backup/restore.go +++ b/internal/backup/restore.go @@ -14,6 +14,7 @@ import ( "strings" "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewexec" ) const restoreMarker = ".restore-in-progress" @@ -243,6 +244,16 @@ func restoreIdentity(ctx context.Context, dir string, m Manifest, id, key string if _, err = tx.ExecContext(ctx, `UPDATE credentials SET revoked=1`); err != nil { return unavailable() } + if err = reviewexec.RestoreHistoricalPullResumes(ctx, tx); err != nil { + if interrupted := checkContext(ctx); interrupted != nil { + return interrupted + } + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "storage_unavailable" { + return invalid() + } + return unavailable() + } if err = tx.Commit(); err != nil { return unavailable() } 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/backup/review_selection_test.go b/internal/backup/review_selection_test.go index e40284af6..57f95014c 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -2,6 +2,7 @@ package backup import ( "context" + "database/sql" "encoding/json" "path/filepath" "reflect" @@ -225,9 +226,7 @@ func TestSelectionInventorySchemaAndPredecessor(t *testing.T) { if err := f.store.DB().QueryRow(`SELECT count(*) FROM review_selections`).Scan(&count); err != nil || count != 0 { t.Fatal("predecessor domain not empty", err) } - if _, err := f.store.DB().Exec(`DROP TABLE review_selections;DELETE FROM metadata WHERE key='schema:review_selection'`); err != nil { - t.Fatal(err) - } + dropSelectionPredecessorDomains(t, f.store.DB()) bundle := restoreBundle(t, f) if _, err := Inspect(t.Context(), bundle.Path); err != nil { t.Fatal(err) @@ -235,18 +234,23 @@ func TestSelectionInventorySchemaAndPredecessor(t *testing.T) { }) } -// Removing the independent optional domain reconstructs the unchanged parent -// physical schema, rather than relabeling a newer reviews/execution migration. +// The newer scheduling and front-cache domains must be absent from a +// predecessor snapshot along with selection. Scheduling references selections +// directly, so leaving it installed would not describe a valid predecessor. +func dropSelectionPredecessorDomains(t *testing.T, db *sql.DB) { + t.Helper() + if _, err := db.Exec(`DROP TABLE review_selection_quarantine; DROP TABLE review_automatic_selections; DROP TABLE review_pull_scheduling; DROP TABLE review_scheduling; DROP TABLE review_front_frames; DROP TABLE review_selections; DELETE FROM metadata WHERE key IN ('schema:review_scheduling','schema:review_fronts','schema:review_selection')`); err != nil { + t.Fatal(err) + } +} + +// Removing the new optional domains reconstructs a valid parent schema without +// relabeling a newer reviews/execution migration. func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testing.T) { f := newRestoreFixture(t) db := f.store.DB() - if _, err := db.Exec(`DROP TABLE review_selections;DELETE FROM metadata WHERE key='schema:review_selection'`); err != nil { - t.Fatal(err) - } + dropSelectionPredecessorDomains(t, db) before := backupRows(t, db) - if _, ok := before["review_front_frames"]; !ok { - t.Fatal("predecessor must already include review front frames") - } schema := restoreRows(t, db, `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name`) metadata := restoreRows(t, db, `SELECT key,value FROM metadata ORDER BY key`) for domain, version := range map[string]string{"reviews": "11", "review_execution": "10", "review_policy": "1", "review_rounds": "5"} { @@ -272,10 +276,10 @@ func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testin t.Fatal("upgrade changed business bytes", table) } } - if got := restoreRows(t, db, `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' AND tbl_name<>'review_selections' ORDER BY type,name`); !reflect.DeepEqual(schema, got) { + if got := restoreRows(t, db, `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' AND tbl_name NOT IN ('review_selection_quarantine','review_selections','review_scheduling','review_pull_scheduling','review_automatic_selections','review_front_frames') ORDER BY type,name`); !reflect.DeepEqual(schema, got) { t.Fatal("upgrade changed predecessor physical SQL") } - if got := restoreRows(t, db, `SELECT key,value FROM metadata WHERE key<>'schema:review_selection' ORDER BY key`); !reflect.DeepEqual(metadata, got) { + if got := restoreRows(t, db, `SELECT key,value FROM metadata WHERE key NOT IN ('schema:review_selection','schema:review_scheduling','schema:review_fronts') ORDER BY key`); !reflect.DeepEqual(metadata, got) { t.Fatal("upgrade changed parent metadata") } var count int @@ -283,16 +287,114 @@ func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testin t.Fatal("upgrade manufactured selection activity", count, err) } var version string - if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:review_selection'`).Scan(&version); err != nil || version != "1" { + if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:review_selection'`).Scan(&version); err != nil || version != "2" { t.Fatal("selection domain version", version, err) } - if len(after) != len(before)+1 { - t.Fatal("upgrade added another table domain") + if len(after) != len(before)+6 { + t.Fatal("upgrade did not reinstall the newer optional domains", len(before), len(after)) } - if err := db.QueryRow(`SELECT count(*) FROM sqlite_schema WHERE name IN ('review_scheduling','review_pull_scheduling','review_automatic_selections','review_pr_followers')`).Scan(&count); err != nil || count != 0 { - t.Fatal("deferred domain installed", count, err) + for domain, version := range map[string]string{"review_selection": "2", "review_scheduling": "2", "review_fronts": "1"} { + var got string + if err := db.QueryRow(`SELECT value FROM metadata WHERE key=?`, "schema:"+domain).Scan(&got); err != nil || got != version { + t.Fatal("reinstalled domain version", domain, got, err) + } + } + if err := db.QueryRow(`SELECT count(*) FROM sqlite_schema WHERE type='table' AND name IN ('review_selection_quarantine','review_selections','review_scheduling','review_pull_scheduling','review_automatic_selections','review_front_frames')`).Scan(&count); err != nil || count != 6 { + t.Fatal("new optional domain tables were not reinstalled", count, err) + } + if err := db.QueryRow(`SELECT count(*) FROM sqlite_schema WHERE name='review_pr_followers'`).Scan(&count); err != nil || count != 0 { + t.Fatal("unexpected deferred domain installed", count, err) + } + for _, table := range []string{"review_scheduling", "review_pull_scheduling", "review_automatic_selections", "review_front_frames"} { + if err := db.QueryRow(`SELECT count(*) FROM ` + table).Scan(&count); err != nil || count != 0 { + t.Fatal("upgrade manufactured optional-domain activity", table, count, err) + } } if err := reviewexec.ValidateSelectionSnapshot(t.Context(), db); err != nil { t.Fatal(err) } } + +func TestSelectionQuarantineInventoryRetainsInertMissingLink(t *testing.T) { + f, id := selectionInventoryFixture(t, "queued") + ctx := t.Context() + // Exercise only the canonical post-recovery representation; this does + // not manufacture an invalid pending row, grant, or executing child. + err := f.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held', + reason='linked_selection_quarantined',revision=2 WHERE id=?`, id); err != nil { + return err + } + _, err := tx.ExecContext(ctx, `INSERT INTO review_selection_quarantine + (selection_id,project_id,original_operation_id,original_state,observed_revision) + VALUES(?,?,'review_operation_absent_fixture','queued',1)`, id, f.project) + return err + }) + if err != nil { + t.Fatal(err) + } + const diagnostics = `SELECT selection_id,project_id,original_operation_id,original_state,observed_revision + FROM review_selection_quarantine` + const children = `SELECT * FROM review_operations ORDER BY id` + before, kept := restoreRows(t, f.store.DB(), diagnostics), restoreRows(t, f.store.DB(), children) + bundle := restoreBundle(t, f) + destination := filepath.Join(t.TempDir(), "inactive-with-diagnostic") + if _, err := Restore(ctx, bundle.Path, destination); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(ctx, filepath.Join(destination, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if len(before) != 1 || !reflect.DeepEqual(before, restoreRows(t, db, diagnostics)) || !reflect.DeepEqual(kept, restoreRows(t, db, children)) { + t.Fatal("inert diagnostic or unchanged child state lost") + } + testBundle := restoreBundle(t, f) + mutateBundleSQL(t, testBundle.Path, `UPDATE review_selection_quarantine SET observed_revision=2`) + assertCurrentSummaryInventoryRefused(t, testBundle, false) +} + +func TestSelectionQuarantineInventoryKeepsV1Restore(t *testing.T) { + f, _ := selectionInventoryFixture(t, "queued") + if _, err := f.store.DB().Exec(`DROP TABLE review_selection_quarantine; + UPDATE metadata SET value='1' WHERE key='schema:review_selection'`); err != nil { + t.Fatal(err) + } + bundle := restoreBundle(t, f) + destination := filepath.Join(t.TempDir(), "inactive-v1-selection") + if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(destination, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var version string + if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:review_selection'`).Scan(&version); err != nil || version != "1" { + t.Fatal("offline restore migrated the previous snapshot", version, err) + } + mutateBundleSQL(t, bundle.Path, `UPDATE review_selections + SET state='held',reason='linked_selection_quarantined',revision=2`) + assertCurrentSummaryInventoryRefused(t, bundle, false) +} + +func TestSelectionQuarantineInventoryRefusesV1NameCollision(t *testing.T) { + f, _ := selectionInventoryFixture(t, "queued") + if _, err := f.store.DB().Exec(`DROP TABLE review_selection_quarantine; + UPDATE metadata SET value='1' WHERE key='schema:review_selection'`); err != nil { + t.Fatal(err) + } + bundle := restoreBundle(t, f) + mutateBundleSQL(t, bundle.Path, `CREATE INDEX Review_Selection_Quarantine ON projects(id)`) + assertCurrentSummaryInventoryRefused(t, bundle, false) +} + +func TestSelectionQuarantineInventoryRejectsDanglingEmptyV2Marker(t *testing.T) { + f, _ := selectionInventoryFixture(t, "queued") + bundle := restoreBundle(t, f) + mutateBundleSQL(t, bundle.Path, `UPDATE review_selections + SET state='held',reason='linked_selection_quarantined',revision=2`) + assertCurrentSummaryInventoryRefused(t, bundle, false) +} diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go new file mode 100644 index 000000000..379d53d25 --- /dev/null +++ b/internal/backup/scheduling_test.go @@ -0,0 +1,121 @@ +package backup + +import ( + "context" + "database/sql" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewexec" +) + +func TestSchedulingBackupRetainsCanonicalProjectRow(t *testing.T) { + f := newRestoreFixture(t) + // Model previously accepted settings in the native schema. The foundation + // has no project write path and this fixture does not synthesize a selection. + if 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`, f.principal).Scan(&credential); err != nil { + return err + } + at := time.Now().UTC().Format(time.RFC3339Nano) + 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,?,?,?,?)`, f.project, f.principal, f.worker, credential, at); err != nil { + return err + } + _, err := tx.ExecContext(ctx, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) + VALUES(?,'review.scheduling_updated',?,1,?,'{"automatic_hosted":true,"automatic_cli":false,"hosted_basis_revision":1,"cli_basis_revision":1}',?)`, f.project, f.project, f.principal, at) + return err + }); err != nil { + t.Fatal(err) + } + const controls = `SELECT * FROM review_scheduling` + const journal = `SELECT * FROM events WHERE event_type='review.scheduling_updated' ORDER BY sequence` + wantControls, wantJournal := restoreRows(t, f.store.DB(), controls), restoreRows(t, f.store.DB(), journal) + bundle := restoreBundle(t, f) + immutable := restoreTree(t, bundle.Path) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal(err) + } + destination := filepath.Join(t.TempDir(), "inactive-project-scheduling") + if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { + t.Fatal(err) + } + store, err := core.Open(t.Context(), destination) + if err != nil { + t.Fatal(err) + } + defer store.Close() + status, err := ReadRecoveryStatus(t.Context(), store) + if err != nil || status.State != "inactive" || !status.ProvidersHeld { + t.Fatal("restored settings unlocked provider work", status, err) + } + for _, db := range []*sql.DB{store.DB(), f.store.DB()} { + if !reflect.DeepEqual(wantControls, restoreRows(t, db, controls)) || !reflect.DeepEqual(wantJournal, restoreRows(t, db, journal)) { + t.Fatal("backup/restore changed prior scheduling authority") + } + } + if !reflect.DeepEqual(immutable, restoreTree(t, bundle.Path)) { + t.Fatal("restore changed the validated bundle") + } +} + +func TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { + f := newRestoreFixture(t) + e := selectionInventoryEngine(t, f.store) + scope := routePolicyInventoryScope(t, f) + zero, one := int64(0), int64(1) + paused, resumed := true, false + for _, pull := range []int64{2, 4} { + if _, err := e.ConfigurePullScheduling(t.Context(), scope, "initial-pull-pause", pull, + reviewexec.PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused, Reason: "Fixture pause"}); err != nil { + t.Fatal(err) + } + } + if _, err := e.ConfigurePullScheduling(t.Context(), scope, "historical-pull-resume", 4, + reviewexec.PullSchedulingRequest{ExpectedRevision: &one, Paused: &resumed}); err != nil { + t.Fatal(err) + } + event := restoreRows(t, f.store.DB(), `SELECT project_id,4,revision,0,'',actor_id,created_at + FROM events WHERE event_type='review.pull_scheduling_updated' AND resource_id='4' AND revision=2`) + if len(event) != 1 || len(event[0]) != 7 { + t.Fatalf("expected one historical resume event, got %v", event) + } + if _, err := f.store.DB().Exec(`DELETE FROM review_pull_scheduling WHERE project_id=? AND pull_number=4`, f.project); err != nil { + t.Fatal(err) + } + const controls = `SELECT project_id,pull_number,revision,paused,reason,actor_id,updated_at FROM review_pull_scheduling ORDER BY pull_number` + const journal = `SELECT * FROM events ORDER BY sequence` + sourceControls, sourceJournal := restoreRows(t, f.store.DB(), controls), restoreRows(t, f.store.DB(), journal) + if len(sourceControls) != 1 { + t.Fatalf("expected one untouched control, got %v", sourceControls) + } + bundle := restoreBundle(t, f) + immutable := restoreTree(t, bundle.Path) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal("valid legacy bundle no longer inspectable", err) + } + destination := filepath.Join(t.TempDir(), "inactive-resume") + if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { + t.Fatal("valid legacy bundle no longer restorable", err) + } + dst, err := openSnapshot(t.Context(), filepath.Join(destination, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer dst.Close() + want := [][]any{sourceControls[0], event[0]} + if got := restoreRows(t, dst, controls); !reflect.DeepEqual(want, got) { + t.Fatalf("restored controls lost canonical revision or attribution: got %v, want %v", got, want) + } + if !reflect.DeepEqual(sourceJournal, restoreRows(t, dst, journal)) { + t.Fatal("offline restore appended or rewrote historical events") + } + if !reflect.DeepEqual(sourceControls, restoreRows(t, f.store.DB(), controls)) || !reflect.DeepEqual(immutable, restoreTree(t, bundle.Path)) { + t.Fatal("restore mutated source controls or validated bundle") + } +} diff --git a/internal/core/auth.go b/internal/core/auth.go index 85e19c693..5ee5e4051 100644 --- a/internal/core/auth.go +++ b/internal/core/auth.go @@ -168,6 +168,15 @@ func (s *Store) authorize(ctx context.Context, q querier, scope Scope, permissio return storageError(err) } } + if scope.activeWorkerRequired { + var retired bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM worker_retirements WHERE project_id=? AND worker_id=?)`, scope.ProjectID, scope.WorkerID).Scan(&retired); err != nil { + return storageError(err) + } + if retired { + return Fail("worker_retired", "This worker is retired; select an active worker for new coordination work.", 409) + } + } } else if scope.WorkerID != "" { return Fail("validation_failed", "Worker attribution requires a project.", 400) } diff --git a/internal/core/mutation.go b/internal/core/mutation.go index 7c058c2cc..09420929d 100644 --- a/internal/core/mutation.go +++ b/internal/core/mutation.go @@ -90,10 +90,16 @@ func mutationFingerprint(scope Scope, m Mutation) (string, error) { if !validIdempotencyKey(m.Key) || m.Operation == "" || m.Target == "" { return "", Fail("validation_failed", "A bounded Idempotency-Key, operation and target are required.", 400) } + return MutationRequestFingerprint(m.Request, scope.WorkerID) +} + +// MutationRequestFingerprint identifies a normalized request and worker in a +// retained receipt. It supplies no instance, project or principal authority. +func MutationRequestFingerprint(request any, worker string) (string, error) { data, err := json.Marshal(struct { Request any Worker string - }{m.Request, scope.WorkerID}) + }{request, worker}) if err != nil { return "", Fail("validation_failed", "The mutation request cannot be encoded.", 400) } diff --git a/internal/core/project_automation.go b/internal/core/project_automation.go new file mode 100644 index 000000000..df217152e --- /dev/null +++ b/internal/core/project_automation.go @@ -0,0 +1,52 @@ +package core + +import ( + "context" + "database/sql" + "errors" +) + +// AuthenticatedCredentialID identifies the exact current credential behind an +// authenticated scope without exposing its token or hash. It grants no access. +func (s *Store) AuthenticatedCredentialID(ctx context.Context, tx *sql.Tx, scope Scope) (string, error) { + permission := "read" + if scope.Administrative() { + permission = "admin" + } + if err := s.authorize(ctx, tx, scope, permission); err != nil { + return "", err + } + var id string + err := tx.QueryRowContext(ctx, `SELECT id FROM credentials WHERE token_sha256=? AND principal_id=? AND revoked=0`, scope.tokenHash, scope.PrincipalID).Scan(&id) + if err != nil { + return "", storageError(err) + } + return id, nil +} + +// ProjectAutomationScope revalidates an explicitly retained project automation +// authorization. Callers obtain these identities from their own durable control +// record, never from an unauthenticated request. The exact credential must still +// manage this project and its attributed worker must remain active. Subsequent +// Store operations reauthorize the returned scope again at their boundary. +func (s *Store) ProjectAutomationScope(ctx context.Context, tx *sql.Tx, project, principal, worker, credential string) (Scope, error) { + if project == "" || principal == "" || worker == "" || credential == "" { + return Scope{}, Fail("forbidden", "Current project automation authorization is required.", 403) + } + var hash string + err := tx.QueryRowContext(ctx, `SELECT token_sha256 FROM credentials WHERE id=? AND principal_id=? AND revoked=0`, credential, principal).Scan(&hash) + if errors.Is(err, sql.ErrNoRows) { + return Scope{}, Fail("forbidden", "The project automation authorization is no longer current.", 403) + } + if err != nil { + return Scope{}, storageError(err) + } + scope := Scope{ProjectID: project, PrincipalID: principal, WorkerID: worker, tokenHash: hash, instanceID: s.instanceID, admin: true, activeWorkerRequired: true} + if err := s.authorize(ctx, tx, scope, "admin"); err != nil { + return Scope{}, err + } + if err := CheckActiveWorker(ctx, tx, project, worker); err != nil { + return Scope{}, err + } + return scope, nil +} diff --git a/internal/core/project_automation_test.go b/internal/core/project_automation_test.go new file mode 100644 index 000000000..dca214f87 --- /dev/null +++ b/internal/core/project_automation_test.go @@ -0,0 +1,210 @@ +package core + +import ( + "context" + "database/sql" + "encoding/json" + "net/http/httptest" + "strings" + "testing" +) + +func automationFixture(t *testing.T) (*Store, Scope) { + t.Helper() + s, scope, _ := streamFixture(t) + _, err := s.DB().Exec(`UPDATE grants SET can_manage=1 WHERE credential_id='credential'; +INSERT INTO projects VALUES('foreign','Foreign',2,'synthetic/foreign'); +INSERT INTO workers VALUES('foreign','foreign-worker','Foreign worker'); +INSERT INTO credentials VALUES('alternate','alternate-principal',?,0,0); +INSERT INTO grants(credential_id,project_id,can_read,can_write,can_manage) VALUES('alternate','project',1,1,1)`, tokenHash("synthetic-alternate-automation-token")) + if err != nil { + t.Fatal(err) + } + return s, scope.RequireAdministration() +} + +func automationTx(t *testing.T, s *Store) *sql.Tx { + t.Helper() + tx, err := s.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = tx.Rollback() }) + return tx +} + +func TestAuthenticatedCredentialIDRetainsExactIdentityAndScopeCeilings(t *testing.T) { + s, scope := automationFixture(t) + if _, err := s.DB().Exec(`INSERT INTO credentials VALUES('duplicate','principal',?,0,0)`, tokenHash("synthetic-duplicate-principal-token")); err == nil { + t.Fatal("canonical schema permitted alternate credentials for one principal") + } + for _, tc := range []struct{ token, id string }{{"synthetic-core-stream-token-1234567", "credential"}, {"synthetic-alternate-automation-token", "alternate"}} { + r := httptest.NewRequest("GET", "/", nil) + r.SetPathValue("project_id", "project") + r.Header.Set("Authorization", "Bearer "+tc.token) + r.Header.Set("X-FC-Worker", "worker") + authenticated, err := s.AdminScope(r) + if err != nil { + t.Fatal(err) + } + tx := automationTx(t, s) + id, err := s.AuthenticatedCredentialID(t.Context(), tx, authenticated) + _ = tx.Rollback() + if err != nil || id != tc.id || strings.Contains(id, tc.token) || id == tokenHash(tc.token) { + t.Fatal("authenticated credential was substituted or exposed secret material", err) + } + } + for _, tc := range []struct { + name, code, query string + change func(*Scope) + }{ + {"unauthenticated", "unauthorized", "", func(v *Scope) { *v = Scope{ProjectID: "project", PrincipalID: "principal", WorkerID: "worker"} }}, + {"principal", "unauthorized", "", func(v *Scope) { v.PrincipalID = "another-principal" }}, + {"instance", "unauthorized", "", func(v *Scope) { v.instanceID = "another-instance" }}, + {"project", "forbidden", "", func(v *Scope) { v.ProjectID, v.WorkerID = "foreign", "foreign-worker" }}, + {"revoked-original", "unauthorized", `UPDATE credentials SET revoked=1 WHERE id='credential'`, func(*Scope) {}}, + {"demoted-original", "forbidden", `UPDATE grants SET can_manage=0 WHERE credential_id='credential'`, func(*Scope) {}}, + } { + t.Run(tc.name, func(t *testing.T) { + forged := scope + tc.change(&forged) + tx := automationTx(t, s) + if tc.query != "" { + if _, err := tx.ExecContext(t.Context(), tc.query); err != nil { + t.Fatal(err) + } + } + id, err := s.AuthenticatedCredentialID(t.Context(), tx, forged) + browserCoreCode(t, err, tc.code) + if id != "" { + t.Fatal("refused scope received a credential identity") + } + }) + } + // A browser read may identify its own credential, but identifying it must + // not remove its original read-only ceiling after a later role upgrade. + browserStore, _, _ := streamFixture(t) + id, cookie := browserCoreSession(t, browserStore) + browser, err := browserStore.Scope(browserCoreRequest(browserStore, id, cookie), "read") + if err != nil { + t.Fatal(err) + } + if _, err := browserStore.DB().Exec(`UPDATE grants SET can_write=1,can_manage=1 WHERE credential_id='credential'`); err != nil { + t.Fatal(err) + } + tx := automationTx(t, browserStore) + credential, err := browserStore.AuthenticatedCredentialID(t.Context(), tx, browser) + if err != nil || credential != "credential" || !browser.readOnly || browser.Administrative() { + t.Fatal("identity lookup changed the attenuated browser scope", err) + } + _, err = browserStore.AuthenticatedCredentialID(t.Context(), tx, browser.RequireAdministration()) + browserCoreCode(t, err, "forbidden") +} + +func TestProjectAutomationScopeRequiresExactCurrentManagementAndActiveWorker(t *testing.T) { + s, _ := automationFixture(t) + for _, tc := range []struct { + name, project, principal, worker, credential, query, code string + }{ + {name: "valid"}, + {name: "instance-administrator", query: `UPDATE grants SET can_manage=0 WHERE credential_id='credential'; UPDATE credentials SET is_admin=1 WHERE id='credential'`}, + {name: "missing-credential", credential: "missing", code: "forbidden"}, + {name: "wrong-principal", principal: "another-principal", code: "forbidden"}, + {name: "foreign-credential", credential: "alternate", code: "forbidden"}, + {name: "replaced-credential", query: `DELETE FROM grants WHERE credential_id='credential'; DELETE FROM credentials WHERE id='credential'; INSERT INTO credentials VALUES('replacement','principal','` + tokenHash("synthetic-replacement-token") + `',0,0); INSERT INTO grants(credential_id,project_id,can_read,can_write,can_manage) VALUES('replacement','project',1,1,1)`, code: "forbidden"}, + {name: "foreign-project", project: "foreign", worker: "foreign-worker", code: "forbidden"}, + {name: "missing-project", project: "missing", code: "not_found"}, + {name: "missing-worker", worker: "missing", code: "not_found"}, + {name: "foreign-worker", worker: "foreign-worker", code: "not_found"}, + {name: "revoked-original", query: `UPDATE credentials SET revoked=1 WHERE id='credential'`, code: "forbidden"}, + {name: "demoted-original", query: `UPDATE grants SET can_manage=0 WHERE credential_id='credential'`, code: "forbidden"}, + {name: "retired-worker", query: `INSERT INTO worker_retirements VALUES('project','worker','2026-11-01T00:00:00Z','synthetic-actor')`, code: "worker_retired"}, + } { + t.Run(tc.name, func(t *testing.T) { + project, principal, worker, credential := "project", "principal", "worker", "credential" + if tc.project != "" { + project = tc.project + } + if tc.principal != "" { + principal = tc.principal + } + if tc.worker != "" { + worker = tc.worker + } + if tc.credential != "" { + credential = tc.credential + } + tx := automationTx(t, s) + if tc.query != "" { + if _, err := tx.ExecContext(t.Context(), tc.query); err != nil { + t.Fatal(err) + } + } + background, err := s.ProjectAutomationScope(t.Context(), tx, project, principal, worker, credential) + if tc.code != "" { + browserCoreCode(t, err, tc.code) + if background != (Scope{}) { + t.Fatal("refused automation returned authority") + } + return + } + if err != nil || background.ProjectID != project || background.PrincipalID != principal || background.WorkerID != worker || !background.Administrative() { + t.Fatal("background scope lost exact management attribution", err) + } + id, err := s.AuthenticatedCredentialID(t.Context(), tx, background) + if err != nil || id != credential { + t.Fatal("background scope selected an alternate credential", err) + } + encoded, err := json.Marshal(background) + if err != nil || strings.Contains(string(encoded), background.tokenHash) || strings.Contains(string(encoded), "synthetic-core-stream-token") { + t.Fatal("background scope exposed authentication material", err) + } + }) + } + for _, tuple := range [][4]string{{"", "principal", "worker", "credential"}, {"project", "", "worker", "credential"}, {"project", "principal", "", "credential"}, {"project", "principal", "worker", ""}} { + tx := automationTx(t, s) + _, err := s.ProjectAutomationScope(t.Context(), tx, tuple[0], tuple[1], tuple[2], tuple[3]) + _ = tx.Rollback() + browserCoreCode(t, err, "forbidden") + } +} + +func TestProjectAutomationScopeReauthorizesAtNormalStoreBoundaries(t *testing.T) { + s, _ := automationFixture(t) + tx := automationTx(t, s) + background, err := s.ProjectAutomationScope(t.Context(), tx, "project", "principal", "worker", "credential") + _ = tx.Rollback() + if err != nil { + t.Fatal(err) + } + mutation := Mutation{Operation: "test.automation", Target: "local-control", Key: "original-automation-key", Request: struct{}{}} + if _, err := s.Mutate(t.Context(), background, mutation, func(context.Context, *sql.Tx) (any, error) { return map[string]string{"outcome": "stored"}, nil }); err != nil { + t.Fatal("current background management scope was unusable", err) + } + for _, tc := range []struct{ query, reset, code string }{ + {`INSERT INTO worker_retirements VALUES('project','worker','2026-11-01T00:00:00Z','synthetic-actor')`, `DELETE FROM worker_retirements`, "worker_retired"}, + {`UPDATE grants SET can_manage=0 WHERE credential_id='credential'`, `UPDATE grants SET can_manage=1 WHERE credential_id='credential'`, "forbidden"}, + {`UPDATE credentials SET revoked=1 WHERE id='credential'`, `UPDATE credentials SET revoked=0 WHERE id='credential'`, "unauthorized"}, + } { + if _, err := s.DB().Exec(tc.query); err != nil { + t.Fatal(err) + } + called := false + err := s.Read(t.Context(), background, func(context.Context, *sql.Tx) error { called = true; return nil }) + browserCoreCode(t, err, tc.code) + _, err = s.Mutate(t.Context(), background, mutation, func(context.Context, *sql.Tx) (any, error) { called = true; return nil, nil }) + browserCoreCode(t, err, tc.code) + fresh := mutation + fresh.Key = "new-automation-key" + _, err = s.Mutate(t.Context(), background, fresh, func(context.Context, *sql.Tx) (any, error) { called = true; return nil, nil }) + browserCoreCode(t, err, tc.code) + _, _, err = s.Replay(t.Context(), background, mutation) + browserCoreCode(t, err, tc.code) + if called { + t.Fatal("stale authorization entered a Store callback") + } + if _, err := s.DB().Exec(tc.reset); err != nil { + t.Fatal(err) + } + } +} diff --git a/internal/core/types.go b/internal/core/types.go index c3213e73a..570e48f63 100644 --- a/internal/core/types.go +++ b/internal/core/types.go @@ -11,17 +11,18 @@ import ( ) type Scope struct { - PrincipalID string - ProjectID string - WorkerID string - tokenHash string - instanceID string - admin bool - instanceAdmin bool - readOnly bool - expiresAt time.Time - sessionManage bool - sessionProject string + PrincipalID string + ProjectID string + WorkerID string + tokenHash string + instanceID string + admin bool + activeWorkerRequired bool + instanceAdmin bool + readOnly bool + expiresAt time.Time + sessionManage bool + sessionProject string } type Mutation struct { diff --git a/internal/reviewexec/adoption_holds_integration_test.go b/internal/reviewexec/adoption_holds_integration_test.go index 8fb789629..e6c787f3d 100644 --- a/internal/reviewexec/adoption_holds_integration_test.go +++ b/internal/reviewexec/adoption_holds_integration_test.go @@ -631,12 +631,43 @@ func TestAdoptionHoldsIntegrationSupervisorSettlesRepositoryChangeDuringPrepare( }} err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}) if corrupt { - attemptCode(t, err, "review_persistence_failed") - if op := roundOperation(t, f, receipt.ID); op.State == "held" { - t.Fatal("storage corruption was disguised as a normal policy hold", op) + op := roundOperation(t, f, receipt.ID) + if err != nil || op.State != "queued" || op.Reason != "automatic_scheduling_unavailable" || op.AttemptID != "" || op.ID != receipt.ID || preparing.ID == "" { + t.Fatal("typed project corruption lost its queued intent", op, err) } - if driver.calls.Load() != 0 { - t.Fatal("corrupt retained source reached dispatch") + if driver.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("corrupt retained source reached dispatch or leaked reservation") + } + // Detached corruption holds must remain covered by restore validation. + tx, txErr := f.store.DB().BeginTx(t.Context(), nil) + if txErr != nil { + t.Fatal(txErr) + } + if err := ValidateOperationWaitsSnapshot(t.Context(), tx); err != nil { + t.Fatal("valid detached hold", err) + } + tx.Rollback() + if _, err := f.store.DB().Exec(`UPDATE review_execution_attempts SET external_id='unexpected-provider-effect' WHERE id=?`, preparing.ID); err != nil { + t.Fatal(err) + } + tx, txErr = f.store.DB().BeginTx(t.Context(), nil) + if txErr != nil { + t.Fatal(txErr) + } + if err := ValidateOperationWaitsSnapshot(t.Context(), tx); err == nil { + t.Fatal("restore skipped corrupt detached scheduling hold") + } + tx.Rollback() + if _, err := f.store.DB().Exec(`UPDATE review_execution_attempts SET external_id='' WHERE id=?`, preparing.ID); err != nil { + t.Fatal(err) + } + f.configure(t, otherAttemptProject, "test-capability", 0, false) + f.enqueue(t, otherAttemptProject, "other-after-corrupt-source", channel, 2, 1) + other := &controlledDriver{dispatch: func(_ context.Context, _ Operation, _ Attempt, _ func(context.Context, string) error) (Result, error) { + return Result{State: "failed", Reason: "synthetic_no_post"}, nil + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": other}); err != nil || other.calls.Load() != 1 { + t.Fatal("corrupt source starved healthy project", err, other.calls.Load()) } return } @@ -669,3 +700,38 @@ func TestAdoptionHoldsIntegrationSupervisorSettlesRepositoryChangeDuringPrepare( } } } + +func TestSchedulingCorruptionContinuesHealthyCandidateInSamePass(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + f.enqueue(t, attemptProject, "first-corrupt", channel, 2, 1) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + f.enqueue(t, otherAttemptProject, "later-healthy", channel, 2, 1) + corruptPrepared := false + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + if o.ProjectID == attemptProject { + corruptPrepared = true + integrationImportHold(t, f, o.PullNumber) + if _, err := f.store.DB().Exec(`UPDATE review_adoption_obligations SET revision=2 WHERE project_id=?`, o.ProjectID); err != nil { + t.Fatal(err) + } + } + intent := "" + if channel == "hosted" { + intent = "synthetic-unposted-intent" + } + return Preparation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber), Intent: intent}, nil + }, dispatch: func(_ context.Context, o Operation, _ Attempt, _ func(context.Context, string) error) (Result, error) { + if !corruptPrepared || o.ProjectID != otherAttemptProject { + t.Fatal("unexpected dispatch order or corrupt dispatch", o.ProjectID) + } + return Result{State: "failed", Reason: "synthetic_no_post"}, nil + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil || driver.calls.Load() != 1 { + t.Fatal("same pass starved later healthy candidate", err, driver.calls.Load()) + } + }) + } +} diff --git a/internal/reviewexec/allowance_observation.go b/internal/reviewexec/allowance_observation.go index ba197f0aa..f24d2e9ff 100644 --- a/internal/reviewexec/allowance_observation.go +++ b/internal/reviewexec/allowance_observation.go @@ -27,6 +27,7 @@ const ( storedReviewAdmission storedConfigurationHistory storedOperationIdentity + storedRoundHistory ) type storedUnavailableError struct { @@ -78,7 +79,7 @@ func readCLIAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation, a var err error var draft bool var historical Operation - historical, draft, err = historicalCLIDraftOperation(ctx, q, o, a) + historical, draft, err = historicalUnusedPreparationOperation(ctx, q, o, a, true) if err == nil { if draft { o = historical @@ -107,6 +108,12 @@ func readCLIAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation, a } func readHostedAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (hostedAllowanceRecord, error) { + return readHostedAllowanceRecordForHistory(ctx, q, o, a, false) +} + +// Scheduling detachment is attribution for snapshot inspection only. Live +// allowance and query readers do not use it to authorize or recover actions. +func readHostedAllowanceRecordForHistory(ctx context.Context, q EvidenceQuery, o Operation, a Attempt, snapshot bool) (hostedAllowanceRecord, error) { var project, attempt string var body sql.NullString err := q.QueryRowContext(ctx, `SELECT project_id,attempt_id,CASE WHEN typeof(body_json)='text' AND length(CAST(body_json AS BLOB))<=16384 THEN body_json END FROM review_hosted_preflight WHERE attempt_id=?`, a.ID).Scan(&project, &attempt, &body) @@ -120,10 +127,22 @@ func readHostedAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation return hostedAllowanceRecord{}, allowanceUnavailable() } if o.AttemptID != a.ID { - var err error - o, err = historicalCooldownOperation(ctx, q, o, a) - if err != nil { - return hostedAllowanceRecord{}, allowanceDependencyError(err) + var retained bool + if snapshot && o.Channel == "hosted" { + var historical Operation + historical, retained, err = historicalUnusedPreparationOperation(ctx, q, o, a, true) + if err != nil { + return hostedAllowanceRecord{}, allowanceDependencyError(err) + } + if retained { + o = historical + } + } + if !retained { + o, err = historicalCooldownOperation(ctx, q, o, a) + if err != nil { + return hostedAllowanceRecord{}, allowanceDependencyError(err) + } } } if !validAllowanceOwners(o, a) { @@ -289,7 +308,7 @@ func ValidateAllowanceSnapshot(ctx context.Context, q EvidenceQuery, executionVe if table == "review_cli_preflight" { _, err = readCLIAllowanceRecord(ctx, q, o, a) } else { - _, err = readHostedAllowanceRecord(ctx, q, o, a) + _, err = readHostedAllowanceRecordForHistory(ctx, q, o, a, true) } if err != nil { return err diff --git a/internal/reviewexec/attempt_projection.go b/internal/reviewexec/attempt_projection.go index b2e68f58f..af0b052aa 100644 --- a/internal/reviewexec/attempt_projection.go +++ b/internal/reviewexec/attempt_projection.go @@ -69,7 +69,7 @@ func publishJournalAttempt(ctx context.Context, tx *sql.Tx, attempt Attempt, met } if operation.AttemptID != attempt.ID { // History may retain an unused preparation that detached before dispatch. - original, draft, err := historicalCLIDraftOperation(ctx, tx, operation, attempt) + original, draft, err := historicalUnusedPreparationOperation(ctx, tx, operation, attempt, true) if err != nil { if errors.Is(err, sql.ErrNoRows) || isWaitUnavailable(err) { return reviews.Receipt{}, publicationConflict() diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index ddc842326..fd272f9e8 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -95,6 +95,20 @@ func (e *Engine) startAttempt(ctx context.Context, project, id string, draftRead if o.Wait != nil && (o.Wait.Paused || o.Wait.RetryNotBefore != "" && now.Before(mustWaitTime(o.Wait.RetryNotBefore))) { return nil } + scheduling, err := readPullScheduling(ctx, tx, project, o.PullNumber) + if err != nil { + return err + } + if scheduling.Paused { + return nil + } + if err := e.requireAutomaticOperation(ctx, tx, o); err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Status == 403 { + return nil + } + return err + } at, err := attemptRecordingStamp(ctx, tx, o, nil, e.sampleAttemptTime()) if err != nil { return err @@ -240,6 +254,15 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision if anchor.PullNumber != o.PullNumber || anchor.CandidateSHA != o.HeadSHA { return conflict() } + // Preparation may have overlapped a PR pause or a withdrawal of the + // automatic intent's authority. Recheck in this admission transaction, + // before recording a possibly issued action. + if err := requirePullScheduling(ctx, tx, project, o.PullNumber); err != nil { + return err + } + if err := e.requireAutomaticOperation(ctx, tx, o); err != nil { + return err + } if err := requireSourceObligationsClear(ctx, tx, project, o.PullNumber); err != nil { return err } @@ -375,7 +398,9 @@ func (e *Engine) Advance(ctx context.Context, project, id string, expectedRevisi return err } operationState, operationAttempt := state, o.AttemptID - if o.Channel == "cli" && reason == cliDraftWait && state == "held" && o.State == "preparing" && o.AttemptID == a.ID && a.Anchor == nil && a.Intent == "" && a.ExternalID == "" { + // Only an unused preparation may detach and retain the same queued intent. + retainQueued := o.Channel == "cli" && reason == cliDraftWait || reason == "pull_scheduling_paused" || reason == "automation_authorization_changed" || reason == "automatic_scheduling_unavailable" + if retainQueued && state == "held" && o.State == "preparing" && o.AttemptID == a.ID && a.Anchor == nil && a.Intent == "" && a.ExternalID == "" { operationState, operationAttempt = "queued", "" } if _, err = tx.ExecContext(ctx, `UPDATE review_operations SET state=?,revision=revision+1,reason=?,attempt_id=?,updated_at=? WHERE id=?`, operationState, reason, operationAttempt, at, a.OperationID); err != nil { diff --git a/internal/reviewexec/carried_obligations.go b/internal/reviewexec/carried_obligations.go index 995854343..d185e6869 100644 --- a/internal/reviewexec/carried_obligations.go +++ b/internal/reviewexec/carried_obligations.go @@ -22,9 +22,28 @@ func requireSourceObligationsClear(ctx context.Context, tx *sql.Tx, project stri return nil } -func sourceObligationCount(ctx context.Context, tx *sql.Tx, project string, pull int64) (int64, error) { +// The automatic dependency count is distinct from the admission guard above. +func sourceObligationCount(ctx context.Context, tx adoptionholds.Query, project string, pull int64) (int64, error) { facts, err := adoptionholds.ReadFacts(ctx, tx, project, pull) - return facts.Open, sourceObligationReadError(err) + refusal := sourceObligationReadError(err) + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "repository_changed" { + // A retained binding mismatch prevents planning only for this project. + // Keep the public source hold and do not enter unused-attempt recovery. + return 0, &automaticProjectStateError{refusal} + } + return facts.Open, refusal +} + +// Preserve the existing unused-attempt recovery for typed carried-obligation +// storage faults without classifying other project-local history as scheduling. +type sourceObligationProjectStateError struct{ error } + +func (e *sourceObligationProjectStateError) Unwrap() error { return e.error } + +func isSourceObligationProjectStateError(err error) bool { + var source *sourceObligationProjectStateError + return errors.As(err, &source) } func sourceObligationReadError(err error) error { @@ -32,5 +51,8 @@ func sourceObligationReadError(err error) error { if errors.As(err, &failure) && failure.Code == "repository_changed" { return sourceHold("repository_changed") } + if adoptionholds.IsProjectStateError(err) { + return &sourceObligationProjectStateError{&automaticProjectStateError{err}} + } return err } diff --git a/internal/reviewexec/cli_coverage.go b/internal/reviewexec/cli_coverage.go index 9df50dcb2..76786551b 100644 --- a/internal/reviewexec/cli_coverage.go +++ b/internal/reviewexec/cli_coverage.go @@ -83,7 +83,7 @@ func channelProgress(ctx context.Context, tx *sql.Tx, project string, repository return ComparisonState{}, err } if dirty { - return ComparisonState{}, adjudicationStorageError() + return ComparisonState{}, &automaticProjectStateError{adjudicationStorageError()} } c, err := readRoundControl(ctx, tx, project, number, channel) if err != nil { diff --git a/internal/reviewexec/cli_draft_wait.go b/internal/reviewexec/cli_draft_wait.go index fed5ea605..fbec0f85b 100644 --- a/internal/reviewexec/cli_draft_wait.go +++ b/internal/reviewexec/cli_draft_wait.go @@ -88,6 +88,9 @@ func (e *Engine) checkCLIDraft(ctx context.Context, o Operation, drivers map[str if current.State != "queued" || current.Revision != o.Revision { return conflict() } + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + return err + } if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections WHERE project_id=? AND operation_id=?)`, o.ProjectID, o.ID).Scan(&selected); err != nil || selected { return err } @@ -97,6 +100,9 @@ func (e *Engine) checkCLIDraft(ctx context.Context, o Operation, drivers map[str if err != nil { var refusal *core.Error if errors.As(err, &refusal) { + if refusal.Code == linkedSelectionCustodyHeld { + return false, false, false, err + } if refusal.Code == "overloaded" { // The worker still defers this row but must not acknowledge // exhausted work when storage prevented the readiness read. @@ -211,14 +217,21 @@ func (e *Engine) recordCLIDraftDecision(ctx context.Context, o Operation, reason // historicalCLIDraftOperation identifies an unused preparation detached when // GitHub returned the PR to Draft. It supplies attribution for history only. func historicalCLIDraftOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (Operation, bool, error) { + return historicalUnusedPreparationOperation(ctx, q, o, a, false) +} + +// historicalUnusedPreparationOperation verifies detached draft and scheduling +// holds without inventing provider evidence or changing the current operation. +func historicalUnusedPreparationOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt, scheduling bool) (Operation, bool, error) { var reason string if err := q.QueryRowContext(ctx, `SELECT reason FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&reason); err != nil { return Operation{}, false, err } - if reason != cliDraftWait { + draft := reason == cliDraftWait + if !draft && !(scheduling && (reason == "pull_scheduling_paused" || reason == "automation_authorization_changed" || reason == "automatic_scheduling_unavailable")) { return Operation{}, false, nil } - if o.Channel != "cli" || a.OperationID != o.ID || a.ProjectID != o.ProjectID || a.ID == o.AttemptID || a.State != "held" || a.Revision != 2 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { + if draft && o.Channel != "cli" || a.OperationID != o.ID || a.ProjectID != o.ProjectID || a.ID == o.AttemptID || a.State != "held" || a.Revision != 2 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { return Operation{}, false, waitUnavailable() } var startedAt, heldAt string @@ -239,17 +252,17 @@ func historicalCLIDraftOperation(ctx context.Context, q EvidenceQuery, o Operati if occupied || !validStart || !validHold || held.Before(started) { return Operation{}, false, waitUnavailable() } - o.AttemptID, o.State, o.Reason, o.Wait = a.ID, "held", cliDraftWait, nil - // A fresh draft observation can detach an unused positive permit. Validate - // its original attribution without granting it authority to dispatch. Corrupt - // optional allowance cannot prevent history-only projection of this proven - // unused attempt; operational lookup failures still abort the transaction. - record, err := readCLIAllowanceRecord(ctx, q, o, a) - if err != nil && !errors.Is(err, errAllowanceObservationAbsent) && !storedAllowanceUnavailable(err) { - return Operation{}, false, err - } - if err == nil && record.Observation.Remaining <= 0 { - return Operation{}, false, waitUnavailable() + o.AttemptID, o.State, o.Reason, o.Wait = a.ID, "held", reason, nil + if draft { + // A fresh draft observation can detach an unused positive permit. Validate + // its original attribution without granting it authority to dispatch. + record, err := readCLIAllowanceRecord(ctx, q, o, a) + if err != nil && !errors.Is(err, errAllowanceObservationAbsent) && !storedAllowanceUnavailable(err) { + return Operation{}, false, err + } + if err == nil && record.Observation.Remaining <= 0 { + return Operation{}, false, waitUnavailable() + } } return o, true, nil } diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go index 329342623..9a04970a8 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -73,6 +73,20 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i if state.RoundsConfigured && state.RoundsComplete || !state.RoundsConfigured && state.Covered { return evaluatedFront{state: "complete", plan: plan}, nil } + scheduling, err := readPullScheduling(ctx, q, r.ProjectID, plan.Pull.Number) + if err != nil { + return evaluatedFront{}, err + } + if scheduling.Paused { + return evaluatedFront{state: "held", reason: "pull_scheduling_paused", plan: plan}, nil + } + suppressed, err := e.automaticPullSuppressed(ctx, q, r, plan.Pull.Number) + if err != nil { + return evaluatedFront{}, err + } + if suppressed { + return evaluatedFront{state: "held", reason: "automatic_intent_retained", plan: plan}, nil + } if plan.Pull.State != "open" { return evaluatedFront{state: "held", reason: "front_unavailable", plan: plan}, nil } 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..0f6f9b948 --- /dev/null +++ b/internal/reviewexec/hosted_detached_preflight_snapshot_test.go @@ -0,0 +1,60 @@ +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) + } + 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/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 4d893ccc7..4ace0da9a 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -92,6 +92,14 @@ ORDER BY q.key,o.created_at,o.id`, string(queue), position, o.ProjectID, o.Chann } func (e *Engine) hostedPriorityBinding(ctx context.Context, tx *sql.Tx, o Operation) (bool, error) { + // A proved custody hold is already ineligible; do not let it consult or + // block unrelated source or provider evidence. + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + if isLinkedSelectionCustodyHeld(err) { + return false, nil + } + return false, err + } var err error if o.Channel == "hosted" { var installed bool diff --git a/internal/reviewexec/hosted_priority_test.go b/internal/reviewexec/hosted_priority_test.go index f59534fbd..90b37f4f6 100644 --- a/internal/reviewexec/hosted_priority_test.go +++ b/internal/reviewexec/hosted_priority_test.go @@ -373,3 +373,36 @@ func TestConfigurationHistoryIsolationIsTypedAndBounded(t *testing.T) { t.Fatal("diagnostic throttle did not expire") } } + +// Automatic-planning damage and queued configuration-history damage belong to +// different local isolation boundaries even when their public error is equal. +func TestConfigurationHistoryAndAutomaticFailureMarkersStayDistinct(t *testing.T) { + e := &Engine{} + op := Operation{ID: "review_operation_candidate", ProjectID: "project"} + for _, tc := range []struct { + name string + err error + automatic bool + history bool + }{ + {"automatic", automaticProjectStateFailure("storage_unavailable", "Retained state unavailable.", 500), true, false}, + {"history", newStoredUnavailable(storedConfigurationHistory, "Retained state unavailable."), false, true}, + {"admission", newStoredUnavailable(storedReviewAdmission, "Retained state unavailable."), false, false}, + {"operational", core.Fail("storage_unavailable", "Retained state unavailable.", 500), false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, err := range []error{tc.err, fmt.Errorf("wrapped: %w", tc.err)} { + if automaticProjectRefused(err) != tc.automatic || isStoredUnavailable(err, storedConfigurationHistory) != tc.history { + t.Fatal("local failure boundaries overlapped", err) + } + if !tc.history && e.skipUnavailableConfiguration(t.Context(), op, err) { + t.Fatal("unrelated failure became queued configuration damage", err) + } + var failure *core.Error + if !errors.As(err, &failure) || failure.Code != "storage_unavailable" || failure.Status != 500 { + t.Fatal("public failure contract changed", err) + } + } + }) + } +} diff --git a/internal/reviewexec/hosted_wait.go b/internal/reviewexec/hosted_wait.go index 91afc8f9c..bcf98a723 100644 --- a/internal/reviewexec/hosted_wait.go +++ b/internal/reviewexec/hosted_wait.go @@ -93,18 +93,21 @@ func readOperationWait(ctx context.Context, q EvidenceQuery, o Operation) (*Oper } var result OperationWait var baseline sql.NullString - var paused int64 - err = q.QueryRowContext(ctx, `SELECT baseline_attempt_id,retry_not_before,paused FROM review_operation_waits WHERE operation_id=?`, o.ID).Scan(&baseline, &result.RetryNotBefore, &paused) + var rawPaused any + err = q.QueryRowContext(ctx, `SELECT baseline_attempt_id,retry_not_before,paused FROM review_operation_waits WHERE operation_id=?`, o.ID).Scan(&baseline, &result.RetryNotBefore, &rawPaused) if errors.Is(err, sql.ErrNoRows) { return nil, nil } if err != nil { return nil, err } - result.BaselineAttemptID, result.Paused = baseline.String, paused == 1 - if paused != 0 && paused != 1 || baseline.Valid != (result.RetryNotBefore != "") || baseline.Valid && (!hostedObservationID(baseline.String, "review_attempt_") || !validChannel(o.Channel)) { + // Inspect the native value before database/sql can coerce it or turn + // malformed retained data into a generic conversion error. + paused, integer := rawPaused.(int64) + if !integer || paused != 0 && paused != 1 || baseline.Valid != (result.RetryNotBefore != "") || baseline.Valid && (!hostedObservationID(baseline.String, "review_attempt_") || !validChannel(o.Channel)) { return nil, waitUnavailable() } + result.BaselineAttemptID, result.Paused = baseline.String, paused == 1 if baseline.Valid { if _, ok := hostedObservationTime(result.RetryNotBefore); !ok { return nil, waitUnavailable() diff --git a/internal/reviewexec/hosted_wait_test.go b/internal/reviewexec/hosted_wait_test.go index b47eb6cf2..b5a37d24f 100644 --- a/internal/reviewexec/hosted_wait_test.go +++ b/internal/reviewexec/hosted_wait_test.go @@ -78,7 +78,16 @@ func TestCooldownSchemaRetainsDependentRows(t *testing.T) { func snapshotTable(t *testing.T, f *attemptFixture, table string) string { t.Helper() - rows, err := f.store.DB().Query(`SELECT * FROM ` + table + ` ORDER BY rowid`) + return snapshotTableThrough(t, f.store.DB(), table) +} + +type snapshotTableReader interface { + QueryContext(context.Context, string, ...any) (*sql.Rows, error) +} + +func snapshotTableThrough(t *testing.T, reader snapshotTableReader, table string) string { + t.Helper() + rows, err := reader.QueryContext(t.Context(), `SELECT * FROM `+table+` ORDER BY rowid`) if err != nil { t.Fatal(err) } diff --git a/internal/reviewexec/hosted_wait_validation.go b/internal/reviewexec/hosted_wait_validation.go index b7e217b6d..00c9225d0 100644 --- a/internal/reviewexec/hosted_wait_validation.go +++ b/internal/reviewexec/hosted_wait_validation.go @@ -18,6 +18,7 @@ func ValidateOperationWaitsSnapshot(ctx context.Context, tx *sql.Tx) error { LEFT JOIN review_operations o ON o.id=a.operation_id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE (o.id IS NULL OR o.attempt_id<>a.id) AND t.reason IN ('allowance_exhausted','hosted_allowance_cooldown') + UNION SELECT o.project_id,o.id FROM review_operations o JOIN review_execution_attempts a ON a.operation_id=o.id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE a.id<>o.attempt_id AND t.reason IN ('pull_scheduling_paused','automation_authorization_changed','automatic_scheduling_unavailable') ORDER BY 2`, cliDraftWait, cliDraftWait) if err != nil { return err @@ -76,7 +77,7 @@ func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) } var firstDeadline, lastDeadline, baselineDeadline time.Time foundCurrent := o.AttemptID == "" - foundDraft := false + foundDetached, foundDraft := false, false for _, id := range ids { a, err := readAttempt(ctx, tx, o.ProjectID, id) if err != nil { @@ -95,15 +96,16 @@ func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) } continue } - _, draft, err := historicalCLIDraftOperation(ctx, tx, o, a) + historicalUnused, unused, err := historicalUnusedPreparationOperation(ctx, tx, o, a, true) if err != nil { if errors.Is(err, sql.ErrNoRows) { return waitUnavailable() } return err } - if draft { - foundDraft = true + if unused { + foundDetached = true + foundDraft = foundDraft || historicalUnused.Reason == cliDraftWait continue } if !hasBaseline { @@ -173,7 +175,7 @@ func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) return waitUnavailable() } } - if !foundCurrent || o.Wait == nil && !foundDraft { + if !foundCurrent || o.Wait == nil && !foundDetached || o.Reason == cliDraftWait && !foundDraft { return waitUnavailable() } if hasBaseline { diff --git a/internal/reviewexec/http.go b/internal/reviewexec/http.go index fb7f5f2ac..f21919a8e 100644 --- a/internal/reviewexec/http.go +++ b/internal/reviewexec/http.go @@ -18,6 +18,7 @@ func (e *Engine) Register(mux *http.ServeMux) { e.registerCIWatchHTTP(mux) mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/rounds/progress", e.readRoundProgressHTTP) mux.HandleFunc("POST /api/v1/projects/{project_id}/reviews/operations/{operation_id}/control", e.controlOperationHTTP) + e.registerSchedulingHTTP(mux) mux.HandleFunc("POST /api/v1/projects/{project_id}/reviews/selections", e.enqueueRunHTTP) mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/selections/{selection_id}", e.readRunHTTP) adoptionholds.New(e.store).Register(mux) @@ -154,6 +155,7 @@ func (e *Engine) enqueueHTTP(w http.ResponseWriter, r *http.Request) { } if terminal { operation = operationForResponse(operation, r.Header.Get(operationWaitHeader)) + e.queuedResponseHeader(w, r, scope, operation.ID, operation.State, operation.Channel, operation.Revision) core.WriteJSON(w, http.StatusOK, operation) return } 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/policy.go b/internal/reviewexec/policy.go index 7bdf8cce1..eb0230529 100644 --- a/internal/reviewexec/policy.go +++ b/internal/reviewexec/policy.go @@ -112,15 +112,19 @@ func (e *Engine) ConfigurePolicy(ctx context.Context, scope core.Scope, key stri func readPolicy(ctx context.Context, tx *sql.Tx, project string) (PolicyRecord, error) { var record PolicyRecord var body string - err := tx.QueryRowContext(ctx, `SELECT project_id,revision,actor_id,created_at,body_json FROM review_policy_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, project).Scan(&record.ProjectID, &record.Revision, &record.ActorID, &record.RecordedAt, &body) + var bodyValue, revisionValue any + err := tx.QueryRowContext(ctx, `SELECT project_id,revision,actor_id,created_at,body_json FROM review_policy_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, project).Scan(&record.ProjectID, &revisionValue, &record.ActorID, &record.RecordedAt, &bodyValue) if errors.Is(err, sql.ErrNoRows) { return PolicyRecord{}, core.Fail("reviews_policy_unconfigured", "Configure explicit project review requirements before assessing policy.", 409) } if err != nil { return PolicyRecord{}, err } - if len(body) > 1024 || strictjson.Decode([]byte(body), &record.Policy) != nil || !validPolicy(record.Policy) { - return PolicyRecord{}, core.Fail("storage_unavailable", "Stored project review policy is unavailable.", 500) + var validBody, validRevision bool + body, validBody = bodyValue.(string) + record.Revision, validRevision = revisionValue.(int64) + if !validBody || !validRevision || record.Revision < 1 || len(body) > 1024 || strictjson.Decode([]byte(body), &record.Policy) != nil || !validPolicy(record.Policy) { + return PolicyRecord{}, automaticProjectStateFailure("storage_unavailable", "Stored project review policy is unavailable.", 500) } return record, nil } diff --git a/internal/reviewexec/policy_admission.go b/internal/reviewexec/policy_admission.go index 5424631f2..74dbea265 100644 --- a/internal/reviewexec/policy_admission.go +++ b/internal/reviewexec/policy_admission.go @@ -53,6 +53,12 @@ func (e *Engine) currentExecutionContext(ctx context.Context, tx *sql.Tx, operat // delay its retry without discarding it; all other authority checks still apply. func (e *Engine) executionContext(ctx context.Context, tx *sql.Tx, operation Operation, retainCooldown bool) (ExecutionContext, error) { result := ExecutionContext{Operation: operation} + if err := requirePullScheduling(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil { + return ExecutionContext{}, err + } + if err := e.requireAutomaticOperation(ctx, tx, operation); err != nil { + return ExecutionContext{}, err + } if err := requireSourceObligationsClear(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil { return ExecutionContext{}, 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/queued_diagnostic.go b/internal/reviewexec/queued_diagnostic.go index 55a9a87e6..f53e66284 100644 --- a/internal/reviewexec/queued_diagnostic.go +++ b/internal/reviewexec/queued_diagnostic.go @@ -60,6 +60,14 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, if op.ID != id || op.State != "queued" || op.Revision != revision { return nil } + if err := e.requireAutomaticOperation(ctx, tx, op); err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "automation_authorization_changed" { + cause = "automation_authorization_changed" + return nil + } + return err + } latest, latestRevision, err := readConfiguration(ctx, tx, op.ProjectID) if err != nil { return err @@ -83,6 +91,14 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, cause = "project_paused" return nil } + scheduling, err := readPullScheduling(ctx, tx, op.ProjectID, op.PullNumber) + if err != nil { + return err + } + if scheduling.Paused { + cause = "pull_scheduling_paused" + return nil + } if op.Reason == cliDraftWait { cause = cliDraftWait return nil diff --git a/internal/reviewexec/requests.go b/internal/reviewexec/requests.go index dcb4ab352..7a0ce89eb 100644 --- a/internal/reviewexec/requests.go +++ b/internal/reviewexec/requests.go @@ -133,7 +133,7 @@ func readConfiguration(ctx context.Context, tx *sql.Tx, project string) (Configu revision, revisionOK := rawRevision.(int64) body, bodyOK := rawBody.(string) if !revisionOK || revision < 1 || !bodyOK || len(body) > 8192 || strictjson.Decode([]byte(body), &c) != nil || validateConfigurationShape(c) != nil { - return c, 0, newStoredUnavailable(storedConfigurationHistory, "Stored review configuration is unavailable.") + return c, 0, &automaticProjectStateError{newStoredUnavailable(storedConfigurationHistory, "Stored review configuration is unavailable.")} } return c, revision, nil } @@ -163,6 +163,9 @@ const ( // enqueueRequestTx preserves ordinary admission inside a selection child transaction. func (e *Engine) enqueueRequestTx(ctx context.Context, tx *sql.Tx, scope core.Scope, r Request) (Receipt, error) { + if err := requirePullScheduling(ctx, tx, scope.ProjectID, r.PullNumber); err != nil { + return Receipt{}, err + } c, revision, err := readConfiguration(ctx, tx, scope.ProjectID) if err != nil { return Receipt{}, err diff --git a/internal/reviewexec/round_controls.go b/internal/reviewexec/round_controls.go index 52a21a56e..26c9eada9 100644 --- a/internal/reviewexec/round_controls.go +++ b/internal/reviewexec/round_controls.go @@ -78,7 +78,7 @@ AND NOT EXISTS(SELECT 1 FROM review_round_operation_bindings b WHERE b.operation AND (p.state='dirty' OR (json_extract(e.body_json,'$.capture.review.Complete')=1 AND json_extract(e.body_json,'$.capture.review.Outcome')='completed' AND COALESCE(json_extract(s.body_json,'$.finalized'),0)=0)) LIMIT 1` func roundUnavailable() error { - return core.Fail("storage_unavailable", "Stored review round controls are unavailable.", 500) + return newStoredUnavailable(storedRoundHistory, "Stored review round controls are unavailable.") } func roundDenied(code, message string) error { return core.Fail(code, message, 409) } func roundScope(project string, pull int64, channel string) bool { @@ -124,7 +124,7 @@ func readRoundRecordVersion(ctx context.Context, q EvidenceQuery, project string } else if version == 2 { columns = roundColumnsV2 + `,0` } - err := q.QueryRowContext(ctx, `SELECT `+columns+` FROM review_round_controls WHERE project_id=? AND pull_number=? AND channel=?`, project, pull, channel).Scan(&c.ProjectID, &c.PullNumber, &c.Channel, &c.Revision, &c.Epoch, &c.grantRevision, &c.Closed, &c.Minimum, &c.Maximum, &c.Taper, &c.Used, &c.Dry, &c.Tapered, &c.ActorID, &c.CreatedAt, &c.UpdatedAt, &c.InitialDry, &c.InitiallyTapered, &c.OriginSource, &c.OriginKey, &c.OriginSHA256, &c.MaximumUnbounded) + err := scanRoundValues(q.QueryRowContext(ctx, `SELECT `+columns+` FROM review_round_controls WHERE project_id=? AND pull_number=? AND channel=?`, project, pull, channel), &c.ProjectID, &c.PullNumber, &c.Channel, &c.Revision, &c.Epoch, &c.grantRevision, &c.Closed, &c.Minimum, &c.Maximum, &c.Taper, &c.Used, &c.Dry, &c.Tapered, &c.ActorID, &c.CreatedAt, &c.UpdatedAt, &c.InitialDry, &c.InitiallyTapered, &c.OriginSource, &c.OriginKey, &c.OriginSHA256, &c.MaximumUnbounded) if errors.Is(err, sql.ErrNoRows) { return c, nil } @@ -133,27 +133,30 @@ func readRoundRecordVersion(ctx context.Context, q EvidenceQuery, project string } c.Configured = true var grantBody, latestBody string - if err := q.QueryRowContext(ctx, `SELECT g.body_json,l.body_json,EXISTS(SELECT 1 FROM review_round_changes t WHERE t.project_id=g.project_id AND t.pull_number=g.pull_number AND t.channel=g.channel AND t.epoch=g.epoch AND t.action='taper' AND t.revision<=?) FROM review_round_changes g JOIN review_round_changes l ON l.project_id=g.project_id AND l.pull_number=g.pull_number AND l.channel=g.channel AND l.revision=? AND l.epoch=g.epoch WHERE g.project_id=? AND g.pull_number=? AND g.channel=? AND g.revision=? AND g.epoch=?`, c.Revision, c.Revision, project, pull, channel, c.grantRevision, c.Epoch).Scan(&grantBody, &latestBody, &c.taperSet); err != nil { + if err := scanRoundValues(q.QueryRowContext(ctx, `SELECT g.body_json,l.body_json,EXISTS(SELECT 1 FROM review_round_changes t WHERE t.project_id=g.project_id AND t.pull_number=g.pull_number AND t.channel=g.channel AND t.epoch=g.epoch AND t.action='taper' AND t.revision<=?) FROM review_round_changes g JOIN review_round_changes l ON l.project_id=g.project_id AND l.pull_number=g.pull_number AND l.channel=g.channel AND l.revision=? AND l.epoch=g.epoch WHERE g.project_id=? AND g.pull_number=? AND g.channel=? AND g.revision=? AND g.epoch=?`, c.Revision, c.Revision, project, pull, channel, c.grantRevision, c.Epoch), &grantBody, &latestBody, &c.taperSet); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return roundRecord{}, &automaticProjectStateError{roundUnavailable()} + } return roundRecord{}, err } var bound RoundControl bound, _, err = decodeRoundHistory(grantBody) if err != nil { - return roundRecord{}, err + return roundRecord{}, &automaticProjectStateError{err} } latest, cumulative, err := decodeRoundHistory(latestBody) if err != nil { - return roundRecord{}, err + return roundRecord{}, &automaticProjectStateError{err} } c.cumulative = cumulative if latest.ProjectID != project || latest.PullNumber != pull || latest.Channel != channel || latest.Revision != c.Revision || latest.Epoch != c.Epoch || latest.Taper != c.Taper || version < 5 && c.taperSet { - return roundRecord{}, roundUnavailable() + return roundRecord{}, &automaticProjectStateError{roundUnavailable()} } if bound.ProjectID != project || bound.PullNumber != pull || bound.Channel != channel || bound.Revision != c.grantRevision || bound.Epoch != c.Epoch { - return roundRecord{}, roundUnavailable() + return roundRecord{}, &automaticProjectStateError{roundUnavailable()} } if !validRoundControl(c.RoundControl) || c.grantRevision < 1 || c.grantRevision > c.Revision || version < 4 && (c.cumulative || c.Maximum > 1000) || c.Used < bound.Used || c.cumulative && c.Tapered != (effectiveRoundTapered(c) && roundTaperBoundary(bound, c.Used)) || !c.cumulative && !validLegacyRoundControl(c.RoundControl) { - return roundRecord{}, roundUnavailable() + return roundRecord{}, &automaticProjectStateError{roundUnavailable()} } return c, nil } @@ -617,3 +620,33 @@ func storeRoundRecord(ctx context.Context, tx *sql.Tx, c roundRecord) error { _, err := tx.ExecContext(ctx, `INSERT INTO review_round_controls(`+roundColumns+`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(project_id,pull_number,channel) DO UPDATE SET revision=excluded.revision,epoch=excluded.epoch,grant_revision=excluded.grant_revision,closed=excluded.closed,minimum=excluded.minimum,maximum=excluded.maximum,taper=excluded.taper,used=excluded.used,dry=excluded.dry,tapered=excluded.tapered,actor_id=excluded.actor_id,updated_at=excluded.updated_at,initial_dry=excluded.initial_dry,initially_tapered=excluded.initially_tapered,origin_source=excluded.origin_source,origin_key=excluded.origin_key,origin_sha256=excluded.origin_sha256,maximum_unbounded=excluded.maximum_unbounded`, c.ProjectID, c.PullNumber, c.Channel, c.Revision, c.Epoch, c.grantRevision, c.Closed, c.Minimum, c.Maximum, c.Taper, c.Used, c.Dry, c.Tapered, c.ActorID, c.CreatedAt, c.UpdatedAt, c.InitialDry, c.InitiallyTapered, c.OriginSource, c.OriginKey, c.OriginSHA256, c.MaximumUnbounded) return err } + +// Scan without database/sql conversions so malformed retained values can be +// distinguished from an actual query or transaction failure. +func scanRoundValues(row *sql.Row, destinations ...any) error { + values := make([]any, len(destinations)) + pointers := make([]any, len(values)) + for i := range values { + pointers[i] = &values[i] + } + if err := row.Scan(pointers...); err != nil { + return err + } + for i, destination := range destinations { + valid := false + switch out := destination.(type) { + case *string: + *out, valid = values[i].(string) + case *int64: + *out, valid = values[i].(int64) + case *bool: + v, ok := values[i].(int64) + valid = ok && (v == 0 || v == 1) + *out = v == 1 + } + if !valid { + return &automaticProjectStateError{roundUnavailable()} + } + } + return nil +} diff --git a/internal/reviewexec/routes.go b/internal/reviewexec/routes.go index e686be162..edd549316 100644 --- a/internal/reviewexec/routes.go +++ b/internal/reviewexec/routes.go @@ -522,7 +522,7 @@ func pendingIncomingRoutes(ctx context.Context, tx *sql.Tx, project string, pull return 0, err } if dirty { - return 0, routeStorageError() + return 0, &automaticProjectStateError{routeStorageError()} } var pending int64 if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM review_route_policy_facts WHERE project_id=? AND target_pull_number=? AND active=1 AND pending=1`, project, pull).Scan(&pending); err != nil { @@ -531,7 +531,7 @@ func pendingIncomingRoutes(ctx context.Context, tx *sql.Tx, project string, pull // Browser JSON must preserve the exact count; this is a wire precision // invariant, not a practical retained-route capacity or page-size limit. if pending < 0 || pending > 1<<53-1 { - return 0, routeStorageError() + return 0, &automaticProjectStateError{routeStorageError()} } return pending, nil } diff --git a/internal/reviewexec/run_http.go b/internal/reviewexec/run_http.go index 8259ef4e1..40de29052 100644 --- a/internal/reviewexec/run_http.go +++ b/internal/reviewexec/run_http.go @@ -168,6 +168,7 @@ func (e *Engine) enqueueRunHTTP(w http.ResponseWriter, r *http.Request) { return } if terminal { + e.queuedRunResponseHeader(w, r, scope, state) core.WriteJSON(w, http.StatusOK, runStateForResponse(state, r.Header.Get(operationWaitHeader))) return } diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 4a073bd10..c8c8f2b0b 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -16,6 +16,7 @@ type RunRequest struct { Channel string `json:"channel"` ExpectedPullNumber *int64 `json:"expected_pull_number,omitempty"` ExpectedConfigurationRevision *int64 `json:"expected_configuration_revision,omitempty"` + origin string } type Run struct { ID string `json:"id"` @@ -40,7 +41,7 @@ const runColumns = `id,project_id,actor_id,worker_id,channel,configuration_revis func validRunID(id string) bool { return hostedObservationID(id, "review_selection_") } func runPending(state string) bool { return state == "queued" || state == "selecting" } func runUnavailable() error { - return core.Fail("storage_unavailable", "Stored review selection is unavailable.", 500) + return automaticProjectStateFailure("storage_unavailable", "Stored review selection is unavailable.", 500) } func validRun(r Run) bool { created, e1 := time.Parse(time.RFC3339Nano, r.CreatedAt) @@ -62,10 +63,13 @@ func validRun(r Run) bool { } func readRun(ctx context.Context, q EvidenceQuery, project, id string) (Run, error) { var r Run - err := q.QueryRowContext(ctx, `SELECT `+runColumns+` FROM review_selections WHERE project_id=? AND id=?`, project, id).Scan(&r.ID, &r.ProjectID, &r.ActorID, &r.WorkerID, &r.Channel, &r.ConfigurationRevision, &r.PolicyRevision, &r.CapabilityFingerprint, &r.ExpectedPullNumber, &r.State, &r.Reason, &r.Revision, &r.OperationID, &r.CreatedAt, &r.UpdatedAt) + err := scanRoundValues(q.QueryRowContext(ctx, `SELECT `+runColumns+` FROM review_selections WHERE project_id=? AND id=?`, project, id), &r.ID, &r.ProjectID, &r.ActorID, &r.WorkerID, &r.Channel, &r.ConfigurationRevision, &r.PolicyRevision, &r.CapabilityFingerprint, &r.ExpectedPullNumber, &r.State, &r.Reason, &r.Revision, &r.OperationID, &r.CreatedAt, &r.UpdatedAt) if errors.Is(err, sql.ErrNoRows) { return r, core.Fail("not_found", "The review selection is unavailable in this project.", 404) } + if automaticProjectRefused(err) { + return Run{}, runUnavailable() + } if err != nil { return r, err } @@ -114,6 +118,7 @@ func (e *Engine) EnqueueRun(ctx context.Context, scope core.Scope, key string, i v := *input.ExpectedConfigurationRevision input.ExpectedConfigurationRevision = &v } + input.origin = selectionOriginExplicit out, err := e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.run", Target: "channel-selection", Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { return e.enqueueRunTx(ctx, tx, scope, input) }) @@ -126,7 +131,7 @@ func (e *Engine) EnqueueRun(ctx context.Context, scope core.Scope, key string, i return out, err } -// enqueueRunTx accepts one explicit durable selection. +// enqueueRunTx is shared by explicit requests and the reauthorized automatic coordinator. func (e *Engine) enqueueRunTx(ctx context.Context, tx *sql.Tx, scope core.Scope, input RunRequest) (Receipt, error) { c, revision, err := readConfiguration(ctx, tx, scope.ProjectID) if err != nil { @@ -184,13 +189,23 @@ func (e *Engine) enqueueRunTx(ctx context.Context, tx *sql.Tx, scope core.Scope, if err != nil { return Receipt{}, err } - if err = core.AppendEvent(ctx, tx, scope, "review.selection_requested", id, 1, map[string]any{"channel": input.Channel}); err != nil { + if err = core.AppendEvent(ctx, tx, scope, "review.selection_requested", id, 1, selectionRequestedEvent{Channel: input.Channel, Origin: input.origin, WorkerID: scope.WorkerID}); err != nil { return Receipt{}, err } return Receipt{ID: id, State: "queued", Revision: 1}, nil } func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configuration, int64, string, error) { + if err := e.requireAutomaticRun(ctx, tx, r); err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Status == 403 { + return Configuration{}, 0, "automation_authorization_changed", nil + } + return Configuration{}, 0, "", err + } + if reason, err := automaticSourceRecoveryFence(ctx, tx, r); err != nil || reason != "" { + return Configuration{}, 0, reason, err + } c, revision, err := readConfiguration(ctx, tx, r.ProjectID) if err != nil { return c, 0, "", err @@ -223,6 +238,19 @@ func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configurati if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND channel=? AND state IN ('queued','preparing','posting','active','uncertain'))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { return c, 0, "", err } + if busy { + var automatic bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id=?)`, r.ProjectID, r.ID).Scan(&automatic); err != nil { + return c, 0, "", err + } + if automatic { + // Existing queued requests retain their turn; automatic front + // evaluation considers only the prefix before the earliest one. + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND channel=? AND state IN ('preparing','posting','active','uncertain'))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { + return c, 0, "", err + } + } + } if busy { return c, repository, "review_inflight", nil } @@ -263,15 +291,18 @@ func updateRunAt(ctx context.Context, tx *sql.Tx, r Run, state, reason, operatio func (e *Engine) RecoverReviewRuns(ctx context.Context) error { var changed []string err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { - rows, err := tx.QueryContext(ctx, `SELECT project_id,id FROM review_selections WHERE state='selecting' ORDER BY id LIMIT 257`) + rows, err := tx.QueryContext(ctx, `SELECT project_id,id,`+selectionClaimRevision+` FROM review_selections WHERE state='selecting' ORDER BY id LIMIT 257`) if err != nil { return err } - type key struct{ p, id string } + type key struct { + p, id any + revision int64 + } var keys []key for rows.Next() { var k key - if err = rows.Scan(&k.p, &k.id); err != nil { + if err = rows.Scan(&k.p, &k.id, &k.revision); err != nil { rows.Close() return err } @@ -286,11 +317,45 @@ func (e *Engine) RecoverReviewRuns(ctx context.Context) error { return runUnavailable() } for _, k := range keys { - r, err := readRun(ctx, tx, k.p, k.id) + project, projectOK := k.p.(string) + id, idOK := k.id.(string) + if !projectOK || !idOK { + if _, err := quarantineNativeSelection(ctx, tx, k.p, k.id, "selecting", k.revision); err != nil && !selectionCustodyUnproved(err) { + return err + } + continue + } + r, err := readRun(ctx, tx, project, id) + if automaticProjectRefused(err) || err == nil && r.Revision == math.MaxInt64 { + didChange, err := quarantineSelection(ctx, tx, Run{ProjectID: project, ID: id, State: "selecting", Revision: k.revision}) + if selectionCustodyUnproved(err) { + // Only the pre-write row-local refusal is isolated. Keep + // the original link intact and recover other rows. + continue + } + if err != nil { + return err + } + if didChange { + changed = append(changed, id) + } + continue + } if err != nil { return err } - if err = updateRun(ctx, tx, r, "queued", "", ""); err != nil { + state, reason := "queued", "" + if _, err := automaticSelectionBinding(ctx, tx, r); automaticProjectRefused(err) { + state = "held" + var holdErr error + reason, holdErr = selectionLocalHoldReason(ctx, tx, r) + if holdErr != nil { + return holdErr + } + } else if err != nil { + return err + } + if err = updateRun(ctx, tx, r, state, reason, ""); err != nil { return err } changed = append(changed, r.ID) @@ -390,7 +455,7 @@ func AbandonReviewRuns(ctx context.Context, tx *sql.Tx, at time.Time) (int64, er if err := ctx.Err(); err != nil { return 0, err } - present, err := restoredDomain(ctx, tx, "review_selection", "review_selections", "1") + present, err := restoredDomain(ctx, tx, "review_selection", "review_selections", "1", "2") if err != nil || !present { return 0, err } @@ -433,3 +498,95 @@ func AbandonReviewRuns(ctx context.Context, tx *sql.Tx, at time.Time) (int64, er } return int64(len(selected)), nil } + +// A corrupt revision is an opaque retained value, never an arithmetic operand. +const selectionClaimRevision = `CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision ELSE 0 END` + +// Quarantine only the observed pending row. Never reinterpret a retained +// live child as an explicit operation after removing its selection binding. +func quarantineSelection(ctx context.Context, tx *sql.Tx, expected Run) (bool, error) { + return quarantineNativeSelection(ctx, tx, expected.ProjectID, expected.ID, expected.State, expected.Revision) +} + +// Unproved custody is classified only before any selection writes. It may +// isolate a startup rebuild row, never a failed query or post-write error. +type unprovedSelectionCustodyError struct{ error } + +func (e *unprovedSelectionCustodyError) Unwrap() error { return e.error } +func selectionCustodyUnproved(err error) bool { + var refusal *unprovedSelectionCustodyError + return errors.As(err, &refusal) +} +func quarantineNativeSelection(ctx context.Context, tx *sql.Tx, project, id any, state string, revision int64) (bool, error) { + if state != "queued" && state != "selecting" { + return false, nil + } + const observed = ` WHERE project_id=? AND id=? AND state=? AND ` + selectionClaimRevision + `=?` + var originalLink, originalRevision any + err := tx.QueryRowContext(ctx, `SELECT operation_id,revision FROM review_selections`+observed, project, id, state, revision).Scan(&originalLink, &originalRevision) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + linkGuard := ` AND operation_id IS NULL` + holdReason := "local_read_unavailable" + args := []any{project, id, state, revision} + if originalLink != nil { + // Preserve only positively typed same-project custody. A missing + // child is valid diagnostic history; it cannot support a settled + // automatic binding or confer operation authority. + pid, projectOK := project.(string) + sid, selectionOK := id.(string) + op, linkOK := originalLink.(string) + native, revisionOK := originalRevision.(int64) + if !projectOK || !identifier.MatchString(pid) || !selectionOK || !validRunID(sid) || + !linkOK || !identifier.MatchString(op) || !revisionOK || native < 1 { + return false, &unprovedSelectionCustodyError{runUnavailable()} + } + // A retained child must still match the original immutable binding. + // Refuse foreign or inconsistent provenance rather than moving that + // record into a project where an unrelated operation could be held. + var inconsistent bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM review_selections s JOIN review_operations o ON o.id=s.operation_id + WHERE s.id=? AND s.project_id=? AND + (o.project_id<>s.project_id OR o.actor_id<>s.actor_id OR o.worker_id<>s.worker_id OR + o.channel<>s.channel OR o.configuration_revision<>s.configuration_revision OR + o.policy_revision<>s.policy_revision OR o.capability_fingerprint<>s.capability_fingerprint OR + (s.expected_pull_number<>0 AND o.pull_number<>s.expected_pull_number)) + UNION ALL + SELECT 1 FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id + LEFT JOIN review_operations o ON o.id=s.operation_id WHERE s.id=? AND s.project_id=? AND + (a.project_id<>s.project_id OR a.actor_id<>s.actor_id OR a.worker_id<>s.worker_id OR + typeof(a.pull_number)<>'integer' OR a.pull_number<0 OR a.pull_number>2147483647 OR + (a.pull_number<>0 AND (o.id IS NULL OR o.pull_number<>a.pull_number)) OR + (a.pull_number=0 AND a.pull_basis_sha256<>'')) + )`, sid, pid, sid, pid).Scan(&inconsistent); err != nil { + return false, err + } + if inconsistent { + return false, &unprovedSelectionCustodyError{runUnavailable()} + } + // Preserve the observed exact link without copying child or credential + // state. The outer transaction rolls this back if the hold fails. + if _, err := tx.ExecContext(ctx, `INSERT INTO review_selection_quarantine + (selection_id,project_id,original_operation_id,original_state,observed_revision) VALUES(?,?,?,?,?)`, sid, pid, op, state, native); err != nil { + return false, err + } + holdReason = "linked_selection_quarantined" + linkGuard = ` AND operation_id=?` + args = append(args, op) + } + result, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held',reason=?,operation_id=NULL, + revision=CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision+1 ELSE revision END`+observed+linkGuard, append([]any{holdReason}, args...)...) + if err != nil { + return false, err + } + n, err := result.RowsAffected() + if err == nil && n != 1 && originalLink != nil { + return false, runUnavailable() + } + return n == 1, 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/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go new file mode 100644 index 000000000..4f3d6bf73 --- /dev/null +++ b/internal/reviewexec/run_selection_origin.go @@ -0,0 +1,217 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/strictjson" +) + +const ( + selectionOriginExplicit = "explicit" + selectionOriginAutomatic = "automatic" +) + +type selectionRequestedEvent struct { + Channel string `json:"channel"` + Origin string `json:"origin,omitempty"` + WorkerID string `json:"worker_id,omitempty"` + sequence int64 +} + +func readSelectionRequestedEvent(ctx context.Context, q EvidenceQuery, r Run) (selectionRequestedEvent, error) { + rows, err := q.QueryContext(ctx, `SELECT sequence,actor_id, + CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END + FROM events WHERE project_id=? AND event_type='review.selection_requested' AND resource_id=? AND revision=1 LIMIT 2`, r.ProjectID, r.ID) + if err != nil { + return selectionRequestedEvent{}, err + } + defer rows.Close() + if !rows.Next() { + return selectionRequestedEvent{}, rows.Err() + } + var actor any + var sequence int64 + var body sql.NullString + if err = rows.Scan(&sequence, &actor, &body); err != nil { + return selectionRequestedEvent{}, err + } + var event selectionRequestedEvent + if sequence < 1 || actor != r.ActorID || !body.Valid || strictjson.Decode([]byte(body.String), &event) != nil || event.Channel != r.Channel || body.String != encoded(event) { + return selectionRequestedEvent{}, schedulingUnavailable() + } + switch event.Origin { + case "": + if event.WorkerID != "" { + return selectionRequestedEvent{}, schedulingUnavailable() + } + case selectionOriginExplicit, selectionOriginAutomatic: + if event.WorkerID != r.WorkerID { + return selectionRequestedEvent{}, schedulingUnavailable() + } + default: + return selectionRequestedEvent{}, schedulingUnavailable() + } + if rows.Next() { + return selectionRequestedEvent{}, schedulingUnavailable() + } + event.sequence = sequence + return event, rows.Err() +} + +type automaticSelectionAttribution struct { + revision int64 + credential string +} + +func readAutomaticSelectionAttribution(ctx context.Context, q EvidenceQuery, r Run) (automaticSelectionAttribution, error) { + var attribution automaticSelectionAttribution + var project, revision, actor, worker, credential any + // Read by the unique selection ID so a wrongly scoped row cannot masquerade + // as missing attribution for an otherwise valid selection. + err := q.QueryRowContext(ctx, `SELECT project_id,scheduling_revision,actor_id,worker_id,credential_id + FROM review_automatic_selections WHERE selection_id=?`, r.ID).Scan(&project, &revision, &actor, &worker, &credential) + if err != nil { + return attribution, err + } + nativeRevision, validRevision := revision.(int64) + credentialID, validCredential := credential.(string) + if project != r.ProjectID || actor != r.ActorID || worker != r.WorkerID || !validRevision || nativeRevision < 1 || !validCredential || !identifier.MatchString(credentialID) { + return attribution, schedulingUnavailable() + } + return automaticSelectionAttribution{revision: nativeRevision, credential: credentialID}, nil +} + +func automaticSelectionBinding(ctx context.Context, tx *sql.Tx, r Run) (automaticSelectionAttribution, error) { + event, err := readSelectionRequestedEvent(ctx, tx, r) + if err != nil { + return automaticSelectionAttribution{}, err + } + attribution, err := readAutomaticSelectionAttribution(ctx, tx, r) + if !errors.Is(err, sql.ErrNoRows) && err != nil { + return automaticSelectionAttribution{}, err + } + hasAttribution := err == nil + switch event.Origin { + case selectionOriginAutomatic: + if !hasAttribution || r.ExpectedPullNumber != 0 { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + case selectionOriginExplicit: + if hasAttribution { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + default: + // The automatic scheduler never accepts a caller-supplied PR pin. + if r.ExpectedPullNumber != 0 { + if hasAttribution { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + return attribution, nil + } + if !hasAttribution { + explicit, err := legacyExplicitSelection(ctx, tx, r) + if err != nil { + return automaticSelectionAttribution{}, err + } + if !explicit && event.sequence != 0 { + explicit, err = selectionPredatesAutomation(ctx, tx, r, event.sequence) + if err != nil { + return automaticSelectionAttribution{}, err + } + } + if !explicit { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + } + } + return attribution, nil +} + +// Explicit accepts wrote a canonical mutation receipt in the same transaction. +// Only a positive match proves legacy explicit origin; normal current +// authorization is still independently required to admit the retained work. +func legacyExplicitSelection(ctx context.Context, q EvidenceQuery, r Run) (bool, error) { + var hasHistory bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='restore_history')`).Scan(&hasHistory); err != nil { + return false, err + } + origins := `SELECT value FROM metadata WHERE key IN ('instance_id','restore:source_instance_id')` + if hasHistory { + // Startup validates the connected recovery provenance of this table. + origins += ` UNION SELECT instance_id FROM restore_history + UNION SELECT CASE WHEN json_valid(body_json) THEN json_extract(body_json,'$."restore:source_instance_id"') END FROM restore_history` + } + fingerprint, err := core.MutationRequestFingerprint(RunRequest{Channel: r.Channel}, r.WorkerID) + if err != nil { + return false, err + } + pinnedFingerprint, err := core.MutationRequestFingerprint(RunRequest{Channel: r.Channel, ExpectedConfigurationRevision: &r.ConfigurationRevision}, r.WorkerID) + if err != nil { + return false, err + } + response := encoded(Receipt{ID: r.ID, State: "queued", Revision: 1}) + var explicit bool + err = q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM receipts + WHERE instance_id IN (`+origins+`) AND principal_id=? AND project_id=? AND operation='reviews.run' + AND target='channel-selection' AND fingerprint IN (?,?) AND response_json=?)`, + r.ActorID, r.ProjectID, fingerprint, pinnedFingerprint, response).Scan(&explicit) + return explicit, err +} + +func selectionLocalHoldReason(ctx context.Context, q EvidenceQuery, r Run) (string, error) { + event, err := readSelectionRequestedEvent(ctx, q, r) + if err != nil && !automaticProjectRefused(err) { + return "", err + } + var attributionPresent bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=?)`, r.ID).Scan(&attributionPresent); err != nil { + return "", err + } + if event.Origin == selectionOriginAutomatic || attributionPresent { + return "automatic_scheduling_unavailable", nil + } + return "local_read_unavailable", nil +} + +// An accepted event preceding every enabled revision of its channel is another +// positive distinction for older explicit requests with no exact receipt. +func selectionPredatesAutomation(ctx context.Context, tx *sql.Tx, r Run, acceptedSequence int64) (bool, error) { + projected, err := readScheduling(ctx, tx, r.ProjectID) + if err != nil || projected.Revision > 10000 { + return false, err + } + rows, err := tx.QueryContext(ctx, `SELECT sequence,revision, + CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END + FROM events WHERE project_id=? AND resource_id=? AND event_type='review.scheduling_updated' + ORDER BY sequence LIMIT 10001`, r.ProjectID, r.ProjectID) + if err != nil { + return false, err + } + defer rows.Close() + var expected int64 = 1 + for rows.Next() { + var sequence int64 + var revision any + var body sql.NullString + if err := rows.Scan(&sequence, &revision, &body); err != nil { + return false, err + } + var control schedulingEvent + if revision != expected || !body.Valid || strictjson.Decode([]byte(body.String), &control) != nil || control.Hosted == nil { + return false, nil + } + enabled := control.Hosted + if r.Channel == "cli" { + enabled = control.CLI + } + channelEnabled := enabled != nil && *enabled + if sequence < acceptedSequence && channelEnabled || expected == projected.Revision && channelEnabled != automaticChannelEnabled(projected, r.Channel) { + return false, nil + } + expected++ + } + return expected == projected.Revision+1, rows.Err() +} diff --git a/internal/reviewexec/run_selection_schema.go b/internal/reviewexec/run_selection_schema.go index a96fef207..b9bdc4c65 100644 --- a/internal/reviewexec/run_selection_schema.go +++ b/internal/reviewexec/run_selection_schema.go @@ -2,11 +2,13 @@ package reviewexec import ( "context" + "database/sql" + "errors" "github.com/benhook1013/FireController/internal/core" ) func EnsureSelectionSchema(ctx context.Context, store *core.Store) error { - return store.EnsureSchema(ctx, "review_selection", SelectionSchemaSQL()) + return store.EnsureSchema(ctx, "review_selection", SelectionSchemaSQL(), []string{selectionQuarantineTableSQL}) } // SelectionSchemaSQL returns an independent canonical DDL slice. @@ -23,3 +25,54 @@ func SelectionSchemaSQL() []string { `CREATE INDEX review_selections_pending ON review_selections(state,created_at,id)`, } } + +// The diagnostic binding is not an operation foreign key. It is only used for a +// well-typed historical link and cannot confer authority. +const selectionQuarantineTableSQL = `CREATE TABLE review_selection_quarantine( + selection_id TEXT NOT NULL PRIMARY KEY REFERENCES review_selections(id), + project_id TEXT NOT NULL REFERENCES projects(id), + original_operation_id TEXT NOT NULL CHECK(typeof(original_operation_id)='text' AND length(CAST(original_operation_id AS BLOB)) BETWEEN 1 AND 128), + original_state TEXT NOT NULL CHECK(original_state IN ('queued','selecting')), + observed_revision INTEGER NOT NULL CHECK(typeof(observed_revision)='integer' AND observed_revision>0), + UNIQUE(project_id,original_operation_id))` + +const linkedSelectionCustodyHeld = "selection_custody_quarantined" + +// requireUnquarantinedSelectionLink only denies work. The custody row cannot +// replace active selection attribution or authorize a new provider action. +func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, project, operation string) error { + var proved bool + err := q.QueryRowContext(ctx, `SELECT COALESCE(s.project_id=d.project_id AND s.state='held' AND + s.reason='linked_selection_quarantined' AND s.operation_id IS NULL AND + typeof(d.observed_revision)='integer' AND d.observed_revision>0 AND + typeof(s.revision)='integer' AND s.revision=CASE WHEN d.observed_revision=9223372036854775807 + THEN d.observed_revision ELSE d.observed_revision+1 END AND + d.original_state IN ('queued','selecting') AND + (o.id IS NULL OR (o.project_id=s.project_id AND o.actor_id=s.actor_id AND o.worker_id=s.worker_id AND + o.channel=s.channel AND o.configuration_revision=s.configuration_revision AND o.policy_revision=s.policy_revision AND + o.capability_fingerprint=s.capability_fingerprint AND (s.expected_pull_number=0 OR s.expected_pull_number=o.pull_number))) + AND NOT EXISTS(SELECT 1 FROM review_automatic_selections a WHERE a.selection_id=s.id AND + (a.project_id<>s.project_id OR a.actor_id<>s.actor_id OR a.worker_id<>s.worker_id OR + typeof(a.pull_number)<>'integer' OR a.pull_number<0 OR a.pull_number>2147483647 OR + (a.pull_number<>0 AND (o.id IS NULL OR o.pull_number<>a.pull_number)) OR + (a.pull_number=0 AND a.pull_basis_sha256<>''))), 0) + FROM review_selection_quarantine d LEFT JOIN review_selections s ON s.id=d.selection_id + LEFT JOIN review_operations o ON o.id=d.original_operation_id + WHERE d.project_id=? AND d.original_operation_id=?`, project, operation).Scan(&proved) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil { + return err + } + if !proved { + // An unknown custody row cannot establish ordinary ineligibility. + return runUnavailable() + } + return automaticProjectStateFailure(linkedSelectionCustodyHeld, "This review operation is held for selection custody recovery.", 403) +} + +func isLinkedSelectionCustodyHeld(err error) bool { + var failure *core.Error + return errors.As(err, &failure) && failure.Code == linkedSelectionCustodyHeld +} diff --git a/internal/reviewexec/run_selection_snapshot.go b/internal/reviewexec/run_selection_snapshot.go index acddb5483..c7ccfcadd 100644 --- a/internal/reviewexec/run_selection_snapshot.go +++ b/internal/reviewexec/run_selection_snapshot.go @@ -2,7 +2,10 @@ package reviewexec import ( "context" + "database/sql" + "errors" "fmt" + "math" "slices" "strings" @@ -16,6 +19,14 @@ func ValidateSelectionSnapshot(ctx context.Context, q EvidenceQuery) error { if err := validateSelectionPhysical(ctx, q); err != nil { return err } + if err := validateSelectionQuarantine(ctx, q); err != nil { + return err + } + + var hasScheduling bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='review_automatic_selections')`).Scan(&hasScheduling); err != nil { + return err + } var bad bool // Storage classes and empty keys are checked before scanned string keysets. if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections s LEFT JOIN projects p ON p.id=s.project_id LEFT JOIN workers w ON w.project_id=s.project_id AND w.id=s.worker_id WHERE p.id IS NULL OR w.id IS NULL OR NOT EXISTS(SELECT 1 FROM credentials c WHERE c.principal_id=s.actor_id))`).Scan(&bad); err != nil { @@ -58,6 +69,24 @@ func ValidateSelectionSnapshot(ctx context.Context, q EvidenceQuery) error { if err != nil { return err } + + event, err := readSelectionRequestedEvent(ctx, q, r) + if err != nil { + return err + } + if event.Origin != "" { + attributed := false + if hasScheduling { + _, err := readAutomaticSelectionAttribution(ctx, q, r) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + attributed = err == nil + } + if (event.Origin == selectionOriginAutomatic) != attributed || attributed && r.ExpectedPullNumber != 0 { + return schedulingUnavailable() + } + } var configurationBody, policyBody string if err = q.QueryRowContext(ctx, `SELECT CASE WHEN typeof(body_json)='text' AND length(CAST(body_json AS BLOB))<=16384 THEN body_json END FROM review_execution_config WHERE project_id=? AND revision=?`, r.ProjectID, r.ConfigurationRevision).Scan(&configurationBody); err != nil { return runUnavailable() @@ -152,3 +181,91 @@ func validateSelectionPhysical(ctx context.Context, q EvidenceQuery) error { } return nil } + +func validateSelectionQuarantine(ctx context.Context, q EvidenceQuery) error { + var version string + if err := q.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_selection'`).Scan(&version); err != nil { + return err + } + var objects int + if err := q.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_schema + WHERE (tbl_name='review_selection_quarantine' OR name='review_selection_quarantine' COLLATE NOCASE) + AND sql IS NOT NULL`).Scan(&objects); err != nil { + return err + } + if version == "1" && objects == 0 { + return validateNoSelectionCustodyMarkers(ctx, q) + } + if version != "2" || objects != 1 { + return runUnavailable() + } + var ddl string + if err := q.QueryRowContext(ctx, `SELECT sql FROM sqlite_schema WHERE name='review_selection_quarantine' AND type='table' AND length(CAST(sql AS BLOB))<=16384`).Scan(&ddl); err != nil { + return err + } + if ddl != selectionQuarantineTableSQL { + return runUnavailable() + } + // With no custody records there is no child binding to validate. Older + // supported execution schemas can lack current child identity columns. + // Still require every custody marker to have a retained diagnostic row. + var populated bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selection_quarantine)`).Scan(&populated); err != nil { + return err + } + if !populated { + return validateNoSelectionCustodyMarkers(ctx, q) + } + var inconsistent bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM review_selections s WHERE s.reason='linked_selection_quarantined' AND NOT EXISTS + (SELECT 1 FROM review_selection_quarantine d WHERE d.selection_id=s.id AND d.project_id=s.project_id) + UNION ALL + SELECT 1 FROM review_selection_quarantine d JOIN review_selections s ON s.operation_id=d.original_operation_id + UNION ALL + SELECT 1 FROM review_selection_quarantine d JOIN review_selections s ON s.id=d.selection_id + JOIN review_operations o ON o.id=d.original_operation_id + WHERE o.project_id<>s.project_id OR o.actor_id<>s.actor_id OR o.worker_id<>s.worker_id OR + o.channel<>s.channel OR o.configuration_revision<>s.configuration_revision OR + o.policy_revision<>s.policy_revision OR o.capability_fingerprint<>s.capability_fingerprint OR + (s.expected_pull_number<>0 AND o.pull_number<>s.expected_pull_number))`).Scan(&inconsistent); err != nil { + return err + } + if inconsistent { + return runUnavailable() + } + rows, err := q.QueryContext(ctx, `SELECT CASE WHEN typeof(d.original_operation_id)='text' AND length(CAST(d.original_operation_id AS BLOB))<=128 THEN d.original_operation_id END, + d.original_state,d.observed_revision,s.state,s.reason,s.operation_id,s.revision,s.project_id,d.project_id + FROM review_selection_quarantine d LEFT JOIN review_selections s ON s.id=d.selection_id`) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var link, oldState, state, reason, project, reportedProject string + var revision, observed, currentLink any + if err := rows.Scan(&link, &oldState, &observed, &state, &reason, ¤tLink, &revision, &project, &reportedProject); err != nil { + return err + } + old, oldOK := observed.(int64) + now, nowOK := revision.(int64) + if !identifier.MatchString(link) || oldState != "queued" && oldState != "selecting" || !oldOK || !nowOK || old < 1 || + (old < math.MaxInt64 && now != old+1 || old == math.MaxInt64 && now != old) || + state != "held" || reason != "linked_selection_quarantined" || currentLink != nil || project != reportedProject { + return runUnavailable() + } + } + return rows.Err() +} + +func validateNoSelectionCustodyMarkers(ctx context.Context, q EvidenceQuery) error { + var marker bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections + WHERE reason='linked_selection_quarantined')`).Scan(&marker); err != nil { + return err + } + if marker { + return runUnavailable() + } + return nil +} diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 593d0947b..cd1ec1d08 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -4,13 +4,15 @@ import ( "context" "database/sql" "errors" - "github.com/benhook1013/FireController/internal/core" - "github.com/benhook1013/FireController/internal/reviewprovider" - "github.com/benhook1013/FireController/internal/reviews" + "math" "reflect" "slices" "sync" "time" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewprovider" + "github.com/benhook1013/FireController/internal/reviews" ) // runSourceBudget bounds cumulative source acquisition, excluding local SQL @@ -162,11 +164,13 @@ func (r *runReads) ParentPull(ctx context.Context, repository, branch string) (r } type runChoice struct { - state, reason string - sourceReason string - prefix []SourcePlan - number int64 - head string + state, reason string + sourceReason string + prefix []SourcePlan + number int64 + head string + automaticQueueLimit *int + automaticBasisRevision int64 } // retryRunSelectionLocal retains completed source reads while only retrying @@ -179,7 +183,7 @@ func retryRunSelectionLocal(ctx context.Context, local func() error) error { } err := local() var failure *core.Error - if !errors.As(err, &failure) || failure.Code != "overloaded" { + if automaticProjectRefused(err) || !errors.As(err, &failure) || failure.Code != "overloaded" { return err } timer := time.NewTimer(delay) @@ -215,14 +219,54 @@ func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configurati return e.chooseRunWithSourceBudget(ctx, r, repo, c, reader, e.runSourceBudget) } -func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (runChoice, error) { +func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (result runChoice, resultErr error) { + var automaticQueueLimit *int + + var basisRevision int64 + defer func() { + result.automaticQueueLimit = automaticQueueLimit + result.automaticBasisRevision = basisRevision + }() + // Bound source work before metadata lookahead. Local suppression still + // rechecks the live prefix at admission if queued work changes afterward. + limit, automatic := len(c.Queue), false + err := retryRunSelectionRead(ctx, func() error { + // An expired snapshot must not shorten a later retry's input. + limit, automatic, basisRevision = len(c.Queue), false, 0 + return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil { + return err + } + automatic = attribution.revision != 0 + if !automatic { + return nil + } + limit, err = e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + if err != nil { + return err + } + if limit < 0 || limit > len(c.Queue) { + return schedulingUnavailable() + } + basisRevision, err = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) + return err + }) + }) + if err != nil { + return runChoice{}, err + } + if automatic { + automaticQueueLimit = &limit + } + c.Queue = c.Queue[:limit] if len(c.Queue) == 0 { return runChoice{state: "empty", reason: "queue_complete"}, nil } reads := &runReads{reader: reader, repos: map[int64]reviewprovider.Repository{}, pulls: map[string]map[int64]reviewprovider.Pull{}} source := runSourceBudget{remaining: sourceBudget} var repository reviewprovider.Repository - err := source.read(ctx, func(ctx context.Context) error { + err = source.read(ctx, func(ctx context.Context) error { var err error repository, err = reads.Repository(ctx, repo) return err @@ -244,6 +288,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 } var window []runPullResult windowStart := 0 + windowSize := 4 for i, n := range queue { if err := ctx.Err(); err != nil { return runChoice{}, err @@ -251,7 +296,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 if i >= windowStart+len(window) { windowStart = i err = source.read(ctx, func(ctx context.Context) error { - window = reads.pullWindow(ctx, repository.FullName, repository.ID, queue[i:min(i+4, len(queue))]) + window = reads.pullWindow(ctx, repository.FullName, repository.ID, queue[i:min(i+windowSize, len(queue))]) return nil }) if err != nil { @@ -265,6 +310,13 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 if !sameTarget(pull, repo, n) || pull.State != "open" && pull.State != "closed" || pull.Merged && pull.State != "closed" { return sourceFailure("source_response_invalid"), nil } + // Fresh lifecycle guides only speculative width, never eligibility or + // coverage. Live tails otherwise repeatedly cancel and refetch three + // successors per candidate. Resume batching when merged history resumes. + windowSize = 1 + if pull.Merged { + windowSize = 4 + } plan := SourcePlan{Repository: repository, Pull: pull, ParentSHA: pull.BaseSHA, ObservedAt: stamp()} if !pull.Merged && pull.State == "open" { err = source.read(ctx, func(ctx context.Context) error { @@ -436,27 +488,44 @@ func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) ( var repo int64 var changed string var project, id string + var nativeProject, nativeID any + var quarantined bool var expected int64 err := retryRunSelectionLocal(ctx, func() error { project, id, expected = "", "", 0 + nativeProject, nativeID = nil, nil return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { // Request capacity is a scheduling constraint, not a terminal hold. // Skip saturated projects before source work so they cannot occupy // both selection workers or repeatedly reacquire provider facts. - err := tx.QueryRowContext(ctx, `SELECT s.project_id,s.id,s.revision FROM review_selections s + // A linked selection with a non-native key cannot prove custody. + // Leave it intact and allow unrelated selections to proceed. + err := tx.QueryRowContext(ctx, `SELECT s.project_id,s.id,`+selectionClaimRevision+` FROM review_selections s WHERE s.state='queued' + AND (s.operation_id IS NULL OR (typeof(s.project_id)='text' AND typeof(s.id)='text')) AND (SELECT count(*) FROM review_operations WHERE state IN ('queued','preparing','posting','active','uncertain')) 1 || cliValue < 0 || cliValue > 1 { + return s, schedulingRecordUnavailable() + } + s.AutomaticHosted, s.AutomaticCLI = hostedValue == 1, cliValue == 1 + if s.Revision < 1 || !identifier.MatchString(s.actor) || !roundTime(s.UpdatedAt) || (s.AutomaticHosted || s.AutomaticCLI) && (!identifier.MatchString(s.AuthorizingWorkerID) || !identifier.MatchString(s.credential)) { + return s, schedulingRecordUnavailable() + } + return s, nil +} + +type schedulingEvent struct { + Hosted *bool `json:"automatic_hosted"` + CLI *bool `json:"automatic_cli"` + HostedBasis json.RawMessage `json:"hosted_basis_revision"` + CLIBasis json.RawMessage `json:"cli_basis_revision"` +} + +// Channel basis revisions are carried in the current scheduling event, not in +// the authorization revision. Legacy events retain the shared revision verbatim: +// deploying this change must not regenerate cancelled or failed intent digests. +func schedulingBasisRevisions(ctx context.Context, tx *sql.Tx, s schedulingRecord) (hosted, cli int64, err error) { + if s.Revision == 0 { + return 0, 0, nil + } + rows, err := tx.QueryContext(ctx, `SELECT actor_id,CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision=? LIMIT 2`, s.ProjectID, s.ProjectID, s.Revision) + if err != nil { + return 0, 0, err + } + defer rows.Close() + count := 0 + for rows.Next() { + count++ + var actor string + var payload sql.NullString + if err = rows.Scan(&actor, &payload); err != nil { + return 0, 0, err + } + var event schedulingEvent + if count != 1 || actor != s.actor || !payload.Valid || strictjson.Decode([]byte(payload.String), &event) != nil || event.Hosted == nil || *event.Hosted != s.AutomaticHosted || event.CLI == nil && s.AutomaticCLI || event.CLI != nil && *event.CLI != s.AutomaticCLI { + return 0, 0, schedulingUnavailable() + } + hosted, cli = s.Revision, s.Revision + if len(event.HostedBasis) != 0 || len(event.CLIBasis) != 0 { + if json.Unmarshal(event.HostedBasis, &hosted) != nil || json.Unmarshal(event.CLIBasis, &cli) != nil || string(event.HostedBasis) == "null" || string(event.CLIBasis) == "null" || hosted < 1 || cli < 1 || hosted > s.Revision || cli > s.Revision { + return 0, 0, schedulingUnavailable() + } + } + } + if err = rows.Err(); err != nil { + return 0, 0, err + } + if err = rows.Close(); err != nil { + return 0, 0, err + } + if count != 1 { + return 0, 0, schedulingUnavailable() + } + return hosted, cli, nil +} + +func schedulingAuthorizerAllowed(ctx context.Context, tx *sql.Tx, s schedulingRecord) (bool, error) { + if !s.AutomaticHosted && !s.AutomaticCLI { + return false, nil + } + var allowed bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM credentials c WHERE c.id=? AND c.principal_id=? AND c.revoked=0 AND (c.is_admin=1 OR EXISTS(SELECT 1 FROM grants g WHERE g.credential_id=c.id AND g.project_id=? AND g.can_read=1 AND g.can_write=1 AND g.can_manage=1)) AND EXISTS(SELECT 1 FROM workers w WHERE w.project_id=? AND w.id=? AND NOT EXISTS(SELECT 1 FROM worker_retirements r WHERE r.project_id=w.project_id AND r.worker_id=w.id)))`, s.credential, s.actor, s.ProjectID, s.ProjectID, s.AuthorizingWorkerID).Scan(&allowed) + return allowed, err +} +func (e *Engine) ReadScheduling(ctx context.Context, scope core.Scope) (Scheduling, error) { + var out Scheduling + err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { + s, err := readScheduling(ctx, tx, scope.ProjectID) + if err != nil { + return err + } + out = s.Scheduling + out.PausedPulls = []PullScheduling{} + c, _, configErr := readConfiguration(ctx, tx, scope.ProjectID) + if configErr != nil { + var failure *core.Error + if !errors.As(configErr, &failure) || failure.Code != "reviews_unconfigured" { + return configErr + } + } else { + if validateConfigurationShape(c) != nil { + return schedulingUnavailable() + } + for _, pull := range c.Queue { + p, err := readPullScheduling(ctx, tx, scope.ProjectID, pull) + if err != nil { + return err + } + if p.Paused { + out.PausedPulls = append(out.PausedPulls, p) + } + } + } + if s.AutomaticHosted || s.AutomaticCLI { + var held bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM metadata WHERE (key='restore:provider_state' AND value='held') OR (key='restore:state' AND value='inactive'))`).Scan(&held); err != nil { + return err + } + if held { + out.Reason = "provider_hold" + return nil + } + ok, err := schedulingAuthorizerAllowed(ctx, tx, s) + if err != nil { + return err + } + if !ok { + out.Reason = "authorizer_unavailable" + } + } + return nil + }) + return out, err +} +func validSchedulingRevision(r *int64) bool { return r != nil && *r >= 0 && *r < math.MaxInt64 } + +// A pull-specific retained control refusal is distinct from project +// scheduling, a query error, or another member of the queue. +type pullSchedulingStateError struct { + err error + project string + pull int64 +} + +func (e *pullSchedulingStateError) Error() string { return e.err.Error() } +func (e *pullSchedulingStateError) Unwrap() error { return e.err } + +func readPullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) (s PullScheduling, err error) { + s.ProjectID = project + s.PullNumber = pull + var revision, paused, reason, actor, updated any + err = tx.QueryRowContext(ctx, `SELECT revision,paused,reason,actor_id,updated_at FROM review_pull_scheduling WHERE project_id=? AND pull_number=?`, project, pull).Scan(&revision, &paused, &reason, &actor, &updated) + if errors.Is(err, sql.ErrNoRows) { + return s, nil + } + if err != nil { + return s, err + } + var revisionOK, reasonOK, actorOK, updatedOK bool + s.Revision, revisionOK = revision.(int64) + pausedValue, pausedOK := paused.(int64) + s.Reason, reasonOK = reason.(string) + s.ActorID, actorOK = actor.(string) + s.UpdatedAt, updatedOK = updated.(string) + if !revisionOK || !pausedOK || !reasonOK || !actorOK || !updatedOK || pausedValue < 0 || pausedValue > 1 { + return s, &pullSchedulingStateError{schedulingRecordUnavailable(), project, pull} + } + s.Paused = pausedValue == 1 + if s.Revision < 1 || !identifier.MatchString(s.ActorID) || !roundTime(s.UpdatedAt) || !validSchedulingReason(s.Reason) || !s.Paused && s.Reason != "" { + return s, &pullSchedulingStateError{schedulingRecordUnavailable(), project, pull} + } + return s, nil +} +func validSchedulingReason(s string) bool { + return len(s) <= 256 && utf8.ValidString(s) && strings.IndexFunc(s, unicode.IsControl) < 0 +} +func (e *Engine) ReadPullScheduling(ctx context.Context, scope core.Scope, pull int64) (PullScheduling, error) { + if pull < 1 || pull > 2147483647 { + return PullScheduling{}, invalid() + } + var out PullScheduling + err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { + var err error + out, err = readPullScheduling(ctx, tx, scope.ProjectID, pull) + return err + }) + return out, err +} +func (e *Engine) ConfigurePullScheduling(ctx context.Context, scope core.Scope, key string, pull int64, input PullSchedulingRequest) (json.RawMessage, error) { + if pull < 1 || pull > 2147483647 || !validSchedulingRevision(input.ExpectedRevision) || input.Paused == nil || !validSchedulingReason(input.Reason) { + return nil, invalid() + } + out, err := e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.pull_scheduling", Target: strconv.FormatInt(pull, 10), Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { + old, err := readPullScheduling(ctx, tx, scope.ProjectID, pull) + if err != nil { + return nil, err + } + if old.Revision != *input.ExpectedRevision { + return nil, conflict() + } + reason := input.Reason + if !*input.Paused { + reason = "" + } + _, err = tx.ExecContext(ctx, `INSERT INTO review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(project_id,pull_number) DO UPDATE SET revision=excluded.revision,paused=excluded.paused,reason=excluded.reason,actor_id=excluded.actor_id,updated_at=excluded.updated_at`, scope.ProjectID, pull, old.Revision+1, *input.Paused, reason, scope.PrincipalID, stamp()) + if err != nil { + return nil, err + } + if err = core.AppendEvent(ctx, tx, scope, "review.pull_scheduling_updated", strconv.FormatInt(pull, 10), old.Revision+1, map[string]any{"pull_number": pull, "paused": *input.Paused}); err != nil { + return nil, err + } + return Receipt{ID: strconv.FormatInt(pull, 10), State: "pull_scheduling_updated", Revision: old.Revision + 1}, nil + }) + if err == nil { + e.wakeScheduling() + } + return out, err +} +func (e *Engine) wakeScheduling() { + select { + case e.runWake <- struct{}{}: + default: + } + select { + case e.wake <- struct{}{}: + default: + } +} +func requirePullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) error { + s, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + return err + } + if s.Paused { + return core.Fail("pull_scheduling_paused", "New review admission is paused for this PR; existing issued reviews can still be collected.", 409) + } + return nil +} 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_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go new file mode 100644 index 000000000..0398dbf67 --- /dev/null +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -0,0 +1,71 @@ +package reviewexec + +import ( + "context" + "database/sql" + + "github.com/benhook1013/FireController/internal/strictjson" +) + +// A configuration owner change governs new selections. It need not replace an +// already-selected operation whose own lane has never been withdrawn. Require +// complete durable control history instead of inferring continuity from the +// current enabled bit. The caller still validates the original exact credential, +// principal and active worker; both historical attribution and child stay intact. +func retainedAutomaticAuthorization(ctx context.Context, tx *sql.Tx, r Run, revision int64, originalActor string, current schedulingRecord) (bool, error) { + if r.State != "selected" || r.OperationID == "" || revision < 1 || revision >= current.Revision || current.Revision-revision > 10000 { + return false, nil + } + allowed, err := schedulingAuthorizerAllowed(ctx, tx, current) + if err != nil || !allowed { + return false, err + } + var bound bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections s JOIN review_operations o ON o.project_id=s.project_id AND o.id=s.operation_id WHERE s.project_id=? AND s.id=? AND s.state='selected' AND s.operation_id=? AND s.actor_id=? AND s.worker_id=? AND s.channel=? AND o.actor_id=s.actor_id AND o.worker_id=s.worker_id AND o.channel=s.channel)`, r.ProjectID, r.ID, r.OperationID, r.ActorID, r.WorkerID, r.Channel).Scan(&bound) + if err != nil || !bound { + return false, err + } + return automaticChannelContinuous(ctx, tx, r, revision, originalActor, current) +} + +// An unchanged authorizer may finish an unselected intent after an unrelated +// channel change. Every revision must still prove its own channel stayed on. +func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision int64, originalActor string, current schedulingRecord) (bool, error) { + if revision < 1 || revision >= current.Revision || current.Revision-revision > 10000 { + return false, nil + } + rows, err := tx.QueryContext(ctx, `SELECT revision,actor_id,CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision BETWEEN ? AND ? ORDER BY revision,sequence LIMIT 10002`, r.ProjectID, r.ProjectID, revision, current.Revision) + if err != nil { + return false, err + } + defer rows.Close() + expected := revision + for rows.Next() { + var retainedRevision any + var actor string + var payload sql.NullString + if err = rows.Scan(&retainedRevision, &actor, &payload); err != nil { + return false, err + } + recorded, validRevision := retainedRevision.(int64) + if !validRevision || recorded != expected || recorded == revision && actor != originalActor || recorded == current.Revision && actor != current.actor { + return false, nil + } + var settings schedulingEvent + if !payload.Valid || strictjson.Decode([]byte(payload.String), &settings) != nil { + return false, nil + } + enabled := settings.Hosted + if r.Channel == "cli" { + enabled = settings.CLI + } + if enabled == nil || !*enabled { + return false, nil + } + expected++ + } + if err = rows.Err(); err != nil { + return false, err + } + return expected == current.Revision+1, nil +} diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go new file mode 100644 index 000000000..6a560293c --- /dev/null +++ b/internal/reviewexec/scheduling_automatic.go @@ -0,0 +1,582 @@ +package reviewexec + +import ( + "bytes" + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "io" + "slices" + "strconv" + "strings" + + "github.com/benhook1013/FireController/internal/core" +) + +var errAutomaticParentCycle = errors.New("automatic scheduling retained parent cycle") + +// Tag only validated project-local retained-data refusals. Public status codes +// deliberately remain unchanged; storage_unavailable alone is not a safe reason +// to suppress a failed query, transaction, or shared storage operation. +type automaticProjectStateError struct{ error } + +func (e *automaticProjectStateError) Unwrap() error { return e.error } + +func automaticProjectStateFailure(code, message string, status int) error { + return &automaticProjectStateError{core.Fail(code, message, status)} +} + +func automaticProjectRefused(err error) bool { + var local *automaticProjectStateError + return errors.As(err, &local) +} + +func automaticDenied() error { + return core.Fail("automation_authorization_changed", "Automatic review scheduling is disabled or its original authorizer is no longer authorized.", 403) +} + +func automaticChannelEnabled(s schedulingRecord, channel string) bool { + return channel == "hosted" && s.AutomaticHosted || channel == "cli" && s.AutomaticCLI +} + +func (e *Engine) requireAutomaticRun(ctx context.Context, tx *sql.Tx, r Run) error { + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil || attribution.revision == 0 { + return err + } + revision, credential := attribution.revision, attribution.credential + actor, worker := r.ActorID, r.WorkerID + s, err := readScheduling(ctx, tx, r.ProjectID) + if err != nil { + return err + } + if revision > s.Revision || !automaticChannelEnabled(s, r.Channel) || !validChannel(r.Channel) { + return automaticDenied() + } + if s.actor != actor || s.AuthorizingWorkerID != worker || s.credential != credential { + continuous, err := retainedAutomaticAuthorization(ctx, tx, r, revision, actor, s) + if err != nil { + return err + } + if !continuous { + return automaticDenied() + } + } else if revision != s.Revision { + continuous, err := automaticChannelContinuous(ctx, tx, r, revision, actor, s) + if err != nil { + return err + } + if !continuous { + return automaticDenied() + } + } else { + // Same-revision work still requires the exact canonical event + // behind its enabled control; a retained projection alone is not proof. + if _, _, err := schedulingBasisRevisions(ctx, tx, s); err != nil { + return err + } + } + _, err = e.store.ProjectAutomationScope(ctx, tx, r.ProjectID, actor, worker, credential) + var failure *core.Error + if errors.As(err, &failure) && failure.Status >= 400 && failure.Status < 500 { + return automaticDenied() + } + return err +} +func (e *Engine) requireAutomaticOperation(ctx context.Context, tx *sql.Tx, o Operation) error { + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + return err + } + var project, selection any + err := tx.QueryRowContext(ctx, `SELECT project_id,id FROM review_selections WHERE operation_id=?`, o.ID).Scan(&project, &selection) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil { + return err + } + id, validID := selection.(string) + if project != o.ProjectID || !validID || !validRunID(id) { + return schedulingUnavailable() + } + r, err := readRun(ctx, tx, o.ProjectID, id) + if err != nil { + return err + } + if r.OperationID != o.ID || r.ActorID != o.ActorID || r.WorkerID != o.WorkerID || r.Channel != o.Channel { + return schedulingUnavailable() + } + return e.requireAutomaticRun(ctx, tx, r) +} + +const automaticCurrentRunsBasisQuery = `SELECT v.id,v.channel,v.head_sha,v.complete,v.finalized,v.found,v.accepted,v.routed,v.fixed FROM review_current_runs c JOIN review_run_memberships m ON m.project_id=c.project_id AND m.id=c.id AND m.start_revision=c.start_revision JOIN review_run_versions v ON v.project_id=m.project_id AND v.id=m.id AND v.version_revision=m.version_revision WHERE c.project_id=? AND c.pull_number=? AND v.channel='hosted' AND v.outcome='completed' ORDER BY v.id LIMIT 10001` +const automaticCurrentFindingsBasisQuery = `SELECT f.run_id,f.source_finding_id,f.disposition,f.fix_sha,f.proof_note,f.route_json FROM review_current_runs c JOIN review_run_memberships m ON m.project_id=c.project_id AND m.id=c.id AND m.start_revision=c.start_revision JOIN review_finding_versions f ON f.project_id=m.project_id AND f.run_id=m.id AND f.run_version_revision=m.version_revision WHERE c.project_id=? AND c.pull_number=? ORDER BY f.run_id,f.position LIMIT 10001` + +// Query text remains part of the retained intent digest. Pin only physical join +// order for current-reference reads; never replace the digest input with hints. +func automaticBasisQuery(query string, pinJoins bool) string { + if pinJoins { + return strings.ReplaceAll(query, " JOIN ", " CROSS JOIN ") + } + return query +} + +// The semantic digest excludes projection revisions, observation timestamps, +// attempt states and selection/operation transitions. Failed/cancelled requests +// therefore cannot create their own next automatic request. Only original source +// facts and deliberate controls, completed results and finding work change it. +func automaticPullBasis(ctx context.Context, tx *sql.Tx, project string, pull int64) (string, error) { + return automaticPullBasisChannel(ctx, tx, project, pull, "hosted") +} + +type automaticBasisRead struct { + prefix []byte + revision int64 + workspace bool + frame frontFrame + hasFrame bool +} + +// The channel semantic revision is independent of unrelated control edits. +func automaticChannelBasisRevision(ctx context.Context, tx *sql.Tx, project, channel string) (int64, error) { + s, err := readScheduling(ctx, tx, project) + if err != nil { + return 0, err + } + hosted, cli, err := schedulingBasisRevisions(ctx, tx, s) + if channel == "cli" { + return cli, err + } + return hosted, err +} + +// A planning pass owns one read snapshot. These shared facts never escape it. +func readAutomaticBasis(ctx context.Context, tx *sql.Tx, project, channel string) (automaticBasisRead, error) { + var out automaticBasisRead + var err error + out.revision, err = automaticChannelBasisRevision(ctx, tx, project, channel) + if err != nil { + return out, err + } + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name='review_current_pulls' AND type='table')`).Scan(&out.workspace); err != nil { + return out, err + } + out.frame, out.hasFrame, err = readFrontFrame(ctx, tx, project, channel) + if err != nil { + return out, err + } + var prefix bytes.Buffer + appendRows := automaticBasisAppender(ctx, tx, &prefix, channel, out.revision) + for _, query := range []string{ + `SELECT revision,automatic_hosted FROM review_scheduling WHERE project_id=?`, + `SELECT revision FROM review_execution_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, + `SELECT revision FROM review_policy_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, + } { + if err := appendRows(query, false, project); err != nil { + return out, err + } + } + out.prefix = prefix.Bytes() + return out, nil +} + +func automaticPullBasisChannel(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string) (string, error) { + shared, err := readAutomaticBasis(ctx, tx, project, channel) + if err != nil { + return "", err + } + return automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) +} + +// This historical label is part of the retained digest. Do not change it +// when tightening the SQL used to obtain the same valid rows. +func automaticAdjudicationBasisLabel(channel string) string { + return `SELECT a.evidence_id,a.revision FROM review_adjudication_state a JOIN review_execution_evidence e ON e.id=a.evidence_id AND e.project_id=a.project_id JOIN review_operations o ON o.id=e.operation_id AND o.project_id=e.project_id WHERE a.project_id=? AND o.pull_number=? AND (o.channel='` + channel + `' OR json_array_length(json_extract(e.body_json,'$.capture.review.Findings'))>0) ORDER BY a.evidence_id LIMIT 10001` +} + +func automaticAdjudicationBasisSQL(channel string) string { + // CASE keeps JSON functions away from unavailable input. A null/omitted + // slice was historically empty, not malformed. Keep same-channel rows + // and their contribution independent of the opposite-channel test. + return `WITH evidence AS ( + SELECT a.evidence_id,a.revision,CASE + WHEN o.channel='` + channel + `' THEN 1 + WHEN typeof(e.body_json)='text' AND length(CAST(e.body_json AS BLOB))<=` + strconv.Itoa(MaxEvidenceInputBytes+8192) + ` + THEN CASE WHEN json_valid(e.body_json) THEN CASE + WHEN json_type(e.body_json,'$.capture.review.Findings')='array' THEN json_array_length(e.body_json,'$.capture.review.Findings') + WHEN COALESCE(json_type(e.body_json,'$.capture.review.Findings'),'null')='null' THEN 0 + END END END AS count + FROM review_adjudication_state a JOIN review_execution_evidence e ON e.id=a.evidence_id AND e.project_id=a.project_id + JOIN review_operations o ON o.id=e.operation_id AND o.project_id=e.project_id + WHERE a.project_id=? AND o.pull_number=? + ) + SELECT CASE WHEN count IS NOT NULL THEN evidence_id END,revision FROM evidence + WHERE count IS NULL OR count>0 ORDER BY evidence_id LIMIT 10001` +} + +func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channel string, basisRevision int64) func(string, bool, ...any) error { + return func(query string, pinJoins bool, args ...any) error { + if channel == "cli" { + query = strings.ReplaceAll(query, "revision,automatic_hosted", "revision,automatic_cli") + } + h.Write([]byte(query)) + h.Write([]byte{0}) + executionQuery := automaticBasisQuery(query, pinJoins) + adjudication := query == automaticAdjudicationBasisLabel(channel) + if adjudication { + executionQuery = automaticAdjudicationBasisSQL(channel) + } + rows, err := tx.QueryContext(ctx, executionQuery, args...) + if err != nil { + return err + } + defer rows.Close() + cols, err := rows.Columns() + if err != nil { + return err + } + count := 0 + for rows.Next() { + count++ + if count > 10000 { + return automaticProjectStateFailure("overloaded", "Automatic scheduling needs a narrower retained review scope.", 503) + } + values := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range values { + ptrs[i] = &values[i] + } + if err = rows.Scan(ptrs...); err != nil { + return err + } + for i, v := range values { + if b, ok := v.([]byte); ok { + values[i] = string(b) + } + } + if adjudication && values[0] == nil { + return schedulingUnavailable() + } + // Keep the original query label and JSON framing. Only the + // channel's semantic revision differs after a relevant write. + if query == `SELECT revision,automatic_`+channel+` FROM review_scheduling WHERE project_id=?` { + values[0] = basisRevision + } + b, err := json.Marshal(values) + if err != nil { + return err + } + h.Write(b) + h.Write([]byte{'\n'}) + } + if err = rows.Err(); err != nil { + return err + } + return rows.Close() + } +} + +func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, shared automaticBasisRead) (string, error) { + basisRevision := shared.revision + h := sha256.New() + h.Write(shared.prefix) + appendRows := automaticBasisAppender(ctx, tx, h, channel, basisRevision) + queries := []struct { + sql string + args []any + }{ + {`SELECT revision,paused,reason FROM review_pull_scheduling WHERE project_id=? AND pull_number=?`, []any{project, pull}}, + {`SELECT epoch,grant_revision,closed,minimum,maximum,maximum_unbounded,used,dry,tapered FROM review_round_controls WHERE project_id=? AND pull_number=? AND channel='` + channel + `'`, []any{project, pull}}, + {automaticAdjudicationBasisLabel(channel), []any{project, pull}}, + {`SELECT id,revision,state,disposition,has_fix FROM review_finding_routes WHERE project_id=? AND (source_pull_number=? OR target_pull_number=?) ORDER BY id LIMIT 10001`, []any{project, pull, pull}}, + {`SELECT o.id,o.revision,o.status FROM review_adoption_targets t JOIN review_adoption_obligations o ON o.id=t.obligation_id AND o.project_id=t.project_id WHERE t.project_id=? AND t.pull_number=? ORDER BY o.id LIMIT 10001`, []any{project, pull}}, + } + for _, q := range queries { + if err := appendRows(q.sql, false, q.args...); err != nil { + return "", err + } + } + if shared.workspace { + if err := appendRows(`SELECT p.state,p.head_sha,p.base_ref,p.base_sha,json_extract(p.metadata_json,'$.is_draft') FROM review_current_pulls c JOIN review_pull_memberships m ON m.project_id=c.project_id AND m.number=c.number AND m.start_revision=c.start_revision JOIN review_pull_versions p ON p.project_id=m.project_id AND p.number=m.number AND p.version_revision=m.version_revision WHERE c.project_id=? AND c.number=?`, false, project, pull); err != nil { + return "", err + } + if err := appendRows(strings.ReplaceAll(automaticCurrentRunsBasisQuery, "'hosted'", "'"+channel+"'"), true, project, pull); err != nil { + return "", err + } + if err := appendRows(automaticCurrentFindingsBasisQuery, true, project, pull); err != nil { + return "", err + } + } + dependencies, err := automaticDependenciesWithFrame(ctx, tx, project, pull, channel, shared.frame, shared.hasFrame) + if err != nil { + return "", err + } + h.Write([]byte(encoded(dependencies))) + + return hex.EncodeToString(h.Sum(nil)), nil +} + +// Only a source-owned retained parent chain supplies dependency identity. +// These local facts can make a distinct intent eligible; they never substitute +// for the selection worker's fresh source or final predecessor guard. +func automaticDependencies(ctx context.Context, tx *sql.Tx, project string, pull int64) ([]any, error) { + return automaticDependenciesChannel(ctx, tx, project, pull, "hosted") +} + +func automaticDependenciesChannel(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string) ([]any, error) { + frame, found, err := readFrontFrame(ctx, tx, project, channel) + if err != nil { + return nil, err + } + return automaticDependenciesWithFrame(ctx, tx, project, pull, channel, frame, found) +} + +func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, frame frontFrame, found bool) ([]any, error) { + out := []any{} + if !found { + return out, nil + } + byNumber := make(map[int64]frontPull, len(frame.prefix)) + for _, p := range frame.prefix { + byNumber[p.Number] = p + } + current, found := byNumber[pull] + if !found { + return out, nil + } + seen := map[int64]bool{pull: true} + for parent := current.ParentPullNumber; parent != 0; { + if seen[parent] || len(seen) > 100 { + return nil, errors.Join(errAutomaticParentCycle, schedulingUnavailable()) + } + seen[parent] = true + p, exists := byNumber[parent] + if !exists { + out = append(out, []any{parent, "source_prefix_incomplete"}) + break + } + progress, err := channelProgress(ctx, tx, project, frame.repository, parent, channel) + if err != nil { + return nil, err + } + control, err := readRoundRecord(ctx, tx, project, parent, channel) + if err != nil { + return nil, err + } + obligations, err := sourceObligationCount(ctx, tx, project, parent) + if err != nil { + return nil, err + } + routes, err := pendingIncomingRoutes(ctx, tx, project, parent) + if err != nil { + return nil, err + } + var completed int64 + if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM review_comparison_proofs WHERE project_id=? AND pull_number=? AND channel='`+channel+`' AND state='ready'`, project, parent).Scan(&completed); err != nil { + return nil, err + } + out = append(out, []any{parent, p.HeadSHA, p.ParentPullNumber, p.ParentSHA, progress, control.Configured, control.Epoch, control.grantRevision, control.Closed, control.Used, control.Dry, control.Tapered, completed, obligations, routes}) + parent = p.ParentPullNumber + } + return out, nil +} + +// Planning can move on to a distinct unattempted PR without treating an +// operation's state transition as a reason to recreate that operation. A +// selected PR is suppressed by its own semantic basis, independently of peers. +func (e *Engine) automaticPlanningBasis(ctx context.Context, tx *sql.Tx, project string, c Configuration, ignoreSelection string) (string, bool, error) { + return e.automaticPlanningBasisChannel(ctx, tx, project, c, ignoreSelection, "hosted") +} + +func (e *Engine) automaticPlanningBasisChannel(ctx context.Context, tx *sql.Tx, project string, c Configuration, ignoreSelection string, channel string) (string, bool, error) { + limit, err := e.automaticHostedQueuedPrefixChannel(ctx, tx, project, c, channel) + if err != nil { + return "", false, err + } + return automaticPlanningBasisForPrefix(ctx, tx, project, c.Queue[:limit], ignoreSelection, channel) +} + +func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project string, queue []int64, ignoreSelection, channel string) (string, bool, error) { + var shared automaticBasisRead + if len(queue) > 0 { + var err error + shared, err = readAutomaticBasis(ctx, tx, project, channel) + if err != nil { + return "", false, err + } + } + values := make([]any, 0, len(queue)) + remaining := []int64{} + for _, pull := range queue { + basis, err := automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) + if err != nil { + return "", false, err + } + values = append(values, []any{pull, basis}) + p, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + return "", false, err + } + if p.Paused { + continue + } + pending, err := automaticHostedPendingPullChannel(ctx, tx, project, pull, channel) + if err != nil { + return "", false, err + } + if pending { + continue + } + var seen bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id<>? AND pull_number=? AND pull_basis_sha256=?)`, project, ignoreSelection, pull, basis).Scan(&seen); err != nil { + return "", false, err + } + if !seen { + remaining = append(remaining, pull) + } + } + sum := sha256.Sum256([]byte(encoded([]any{values, remaining}))) + return hex.EncodeToString(sum[:]), len(remaining) > 0, nil +} + +// A waiting request keeps its identity and deadline. Automatic selection may +// reconsider only earlier PRs, rather than duplicate that request or prefetch +// farther successors merely because the request is not executing yet. +func (e *Engine) automaticHostedQueuedPrefix(ctx context.Context, tx *sql.Tx, project string, c Configuration) (int, error) { + return e.automaticHostedQueuedPrefixChannel(ctx, tx, project, c, "hosted") +} + +func (e *Engine) automaticHostedQueuedPrefixChannel(ctx context.Context, tx *sql.Tx, project string, c Configuration, channel string) (int, error) { + queue, err := json.Marshal(c.Queue) + if err != nil { + return 0, err + } + rows, err := tx.QueryContext(ctx, `SELECT q.key,s.id,s.project_id,o.id,EXISTS(SELECT 1 FROM review_selection_quarantine d WHERE d.project_id=o.project_id AND d.original_operation_id=o.id) FROM review_operations o +JOIN json_each(?) q ON q.value=o.pull_number +LEFT JOIN review_selections s ON s.operation_id=o.id +WHERE o.project_id=? AND o.channel=? AND o.state='queued' +AND NOT (o.channel='cli' AND o.reason='cli_draft_wait') +AND NOT EXISTS(SELECT 1 FROM review_operation_waits w WHERE w.operation_id=o.id AND w.paused=1) +AND NOT EXISTS(SELECT 1 FROM review_pull_scheduling s WHERE s.project_id=o.project_id AND s.pull_number=o.pull_number AND s.paused=1) +ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) + if err != nil { + return 0, err + } + defer rows.Close() + for count := 0; rows.Next(); count++ { + if count >= 100 { + return 0, schedulingUnavailable() + } + var position int + var selection, selectionProject any + var operation string + var custodyPresent bool + if err := rows.Scan(&position, &selection, &selectionProject, &operation, &custodyPresent); err != nil { + return 0, err + } + if custodyPresent { + if err := requireUnquarantinedSelectionLink(ctx, tx, project, operation); err != nil { + if isLinkedSelectionCustodyHeld(err) { + continue + } + return 0, err + } + return 0, runUnavailable() + } + // A direct operation has no parent selection and keeps its position. + if selection == nil { + return position, nil + } + id, validID := selection.(string) + if selectionProject != project || !validID || !validRunID(id) { + return 0, schedulingUnavailable() + } + r, err := readRun(ctx, tx, project, id) + if err != nil { + return 0, err + } + if err = e.requireAutomaticRun(ctx, tx, r); err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "automation_authorization_changed" { + // Only the cross-PR fence changes. The immutable bound + // child is still pending for duplicate suppression. + continue + } + return 0, err + } + return position, nil + } + if err = rows.Err(); err != nil { + return 0, err + } + return len(c.Queue), rows.Close() +} + +func automaticHostedPendingPull(ctx context.Context, tx *sql.Tx, project string, pull int64) (bool, error) { + return automaticHostedPendingPullChannel(ctx, tx, project, pull, "hosted") +} + +func automaticHostedPendingPullChannel(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string) (bool, error) { + var pending bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND pull_number=? AND channel='`+channel+`' AND state IN('queued','preparing','posting','active','uncertain'))`, project, pull).Scan(&pending) + return pending, err +} + +func (e *Engine) automaticPullSuppressed(ctx context.Context, tx *sql.Tx, r Run, pull int64) (bool, error) { + // The fact-only evaluator may run without a persisted selection. + if r.ID == "" { + return false, nil + } + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil || attribution.revision == 0 { + return false, err + } + pending, err := automaticHostedPendingPullChannel(ctx, tx, r.ProjectID, pull, r.Channel) + if err != nil || pending { + return pending, err + } + c, _, err := readConfiguration(ctx, tx, r.ProjectID) + if err != nil { + return false, err + } + limit, err := e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + if err != nil { + return false, err + } + if position := slices.Index(c.Queue, pull); position < 0 || position >= limit { + return true, nil + } + basis, err := automaticPullBasisChannel(ctx, tx, r.ProjectID, pull, r.Channel) + if err != nil { + return false, err + } + var seen bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id<>? AND pull_number=? AND pull_basis_sha256=?)`, r.ProjectID, r.ID, pull, basis).Scan(&seen) + return seen, err +} +func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64) error { + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil || attribution.revision == 0 { + return err + } + c, _, err := readConfiguration(ctx, tx, r.ProjectID) + if err != nil { + return err + } + basis, _, err := e.automaticPlanningBasisChannel(ctx, tx, r.ProjectID, c, r.ID, r.Channel) + if err != nil { + return err + } + pullBasis := "" + if pull > 0 { + pullBasis, err = automaticPullBasisChannel(ctx, tx, r.ProjectID, pull, r.Channel) + if err != nil { + return err + } + } + _, err = tx.ExecContext(ctx, `UPDATE review_automatic_selections SET settled_basis_sha256=?,pull_number=?,pull_basis_sha256=? WHERE selection_id=? AND project_id=?`, basis, pull, pullBasis, r.ID, r.ProjectID) + return err +} 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_http.go b/internal/reviewexec/scheduling_http.go new file mode 100644 index 000000000..eaa7ec5a1 --- /dev/null +++ b/internal/reviewexec/scheduling_http.go @@ -0,0 +1,87 @@ +package reviewexec + +import ( + "encoding/json" + "net/http" + "strconv" + + "github.com/benhook1013/FireController/internal/core" +) + +func (e *Engine) registerSchedulingHTTP(mux *http.ServeMux) { + mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/scheduling", e.schedulingHTTP) + mux.HandleFunc("GET /api/v1/projects/{project_id}/reviews/pulls/{pull_number}/scheduling", e.pullSchedulingHTTP) + mux.HandleFunc("POST /api/v1/projects/{project_id}/reviews/pulls/{pull_number}/scheduling", e.pullSchedulingHTTP) +} +func (e *Engine) schedulingHTTP(w http.ResponseWriter, r *http.Request) { + scope, err := e.store.Scope(r, "read") + if err != nil { + core.WriteError(w, err) + return + } + if _, err = core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + out, err := e.ReadScheduling(r.Context(), scope) + if err != nil { + core.WriteError(w, err) + return + } + core.WriteJSON(w, 200, out) +} +func (e *Engine) pullSchedulingHTTP(w http.ResponseWriter, r *http.Request) { + permission := "read" + if r.Method == "POST" { + permission = "write" + } + scope, err := e.store.Scope(r, permission) + if err != nil { + core.WriteError(w, err) + return + } + raw := r.PathValue("pull_number") + pull, err := strconv.ParseInt(raw, 10, 64) + if err != nil || pull < 1 || pull > 2147483647 || strconv.FormatInt(pull, 10) != raw { + core.WriteError(w, invalid()) + return + } + if _, err = core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + if r.Method == http.MethodGet || r.Method == http.MethodHead { + out, err := e.ReadPullScheduling(r.Context(), scope, pull) + if err != nil { + core.WriteError(w, err) + return + } + core.WriteJSON(w, 200, out) + return + } + var wire struct { + ExpectedRevision *int64 `json:"expected_revision"` + Paused *bool `json:"paused"` + Reason json.RawMessage `json:"reason,omitempty"` + } + if err = core.ReadJSON(w, r, &wire); err != nil { + core.WriteError(w, err) + return + } + input := PullSchedulingRequest{ExpectedRevision: wire.ExpectedRevision, Paused: wire.Paused} + if len(wire.Reason) > 0 && (string(wire.Reason) == "null" || json.Unmarshal(wire.Reason, &input.Reason) != nil) { + core.WriteError(w, invalid()) + return + } + key, err := core.IdempotencyKey(r, "idempotency_key_required") + if err != nil { + core.WriteError(w, err) + return + } + out, err := e.ConfigurePullScheduling(r.Context(), scope, key, pull, input) + if err != nil { + core.WriteError(w, err) + return + } + core.WriteJSON(w, 200, out) +} diff --git a/internal/reviewexec/scheduling_pause_history_test.go b/internal/reviewexec/scheduling_pause_history_test.go new file mode 100644 index 000000000..50b6c1309 --- /dev/null +++ b/internal/reviewexec/scheduling_pause_history_test.go @@ -0,0 +1,45 @@ +package reviewexec + +import "testing" + +func TestSchedulingSnapshotRetainsPauseAuthority(t *testing.T) { + for _, corrupt := range []string{"", "unpaused-row", "missing-event", "duplicate-event", "malformed-event", "blob-event", "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 "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_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..04870c1b5 --- /dev/null +++ b/internal/reviewexec/scheduling_recovery_regression_test.go @@ -0,0 +1,281 @@ +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": + admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json=?`, strings.Repeat(" ", maxFrontPrefixBytes+1)) + 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_schema.go b/internal/reviewexec/scheduling_schema.go new file mode 100644 index 000000000..7c33554c1 --- /dev/null +++ b/internal/reviewexec/scheduling_schema.go @@ -0,0 +1,34 @@ +package reviewexec + +import ( + "context" + "github.com/benhook1013/FireController/internal/core" +) + +// SchedulingSchemaSQL owns optional new-request controls, not execution bindings +// or provider evidence. Existing installations start with no enabled settings. +func SchedulingSchemaSQL() []string { + return []string{ + `CREATE TABLE review_scheduling(project_id TEXT PRIMARY KEY REFERENCES projects(id),revision INTEGER NOT NULL CHECK(revision>0),automatic_hosted INTEGER NOT NULL CHECK(automatic_hosted IN(0,1)),actor_id TEXT NOT NULL,worker_id TEXT NOT NULL,credential_id TEXT NOT NULL,updated_at TEXT NOT NULL)`, + `CREATE TABLE review_pull_scheduling(project_id TEXT NOT NULL REFERENCES projects(id),pull_number INTEGER NOT NULL CHECK(pull_number BETWEEN 1 AND 2147483647),revision INTEGER NOT NULL CHECK(revision>0),paused INTEGER NOT NULL CHECK(paused IN(0,1)),reason TEXT NOT NULL,actor_id TEXT NOT NULL,updated_at TEXT NOT NULL,PRIMARY KEY(project_id,pull_number))`, + `CREATE TABLE review_automatic_selections(selection_id TEXT PRIMARY KEY REFERENCES review_selections(id),project_id TEXT NOT NULL REFERENCES projects(id),scheduling_revision INTEGER NOT NULL CHECK(scheduling_revision>0),basis_sha256 TEXT NOT NULL CHECK(length(basis_sha256)=64),settled_basis_sha256 TEXT NOT NULL DEFAULT '',pull_number INTEGER NOT NULL DEFAULT 0 CHECK(pull_number BETWEEN 0 AND 2147483647),pull_basis_sha256 TEXT NOT NULL DEFAULT '',actor_id TEXT NOT NULL,worker_id TEXT NOT NULL,credential_id TEXT NOT NULL,UNIQUE(project_id,basis_sha256))`, + `CREATE INDEX review_automatic_selections_settled ON review_automatic_selections(project_id,settled_basis_sha256)`, + `CREATE INDEX review_automatic_selections_pull ON review_automatic_selections(project_id,pull_number,pull_basis_sha256)`, + } +} +func EnsureSchedulingSchema(ctx context.Context, store *core.Store) error { + return store.EnsureSchema(ctx, "review_scheduling", SchedulingSchemaSQL(), schedulingV2MigrationSQL()) +} + +const schedulingAutomaticCLIColumn = `automatic_cli INTEGER NOT NULL DEFAULT 0 CHECK(automatic_cli IN(0,1))` + +func schedulingV2MigrationSQL() []string { + return []string{`ALTER TABLE review_scheduling ADD COLUMN ` + schedulingAutomaticCLIColumn} +} + +// SchedulingSchemaV2SQL is the canonical physical shape after the additive migration. +func SchedulingSchemaV2SQL() []string { + statements := SchedulingSchemaSQL() + statements[0] = statements[0][:len(statements[0])-1] + ", " + schedulingAutomaticCLIColumn + ")" + return statements +} diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go new file mode 100644 index 000000000..0231bc6c2 --- /dev/null +++ b/internal/reviewexec/scheduling_snapshot.go @@ -0,0 +1,353 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "strconv" + "strings" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/strictjson" +) + +// ValidateSchedulingSnapshot checks retained control/attribution, not current +// authority: revoked credentials and retired authors remain valid history. +// Accept the original Hosted-only domain and the additive CLI setting. +func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { + var version string + if err := tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_scheduling'`).Scan(&version); err != nil { + return err + } + cli := "0" + channels := "'hosted'" + switch version { + case "1": + // Version one predates automatic CLI scheduling. + case "2": + cli = "automatic_cli" + channels = "'hosted','cli'" + default: + return schedulingUnavailable() + } + rows, err := tx.QueryContext(ctx, `SELECT project_id,revision,automatic_hosted,`+cli+`,actor_id,worker_id,credential_id,updated_at FROM review_scheduling`) + if err != nil { + return err + } + for rows.Next() { + var project, actor, worker, credential, at string + var revision int64 + var enabled, cliEnabled bool + if err = scanSchedulingSnapshot(rows, &project, &revision, &enabled, &cliEnabled, &actor, &worker, &credential, &at); err != nil { + break + } + hostedEnabled := enabled + enabled = enabled || cliEnabled + if !identifier.MatchString(project) || revision < 1 || !identifier.MatchString(actor) || !roundTime(at) || worker != "" && !identifier.MatchString(worker) || enabled && (!identifier.MatchString(worker) || !identifier.MatchString(credential)) || !enabled && credential != "" { + err = schedulingUnavailable() + break + } + _, _, err = schedulingBasisRevisions(ctx, tx, schedulingRecord{Scheduling: Scheduling{ProjectID: project, Revision: revision, AutomaticHosted: hostedEnabled, AutomaticCLI: cliEnabled}, actor: actor}) + if err != nil { + break + } + } + if err == nil { + err = rows.Err() + } + closeErr := rows.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + // A genuine project scheduling event must have a projection at least + // as new. Only projects with no retained history default to revision zero. + var ahead bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events e + LEFT JOIN review_scheduling s ON s.project_id=e.project_id + WHERE e.event_type='review.scheduling_updated' AND e.resource_id=e.project_id + AND (s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) + if err != nil { + return err + } + if ahead { + return schedulingUnavailable() + } + + rows, err = tx.QueryContext(ctx, `SELECT project_id,pull_number,revision,paused,reason,actor_id,updated_at FROM review_pull_scheduling`) + if err != nil { + return err + } + controls := 0 + for rows.Next() { + var s PullScheduling + if err = scanSchedulingSnapshot(rows, &s.ProjectID, &s.PullNumber, &s.Revision, &s.Paused, &s.Reason, &s.ActorID, &s.UpdatedAt); err != nil { + break + } + if !identifier.MatchString(s.ProjectID) || s.PullNumber < 1 || s.PullNumber > 2147483647 || s.Revision < 1 || !identifier.MatchString(s.ActorID) || !roundTime(s.UpdatedAt) || !validSchedulingReason(s.Reason) || !s.Paused && s.Reason != "" { + err = schedulingUnavailable() + break + } + controls++ + } + if err == nil { + err = rows.Err() + } + closeErr = rows.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + if err := validatePullSchedulingEvents(ctx, tx, controls); err != nil { + return err + } + if err := validateOrphanPullSchedulingEvents(ctx, tx); err != nil { + return err + } + var bad bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_scheduling s WHERE (s.worker_id<>'' AND NOT EXISTS(SELECT 1 FROM workers w WHERE w.project_id=s.project_id AND w.id=s.worker_id)) OR ((s.automatic_hosted=1 OR `+strings.ReplaceAll(cli, "automatic_cli", "s.automatic_cli")+`=1) AND NOT EXISTS(SELECT 1 FROM credentials c WHERE c.id=s.credential_id AND c.principal_id=s.actor_id))) OR EXISTS(SELECT 1 FROM review_automatic_selections a WHERE NOT EXISTS(SELECT 1 FROM workers w WHERE w.project_id=a.project_id AND w.id=a.worker_id) OR NOT EXISTS(SELECT 1 FROM credentials c WHERE c.id=a.credential_id AND c.principal_id=a.actor_id))`).Scan(&bad) + if err != nil { + return err + } + if bad { + return schedulingUnavailable() + } + var selectionVersion string + if err := tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_selection'`).Scan(&selectionVersion); err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + custodyJoin, linked, held := "", "s.operation_id", "0" + if selectionVersion == "2" { + custodyJoin = " LEFT JOIN review_selection_quarantine q ON q.selection_id=s.id AND q.project_id=s.project_id" + linked = "COALESCE(s.operation_id,q.original_operation_id)" + // The record is only a backup provenance exception. Runtime readers + // separately fence this operation; the held row cannot authorize it. + held = "(s.state='held' AND s.reason='linked_selection_quarantined' AND s.operation_id IS NULL AND q.selection_id IS NOT NULL)" + } + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections a LEFT JOIN review_selections s ON s.id=a.selection_id`+custodyJoin+` + LEFT JOIN review_scheduling c ON c.project_id=a.project_id LEFT JOIN review_operations o ON o.id=`+linked+` + WHERE s.id IS NULL OR s.project_id<>a.project_id OR s.channel NOT IN(`+channels+`) OR s.actor_id<>a.actor_id OR s.worker_id<>a.worker_id OR c.project_id IS NULL + OR a.scheduling_revision>c.revision OR (a.pull_number=0 AND (a.pull_basis_sha256<>'' OR s.state='selected')) + OR (a.pull_number<>0 AND ((s.state<>'selected' AND NOT `+held+`) OR o.id IS NULL OR o.pull_number<>a.pull_number + OR o.project_id<>a.project_id OR o.channel<>s.channel OR o.actor_id<>a.actor_id OR o.worker_id<>a.worker_id)))`).Scan(&bad) + if err != nil { + return err + } + if bad { + return schedulingUnavailable() + } + rows, err = tx.QueryContext(ctx, `SELECT selection_id,project_id,scheduling_revision,basis_sha256,settled_basis_sha256,pull_number,pull_basis_sha256,actor_id,worker_id,credential_id FROM review_automatic_selections`) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var selection, project, basis, settled, pullBasis, actor, worker, credential string + var revision, pull int64 + if err = scanSchedulingSnapshot(rows, &selection, &project, &revision, &basis, &settled, &pull, &pullBasis, &actor, &worker, &credential); err != nil { + return err + } + if !validRunID(selection) || !identifier.MatchString(project) || revision < 1 || !hash.MatchString(basis) || settled != "" && !hash.MatchString(settled) || pull < 0 || pull > 2147483647 || pull > 0 && !hash.MatchString(pullBasis) || !identifier.MatchString(actor) || !identifier.MatchString(worker) || !identifier.MatchString(credential) { + return core.Fail("storage_unavailable", "Stored automatic review attribution is unavailable.", 503) + } + } + if err = rows.Err(); err != nil { + return err + } + return rows.Close() +} + +// Preserve SQLite storage types before checking control and attribution values. +// database/sql otherwise accepts conversions (notably BLOB to string) that the +// live control readers deliberately reject. Genuine scan/query errors propagate. +func scanSchedulingSnapshot(row interface{ Scan(...any) error }, destinations ...any) error { + values := make([]any, len(destinations)) + pointers := make([]any, len(values)) + for i := range values { + pointers[i] = &values[i] + } + if err := row.Scan(pointers...); err != nil { + return err + } + for i, destination := range destinations { + switch target := destination.(type) { + case *string: + value, ok := values[i].(string) + if !ok { + return schedulingUnavailable() + } + *target = value + case *int64: + value, ok := values[i].(int64) + if !ok { + return schedulingUnavailable() + } + *target = value + case *bool: + value, ok := values[i].(int64) + if !ok || value < 0 || value > 1 { + return schedulingUnavailable() + } + *target = value == 1 + default: + return schedulingUnavailable() + } + } + return nil +} + +// An absent control reads as resumed. Refuse a restore if its latest +// retained event instead proves a pause or cannot be read as that identity. +// Rank every event before projecting its native revision; never fall back to +// an older valid resume when the winning revision cannot be trusted. +const orphanPullSchedulingSQL = `WITH orphan AS ( + SELECT e.project_id,e.resource_id,e.revision,e.sequence, + CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END AS payload, + ROW_NUMBER() OVER (PARTITION BY e.project_id,e.resource_id ORDER BY e.revision DESC,e.sequence DESC) AS newest, + COUNT(*) OVER (PARTITION BY e.project_id,e.resource_id,e.revision) AS matches + FROM events e LEFT JOIN review_pull_scheduling s + ON s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) + AND CAST(s.pull_number AS TEXT)=e.resource_id + WHERE e.event_type='review.pull_scheduling_updated' AND s.pull_number IS NULL + )` + +const latestOrphanPullResumesSQL = ` + FROM orphan o JOIN events e ON e.sequence=o.sequence + WHERE o.newest=1` + +func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+` + SELECT CASE WHEN typeof(o.project_id)='text' THEN o.project_id END,o.resource_id, + CASE WHEN typeof(o.revision)='integer' THEN o.revision END,o.payload,o.matches, + CASE WHEN typeof(e.actor_id)='text' AND length(CAST(e.actor_id AS BLOB))<=128 THEN e.actor_id END, + CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END`+latestOrphanPullResumesSQL) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + if err := validateOrphanPullSchedulingEvent(rows); err != nil { + return err + } + } + if err := rows.Err(); err != nil { + return err + } + return rows.Close() +} + +func validateOrphanPullSchedulingEvent(row interface{ Scan(...any) error }) error { + var storedResource, revision any + var matches int64 + var project, payload, actor, createdAt sql.NullString + if err := row.Scan(&project, &storedResource, &revision, &payload, &matches, &actor, &createdAt); err != nil { + return err + } + resource, ok := storedResource.(string) + if !ok || len(resource) > 10 { + return schedulingUnavailable() + } + nativeRevision, revisionOK := revision.(int64) + pull, err := strconv.ParseInt(resource, 10, 32) + if err != nil || pull < 1 || strconv.FormatInt(pull, 10) != resource || !revisionOK || nativeRevision < 1 || matches != 1 || + !validPullSchedulingPayload(payload, pull, false) || !project.Valid || !identifier.MatchString(project.String) || + !actor.Valid || !identifier.MatchString(actor.String) || !createdAt.Valid || !roundTime(createdAt.String) { + return schedulingUnavailable() + } + return nil +} + +// RestoreHistoricalPullResumes preserves the CAS revision of valid legacy +// resume events on an offline restored copy. The caller owns its restore +// transaction. No event, credential, or project scheduling authority changes. +func RestoreHistoricalPullResumes(ctx context.Context, tx *sql.Tx) error { + var state string + if err := tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='restore:state'`).Scan(&state); err != nil { + return err + } + if state != "inactive" { + return schedulingUnavailable() + } + var version string + err := tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_scheduling'`).Scan(&version) + if errors.Is(err, sql.ErrNoRows) { + // Older backups may omit the scheduling domain altogether. + return nil + } + if err != nil { + return err + } + if version != "1" && version != "2" { + return schedulingUnavailable() + } + if err := validateOrphanPullSchedulingEvents(ctx, tx); err != nil { + return err + } + // Both reads are in the same transaction, and no projection was inserted + // until the complete set was validated. Keep the source event sequence. + _, err = tx.ExecContext(ctx, orphanPullSchedulingSQL+` + INSERT INTO review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at) + SELECT o.project_id,CAST(o.resource_id AS INTEGER),o.revision,0,'',e.actor_id,e.created_at`+latestOrphanPullResumesSQL) + return err +} + +func validPullSchedulingPayload(payload sql.NullString, pull int64, paused bool) bool { + var event struct { + PullNumber int64 `json:"pull_number"` + Paused *bool `json:"paused"` + } + return payload.Valid && strictjson.Decode([]byte(payload.String), &event) == nil && + event.PullNumber == pull && event.Paused != nil && *event.Paused == paused +} + +// Scan the event journal once for existing pull controls. With events on the +// outer side of this join, SQLite can seek the control's composite primary key +// rather than reading the same project's event history once for each control. +// Ordered qualifying matches keep duplicate detection constant-space. +const pullSchedulingSnapshotEventsSQL = `SELECT s.project_id,s.pull_number,s.revision,s.paused,s.actor_id, + e.revision,e.actor_id,CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END + FROM events e CROSS JOIN review_pull_scheduling s + WHERE e.event_type='review.pull_scheduling_updated' AND s.project_id=e.project_id + AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id + AND e.revision>=s.revision + ORDER BY s.project_id,s.pull_number` + +func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) error { + if controls == 0 { + return nil + } + rows, err := tx.QueryContext(ctx, pullSchedulingSnapshotEventsSQL) + if err != nil { + return err + } + defer rows.Close() + count := 0 + var lastProject string + var lastPull int64 + for rows.Next() { + var project, actor, eventActor string + var pull, controlRevision, paused int64 + var nativeRevision any + var payload sql.NullString + if err := rows.Scan(&project, &pull, &controlRevision, &paused, &actor, &nativeRevision, &eventActor, &payload); err != nil { + return err + } + revision, integer := nativeRevision.(int64) + if (project == lastProject && pull == lastPull) || !integer || revision != controlRevision || eventActor != actor || !validPullSchedulingPayload(payload, pull, paused == 1) { + return schedulingUnavailable() + } + count++ + lastProject, lastPull = project, pull + } + if err := rows.Err(); err != nil { + return err + } + if count != controls { + return schedulingUnavailable() + } + return rows.Close() +} 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_snapshot_event_integrity_test.go b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go new file mode 100644 index 000000000..eee412f6b --- /dev/null +++ b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go @@ -0,0 +1,176 @@ +package reviewexec + +import ( + "database/sql" + "testing" +) + +func schedulingEventSnapshotFixture(t *testing.T) *sql.Tx { + t.Helper() + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatal(err) + } + db.SetMaxOpenConns(1) + t.Cleanup(func() { db.Close() }) + tx, err := db.BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { tx.Rollback() }) + // These are in-memory snapshot inputs, not changes to a running project. + // Keep event revision untyped to model the native value delivered to Scan. + for _, statement := range []string{ + "CREATE TABLE metadata(key,value)", + "INSERT INTO metadata VALUES ('schema:review_scheduling','2')", + "CREATE TABLE events(sequence INTEGER PRIMARY KEY, project_id, resource_id, event_type, revision, actor_id, payload_json, created_at)", + "CREATE TABLE review_scheduling(project_id,revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at)", + "CREATE TABLE review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at)", + "CREATE TABLE review_automatic_selections(selection_id,project_id,scheduling_revision,basis_sha256,settled_basis_sha256,pull_number,pull_basis_sha256,actor_id,worker_id,credential_id)", + "CREATE TABLE review_selections(id,project_id,channel,state,actor_id,worker_id,operation_id)", + "CREATE TABLE review_operations(id,project_id,pull_number,channel,actor_id,worker_id)", + "CREATE TABLE workers(project_id,id)", + "CREATE TABLE credentials(id,principal_id)", + } { + if _, err := tx.ExecContext(t.Context(), statement); err != nil { + t.Fatal(err) + } + } + return tx +} + +func TestSchedulingSnapshotRequiresEnabledProjectProjection(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + if err := ValidateSchedulingSnapshot(t.Context(), tx); err != nil { + t.Fatalf("project with no scheduling history: %v", err) + } + // An ordinary configure event in a partial snapshot with no control row. + _, 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}')`) + if err != nil { + t.Fatal(err) + } + attemptCode(t, ValidateSchedulingSnapshot(t.Context(), tx), "storage_unavailable") +} + +func TestSchedulingSnapshotRequiresNativeEventRevision(t *testing.T) { + for _, tc := range []struct { + name string + revision any + valid bool + }{{"integer", int64(1), true}, {"real", float64(1), 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','2','review.pull_scheduling_updated',?,'test-actor','{"pull_number":2,"paused":true}')`, tc.revision) + if err != nil { + t.Fatal(err) + } + if _, err := tx.ExecContext(t.Context(), `INSERT INTO review_pull_scheduling VALUES ('test-project',2,1,1,'','test-actor',?)`, stamp()); err != nil { + t.Fatal(err) + } + err = ValidateSchedulingSnapshot(t.Context(), tx) + if tc.valid { + if err != nil { + t.Fatalf("native revision refused: %v", err) + } + } else { + attemptCode(t, err, "storage_unavailable") + } + }) + } +} + +// Different projects can legitimately schedule the same pull number. Each +// one's newest event must remain attached to its own represented control. +func TestSchedulingSnapshotPullEventStreamKeepsProjectIdentity(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + if _, err := tx.ExecContext(t.Context(), `INSERT INTO review_pull_scheduling VALUES + ('test-project',2,2,0,'','test-actor',?), + ('other-project',2,1,1,'','other-actor',?)`, stamp(), stamp()); err != nil { + t.Fatal(err) + } + if _, err := tx.ExecContext(t.Context(), `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json) VALUES + ('test-project','2','review.pull_scheduling_updated',1,'test-actor','{"pull_number":2,"paused":true}'), + ('other-project','2','review.pull_scheduling_updated',1,'other-actor','{"pull_number":2,"paused":true}'), + ('test-project','2','review.pull_scheduling_updated',2,'test-actor','{"pull_number":2,"paused":false}'), + ('other-project','2','ordinary.event',9,'other-actor','{}')`); err != nil { + t.Fatal(err) + } + if err := ValidateSchedulingSnapshot(t.Context(), tx); err != nil { + t.Fatal(err) + } +} + +func TestOrphanResumeRequiresNativeRevisionWithoutChangingCompatibility(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + // Read-only codec probes. No malformed event is installed or ranked. + for _, tc := range []struct { + name string + revision any + valid bool + }{ + {"integer", int64(2), true}, + {"real", float64(2), false}, + {"text", "2", false}, + {"null", nil, false}, + } { + t.Run(tc.name, func(t *testing.T) { + row := tx.QueryRowContext(t.Context(), `SELECT 'test-project', '2', ?, '{"pull_number":2,"paused":false}', 1, 'test-actor', ?`, tc.revision, stamp()) + err := validateOrphanPullSchedulingEvent(row) + if tc.valid { + if err != nil { + t.Fatal(err) + } + } else { + attemptCode(t, err, "storage_unavailable") + } + }) + } +} + +func TestSchedulingSnapshotValidatesLatestOrphanResume(t *testing.T) { + for _, tc := range []struct { + name string + revision any + actor any + at any + }{ + {"text-revision", "1", "test-actor", stamp()}, + {"invalid-actor", int64(3), "invalid actor", stamp()}, + {"blob-actor", int64(3), []byte("test-actor"), stamp()}, + {"invalid-time", int64(3), "test-actor", "not-time"}, + {"blob-time", int64(3), "test-actor", []byte(stamp())}, + } { + t.Run(tc.name, func(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + const insert = `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json,created_at) + VALUES ('test-project','2','review.pull_scheduling_updated',?,?,'{"pull_number":2,"paused":false}',?)` + if _, err := tx.ExecContext(t.Context(), insert, int64(2), "test-actor", stamp()); err != nil { + t.Fatal(err) + } + if err := ValidateSchedulingSnapshot(t.Context(), tx); err != nil { + t.Fatalf("valid legacy resume rejected: %v", err) + } + if _, err := tx.ExecContext(t.Context(), insert, tc.revision, tc.actor, tc.at); err != nil { + t.Fatal(err) + } + attemptCode(t, ValidateSchedulingSnapshot(t.Context(), tx), "storage_unavailable") + }) + } +} + +func TestOrphanResumeRejectsBlobResourceInSnapshotAndRestore(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + if _, err := tx.ExecContext(t.Context(), `INSERT INTO metadata VALUES('restore:state','inactive'); + INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json,created_at) + VALUES ('test-project',X'32','review.pull_scheduling_updated',1,'test-actor','{"pull_number":2,"paused":false}',?)`, stamp()); err != nil { + t.Fatal(err) + } + attemptCode(t, ValidateSchedulingSnapshot(t.Context(), tx), "storage_unavailable") + attemptCode(t, RestoreHistoricalPullResumes(t.Context(), tx), "storage_unavailable") + var rows int + if err := tx.QueryRowContext(t.Context(), `SELECT count(*) FROM review_pull_scheduling`).Scan(&rows); err != nil || rows != 0 { + t.Fatalf("invalid resource produced a projection: %d %v", rows, err) + } +} diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go new file mode 100644 index 000000000..6119e0205 --- /dev/null +++ b/internal/reviewexec/scheduling_source_retry.go @@ -0,0 +1,105 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" +) + +// Recheck recovery fences during every admission snapshot, including after +// source I/O. Interrupted initial reads retain ordinary authorization continuity. +// Completed source holds require the exact accepted scheduling revision even +// after further interrupted reads; incomplete transition evidence is conservative. +func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (string, error) { + if !validChannel(r.Channel) || r.Revision < 4 { + return "", nil + } + var retainedRevision any + err := tx.QueryRowContext(ctx, `SELECT scheduling_revision FROM review_automatic_selections WHERE project_id=? AND selection_id=?`, r.ProjectID, r.ID).Scan(&retainedRevision) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + if err != nil { + return "", err + } + // Compare native SQLite integers, not values coerced by Scan into int64. + accepted, validRevision := retainedRevision.(int64) + if !validRevision || accepted < 1 { + return "", schedulingUnavailable() + } + current, err := readScheduling(ctx, tx, r.ProjectID) + if err != nil { + return "", err + } + if current.Revision == 0 { + return "automation_authorization_changed", nil + } + initial, err := automaticSourceInitialRead(ctx, tx, r) + if err != nil || initial { + return "", err + } + if accepted != current.Revision { + return "automation_authorization_changed", nil + } + superseded, err := automaticSourceSuperseded(ctx, tx, r) + if err != nil { + return "", err + } + if superseded { + return "selection_superseded", nil + } + return "", nil +} + +// A revision alone cannot distinguish restart recovery from a completed hold. +// Prove every retained transition was an unfinished read before relaxing the +// exact-revision fence. A held event (whatever its reason), missing/duplicate +// revision or malformed payload keeps that fence. Aggregate in SQL rather than +// copying an unbounded event history into each admission snapshot. +func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, error) { + var count, distinct, first, last, invalid int64 + err := tx.QueryRowContext(ctx, `SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( + CASE WHEN typeof(revision)='integer' AND json_valid(payload_json) THEN + CASE WHEN json_extract(payload_json,'$.state')=CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END + AND json_extract(payload_json,'$.reason')='' AND (revision<>? OR json_extract(payload_json,'$.state')=?) THEN 0 ELSE 1 END + ELSE 1 END),0) + FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' AND revision BETWEEN 2 AND ?`, r.Revision, r.State, r.ProjectID, r.ID, r.Revision).Scan(&count, &distinct, &first, &last, &invalid) + if err != nil { + return false, err + } + return count == r.Revision-1 && distinct == count && first == 2 && last == r.Revision && invalid == 0, nil +} + +func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, error) { + // Any later or simultaneous same-channel intent supersedes this recovery, even if + // that intent was cancelled, denied, held or completed. A directly submitted + // operation is also a fence; never recover behind its cancellation/uncertainty. + // Compare parsed times, not RFC3339 text with variable fractional precision. + // For rows with no acceptance event, millisecond ties conservatively fence. + // Event sequence is the durable acceptance order even if the wall clock + // moves backwards. Missing acceptance evidence is not permission to retry. + var accepted int64 + err := tx.QueryRowContext(ctx, `SELECT sequence FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_requested' AND revision=1 ORDER BY sequence DESC LIMIT 1`, r.ProjectID, r.ID).Scan(&accepted) + if errors.Is(err, sql.ErrNoRows) { + return true, nil + } + if err != nil { + return false, err + } + var superseded bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM review_selections s WHERE s.project_id=? AND s.channel=? AND s.id<>? + AND julianday(s.created_at)>=julianday(?) + AND NOT EXISTS(SELECT 1 FROM events e WHERE e.project_id=s.project_id AND e.resource_id=s.id AND e.event_type='review.selection_requested' AND e.revision=1) +) OR EXISTS( + SELECT 1 FROM review_operations o WHERE o.project_id=? AND o.channel=? AND julianday(o.created_at)>=julianday(?) + AND NOT EXISTS(SELECT 1 FROM events e WHERE e.project_id=o.project_id AND e.resource_id=o.id AND e.event_type='review.requested' AND e.revision=1) +) OR EXISTS( + SELECT 1 FROM events e JOIN review_selections s ON s.project_id=e.project_id AND s.id=e.resource_id + WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.selection_requested' AND e.revision=1 AND s.channel=? +) OR EXISTS( + SELECT 1 FROM events e JOIN review_operations o ON o.project_id=e.project_id AND o.id=e.resource_id + WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.requested' AND e.revision=1 AND o.channel=? +)`, r.ProjectID, r.Channel, r.ID, r.CreatedAt, r.ProjectID, r.Channel, r.CreatedAt, r.ProjectID, accepted, r.Channel, r.ProjectID, accepted, r.Channel).Scan(&superseded) + return superseded, err +} diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go new file mode 100644 index 000000000..303f3bce1 --- /dev/null +++ b/internal/reviewexec/scheduling_test.go @@ -0,0 +1,508 @@ +package reviewexec + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/core" +) + +func schedulingFixture(t *testing.T) *attemptFixture { + return schedulingFixtureWithQueue(t, []int64{2, 4}) +} + +func schedulingFixtureWithQueue(t *testing.T, queue []int64) *attemptFixture { + t.Helper() + f := selectionFixtureWithQueue(t, queue) + mux := http.NewServeMux() + f.e.Register(mux) + f.handler = mux + return f +} + +func schedulingPause(t *testing.T, f *attemptFixture, pull, revision int64, paused bool) { + t.Helper() + _, err := f.e.ConfigurePullScheduling(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), core.NewID("pause"), pull, PullSchedulingRequest{ExpectedRevision: &revision, Paused: &paused, Reason: "Fix in progress"}) + if err != nil { + t.Fatal(err) + } +} + +func TestSchedulingHTTPDefaultsStrictCASAndPermissions(t *testing.T) { + f := schedulingFixture(t) + call := func(method, path, token, key, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, "/api/v1/projects/"+attemptProject+"/reviews/"+path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+token) + r.Header.Set("X-FC-Worker", "selection-worker") + if key != "" { + r.Header.Set("Idempotency-Key", key) + } + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + return w + } + project := call("GET", "scheduling", f.reader, "", "") + if project.Code != 200 || strings.TrimSpace(project.Body.String()) != `{"paused_pulls":[],"project_id":"exec-project-one","revision":0,"automatic_cli":false,"automatic_hosted":false}` { + t.Fatal(project.Code, project.Body.String()) + } + checkPullScheduling := func(w *httptest.ResponseRecorder, revision int64, paused bool, reason string) { + t.Helper() + var p PullScheduling + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || + p.ProjectID != attemptProject || p.PullNumber != 2 || p.Paused != paused || p.Revision != revision || p.Reason != reason { + t.Fatal(w.Code, w.Body.String()) + } + } + const pull = "pulls/2/scheduling" + checkPullScheduling(call("GET", pull, f.reader, "", ""), 0, false, "") + for _, path := range []string{"scheduling", pull} { + head := call("HEAD", path, f.reader, "", "") + if head.Code != http.StatusOK || !strings.HasPrefix(head.Header().Get("Content-Type"), "application/json") { + t.Fatalf("HEAD %s must use the read path: status=%d body=%s", path, head.Code, head.Body.String()) + } + } + journal := snapshotTable(t, f, "events") + // Even a project manager cannot turn on generation through this foundation slice. + admissionSQL(t, f, `UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'`) + if w := call("POST", "scheduling", f.writer, "disabled-project-post", `{"expected_revision":0,"automatic_hosted":true,"automatic_cli":true}`); w.Code != http.StatusMethodNotAllowed { + t.Fatal(w.Code, w.Body.String()) + } + if w := call("GET", "scheduling", f.reader, "", ""); w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), project.Body.Bytes()) || journal != snapshotTable(t, f, "events") { + t.Fatal("project POST changed scheduling or history", w.Code, w.Body.String()) + } + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + const pause = `{"expected_revision":0,"paused":true,"reason":"Fixing"}` + if w := call("POST", pull, f.reader, "reader-pause", pause); w.Code != http.StatusForbidden { + t.Fatal(w.Code, w.Body.String()) + } + for _, body := range []string{`{"expected_revision":0,"paused":null}`, `{"expected_revision":0,"paused":true,"reason":null}`, `{"expected_revision":0,"paused":true,"reason":"\n"}`} { + if w := call("POST", pull, f.writer, core.NewID("key"), body); w.Code != 400 { + t.Fatal(w.Code, w.Body.String()) + } + } + first := call("POST", pull, f.writer, "pause", pause) + var receipt Receipt + if first.Code != http.StatusOK || json.Unmarshal(first.Body.Bytes(), &receipt) != nil || receipt.ID != "2" || receipt.State != "pull_scheduling_updated" || receipt.Revision != 1 { + t.Fatal(first.Code, first.Body.String()) + } + checkPullScheduling(call("GET", pull, f.reader, "", ""), 1, true, "Fixing") + if w := call("POST", pull, f.writer, "stale", `{"expected_revision":0,"paused":false}`); w.Code != http.StatusConflict { + t.Fatal(w.Code, w.Body.String()) + } + if w := call("POST", pull, f.writer, "pause", pause); w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), first.Body.Bytes()) { + t.Fatal(w.Code, w.Body.String()) + } + if w := call("POST", pull, f.writer, "resume", `{"expected_revision":1,"paused":false,"reason":"discarded"}`); w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + checkPullScheduling(call("GET", pull, f.reader, "", ""), 2, false, "") +} + +func TestSchedulingPausedBothChannelsPreservesQueuedIdentityAndOperationPause(t *testing.T) { + f := schedulingFixture(t) + r := f.enqueue(t, attemptProject, "existing", "cli", 2, 1) + schedulingPause(t, f, 2, 0, true) + before := roundTables(t, f) + for _, channel := range []string{"cli", "hosted"} { + _, err := f.e.Enqueue(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), core.NewID("key"), Request{ExpectedConfigurationRevision: 1, PullNumber: 2, HeadSHA: strings.Repeat("a", 40), Channel: channel}) + attemptCode(t, err, "pull_scheduling_paused") + } + a, err := f.e.StartAttempt(t.Context(), attemptProject, r.ID) + if err != nil || a.ID != "" { + t.Fatal(a, err) + } + if roundTables(t, f) != before { + t.Fatal("paused admission changed retained state") + } + schedulingPause(t, f, 2, 1, false) + a, err = f.e.StartAttempt(t.Context(), attemptProject, r.ID) + if err != nil || a.ID == "" { + t.Fatal(a, err) + } + schedulingPause(t, f, 2, 2, true) + _, err = f.e.ExecutionContext(t.Context(), attemptProject, r.ID) + attemptCode(t, err, "pull_scheduling_paused") + // A separate operation pause is not cleared by resuming PR scheduling. + other := f.enqueue(t, attemptProject, "other", "hosted", 4, 1) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + _, err = f.e.ControlOperation(t.Context(), scope, "operation-pause", other.ID, OperationControl{ExpectedRevision: 1, Action: "pause"}) + if err != nil { + t.Fatal(err) + } + schedulingPause(t, f, 4, 0, true) + schedulingPause(t, f, 4, 1, false) + op, err := f.e.ReadOperation(t.Context(), scope, other.ID) + if err != nil || op.Wait == nil || !op.Wait.Paused { + t.Fatal(op, err) + } +} + +func TestSchedulingCooldownPauseKeepsOriginalTimerAndCollectionContinues(t *testing.T) { + f, a, in, now := queuedCooldown(t) + scope := f.scope(t, attemptProject, f.writer, false) + pause := true + zero := int64(0) + if _, err := f.e.ConfigurePullScheduling(t.Context(), scope, "pr-pause", 2, PullSchedulingRequest{ExpectedRevision: &zero, Paused: &pause}); err != nil { + t.Fatal(err) + } + original := snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "review_hosted_preflight") + snapshotTable(t, f, "review_hosted_allowance_queries") + snapshotTable(t, f, "review_hosted_observations") + *now = in.Observation.RetryNotBefore + pending, err := f.e.pending(t.Context()) + if err != nil || len(pending) != 0 { + t.Fatal(pending, err) + } + next, err := f.e.StartAttempt(t.Context(), attemptProject, a.OperationID) + if err != nil || next.ID != "" { + t.Fatal(next, err) + } + pause = false + one := int64(1) + if _, err = f.e.ConfigurePullScheduling(t.Context(), scope, "pr-resume", 2, PullSchedulingRequest{ExpectedRevision: &one, Paused: &pause}); err != nil { + t.Fatal(err) + } + if original != snapshotTable(t, f, "review_operation_waits")+snapshotTable(t, f, "review_hosted_preflight")+snapshotTable(t, f, "review_hosted_allowance_queries")+snapshotTable(t, f, "review_hosted_observations") { + t.Fatal("PR pause rewrote original cooldown") + } + next, err = f.e.StartAttempt(t.Context(), attemptProject, a.OperationID) + if err != nil || next.ID == "" || next.OperationID != a.OperationID || next.ID == a.ID { + t.Fatal(next, err) + } + // A pause after issuance never prevents retaining/settling the original result. + g, active, capture := hostedPublicationFixture(t, true) + pause = true + if _, err = g.e.ConfigurePullScheduling(t.Context(), g.scope(t, attemptProject, g.writer, false), "pause-issued", 2, PullSchedulingRequest{ExpectedRevision: &zero, Paused: &pause}); err != nil { + t.Fatal(err) + } + retained, err := g.e.RecordReviewEvidence(t.Context(), attemptProject, active.ID, capture) + if err != nil || retained.ID == "" { + t.Fatal(retained, err) + } + if _, err = g.e.Advance(t.Context(), attemptProject, active.ID, active.Revision, "completed", "captured_original_result", active.ExternalID); err != nil { + t.Fatal(err) + } + if count := attemptCount(t, g.store, `SELECT count(*) FROM review_execution_evidence`); count != 1 { + t.Fatal(count) + } +} + +func TestSchedulingFinalActionPauseRace(t *testing.T) { + f, a, _ := hostedActionFixture(t) + if err := f.e.VerifyAction(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal("fixture was not dispatchable", err) + } + zero := int64(0) + paused := true + _, err := f.e.ConfigurePullScheduling(t.Context(), f.scope(t, attemptProject, f.writer, false), "pause-final-race", 2, PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused}) + if err != nil { + t.Fatal(err) + } + before := attemptState(t, f, a) + err = f.e.VerifyAction(t.Context(), attemptProject, a.ID, a.Revision) + attemptCode(t, err, "pull_scheduling_paused") + if attemptState(t, f, a) != before { + t.Fatal("final guard changed journal") + } +} + +func TestSchedulingPauseBeforeAnyIntentBulkReadAndUnenrolledIsolation(t *testing.T) { + f := schedulingFixture(t) + schedulingPause(t, f, 4, 0, true) + schedulingPause(t, f, 99, 0, true) + schedulingPause(t, f, 2, 0, true) + scope := selectionScope(t, f, attemptProject, f.writer, "read") + view, err := f.e.ReadScheduling(t.Context(), scope) + if err != nil || len(view.PausedPulls) != 2 || view.PausedPulls[0].PullNumber != 2 || view.PausedPulls[1].PullNumber != 4 { + t.Fatal("bulk pauses lost queue order or leaked unenrolled PR", view, err) + } + p, err := f.e.ReadPullScheduling(t.Context(), scope, 99) + if err != nil || !p.Paused { + t.Fatal("pause before enrollment was lost", p, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("manual pause created review work") + } +} + +func TestSchedulingQueuedPauseDiagnosticPrecedence(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, wait := range []string{"scheduler", "queue", "draft"} { + t.Run(channel+"/"+wait, func(t *testing.T) { + f := schedulingFixture(t) + pull := int64(2) + if wait == "queue" { + f.enqueue(t, attemptProject, "earlier", channel, 2, 1) + pull = 4 + } + r := f.enqueue(t, attemptProject, "queued-pause", channel, pull, 1) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + admissionSQL(t, f, `INSERT INTO review_operation_waits(operation_id,baseline_attempt_id,retry_not_before,paused) VALUES(?,NULL,'',0)`, r.ID) + if wait == "draft" { + admissionSQL(t, f, `UPDATE review_operations SET reason=? WHERE id=?`, cliDraftWait, r.ID) + } + schedulingPause(t, f, pull, 0, true) + check := func(want string) { + t.Helper() + if got, _ := f.e.queuedDiagnosticDetails(t.Context(), scope, r.ID, r.Revision); got != want { + t.Fatalf("diagnostic=%q want=%q", got, want) + } + } + check("pull_scheduling_paused") + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=json_set(body_json,'$.paused',json('true')) WHERE project_id=?`, attemptProject) + check("project_paused") + var originalBody string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_execution_config WHERE project_id=?`, attemptProject).Scan(&originalBody); err != nil { + t.Fatal(err) + } + for _, invalid := range []string{strings.TrimSuffix(originalBody, "}") + `,"paused":true}`, originalBody + strings.Repeat(" ", 9000)} { + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=? WHERE project_id=?`, invalid, attemptProject) + check("") + } + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=? WHERE project_id=?`, originalBody, attemptProject) + capability := f.e.capabilities["test-capability"] + delete(f.e.capabilities, "test-capability") + check("") + f.e.capabilities["test-capability"] = capability + check("project_paused") + admissionSQL(t, f, `UPDATE review_operation_waits SET paused=1 WHERE operation_id=?`, r.ID) + check("operation_paused") + }) + } + } +} + +func TestSchedulingPausePreservesRetainedCooldown(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var now *time.Time + if channel == "cli" { + f, a, _, now = cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + } else { + f, a, _, now = queuedCooldown(t) + } + scope := f.scope(t, attemptProject, f.writer, false) + pause := func(revision int64, paused bool) { + _, err := f.e.ConfigurePullScheduling(t.Context(), scope, core.NewID("timer-pause"), 2, PullSchedulingRequest{ExpectedRevision: &revision, Paused: &paused}) + if err != nil { + t.Fatal(err) + } + } + before := cliWaitRead(t, f, a.OperationID) + pause(0, true) + if got, _ := f.e.queuedDiagnosticDetails(t.Context(), scope, before.ID, before.Revision); got != "pull_scheduling_paused" { + t.Fatal("quota/cooldown hid PR pause", got) + } + pause(1, false) + *now = cliWaitDue(t, before).Add(time.Second) + driver := &controlledDriver{prepare: func(ctx context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + pause(2, true) + _, err := f.e.ExecutionContext(ctx, o.ProjectID, o.ID) + return Preparation{}, err + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal(err) + } + after := cliWaitRead(t, f, a.OperationID) + if driver.prepares.Load() != 1 || driver.calls.Load() != 0 || after.State != "queued" || after.Reason != "pull_scheduling_paused" || !reflect.DeepEqual(after.Wait, before.Wait) { + t.Fatal("lost original cooldown", before, after) + } + assertCLIWaitSnapshot(t, f) + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("leaked reservation") + } + }) + } +} + +func TestSchedulingPreparationGuardCannotRequeueAdmittedAttempt(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed"} { + t.Run(channel+"/"+reason, func(t *testing.T) { + f := supervisorFixture(t) + r := f.enqueue(t, attemptProject, "admitted-guard", channel, 2, 1) + a := f.start(t, attemptProject, r) + intent := "" + if channel == "hosted" { + intent = "synthetic-trigger" + } + admitted, err := f.e.Admit(t.Context(), attemptProject, a.ID, a.Revision, attemptAnchor(attemptProject, 2), intent) + if err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, admitted.Revision, "held", reason, ""); err == nil { + t.Fatal("admitted attempt accepted a preparation hold") + } + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, admitted.Revision, "failed", reason, ""); err != nil { + t.Fatal(err) + } + after := cliWaitRead(t, f, r.ID) + if after.State != "failed" || after.AttemptID != a.ID { + t.Fatal("admitted action silently requeued", after) + } + }) + } + } +} + +func TestSchedulingDetachedGuardHistoryRejectsCorruption(t *testing.T) { + for _, corrupt := range []string{"anchor", "intent", "external", "state", "revision", "reason"} { + t.Run(corrupt, func(t *testing.T) { + f := schedulingFixture(t) + r := f.enqueue(t, attemptProject, "detached-guard", "hosted", 2, 1) + a := f.start(t, attemptProject, r) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "pull_scheduling_paused", ""); err != nil { + t.Fatal(err) + } + assertCLIWaitSnapshot(t, f) + o := cliWaitRead(t, f, r.ID) + current, err := readAttempt(t.Context(), f.store.DB(), attemptProject, a.ID) + if err != nil { + t.Fatal(err) + } + switch corrupt { + case "anchor": + anchor := attemptAnchor(attemptProject, 2) + current.Anchor = &anchor + case "intent": + current.Intent = "possible-post" + case "external": + current.ExternalID = "trigger" + case "state": + current.State = "active" + case "revision": + current.Revision = 1 + case "reason": + admissionSQL(t, f, `UPDATE review_execution_transitions SET reason='preparation_failed' WHERE attempt_id=? AND revision=2`, a.ID) + } + _, recognized, err := historicalUnusedPreparationOperation(t.Context(), f.store.DB(), o, current, true) + if err == nil && recognized { + t.Fatal("accepted corrupt detached attempt", corrupt) + } + }) + } +} + +func TestSchedulingDetachedGuardProjectsOriginalAttempt(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed"} { + t.Run(reason, func(t *testing.T) { + f := attemptProjectionFixture(t, true) + r := f.enqueue(t, attemptProject, "guard-projection", "hosted", 2, 1) + a := f.start(t, attemptProject, r) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, ""); err != nil { + t.Fatal(err) + } + _, projected := projectedAttempt(t, f, a) + if projected.State != "held" || projected.Reason != reason { + t.Fatal(projected) + } + assertCLIWaitSnapshot(t, f) + o := cliWaitRead(t, f, r.ID) + if _, err := f.e.ControlOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), "cancel-guard", o.ID, OperationControl{ExpectedRevision: o.Revision, Action: "cancel"}); err != nil { + t.Fatal(err) + } + assertCLIWaitSnapshot(t, f) + if _, err := f.e.PublishAttempt(t.Context(), attemptProject, a.ID, nil); err != nil { + t.Fatal("historical projection after cancellation", err) + } + }) + } +} + +func validateSchedulingSnapshotForTest(t *testing.T, f *attemptFixture) error { + t.Helper() + return f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return ValidateSchedulingSnapshot(ctx, tx) + }) +} + +func TestValidateSchedulingSnapshotRejectsStaleProjectProjection(t *testing.T) { + f := schedulingFixture(t) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + at := stamp() + // Retained inputs only: model an accepted enable followed by a disable. + // The current row and both journal events must agree before simulating a + // stale projection. No selection or provider action is constructed. + admissionSQL(t, f, `INSERT INTO review_scheduling + (project_id,revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at) + VALUES(?,2,0,0,?,'','',?)`, attemptProject, scope.PrincipalID, at) + admissionSQL(t, f, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) VALUES + (?,'review.scheduling_updated',?,1,?,'{"automatic_hosted":true,"automatic_cli":false}',?), + (?,'review.scheduling_updated',?,2,?,'{"automatic_hosted":false,"automatic_cli":false}',?)`, + attemptProject, attemptProject, scope.PrincipalID, at, attemptProject, attemptProject, scope.PrincipalID, at) + for _, identity := range [][2]string{{otherAttemptProject, attemptProject}, {attemptProject, otherAttemptProject}} { + admissionSQL(t, f, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) + SELECT ?,event_type,?,revision+1,actor_id,payload_json,created_at FROM events + WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision=2`, + identity[0], identity[1], attemptProject, attemptProject) + } + if err := validateSchedulingSnapshotForTest(t, f); err != nil { + t.Fatalf("healthy rev-2 projection rejected: %v", err) + } + admissionSQL(t, f, `UPDATE review_scheduling SET revision=1,automatic_hosted=1,worker_id='selection-worker',credential_id='exec-writer-cred' WHERE project_id=?`, attemptProject) + attemptCode(t, validateSchedulingSnapshotForTest(t, f), "storage_unavailable") +} + +func TestValidateSchedulingSnapshotRejectsMissingPausedPullProjection(t *testing.T) { + f := schedulingFixture(t) + schedulingPause(t, f, 2, 0, true) + schedulingPause(t, f, 4, 0, true) + schedulingPause(t, f, 4, 1, false) + if err := validateSchedulingSnapshotForTest(t, f); err != nil { + t.Fatalf("healthy paused and resumed projections rejected: %v", err) + } + admissionSQL(t, f, `DELETE FROM review_pull_scheduling WHERE project_id=? AND pull_number=4`, attemptProject) + if err := validateSchedulingSnapshotForTest(t, f); err != nil { + t.Fatalf("absent projection for a latest genuine resume refused: %v", err) + } + admissionSQL(t, f, `DELETE FROM review_pull_scheduling WHERE project_id=? AND pull_number=2`, attemptProject) + attemptCode(t, validateSchedulingSnapshotForTest(t, f), "storage_unavailable") +} + +func TestValidateSchedulingSnapshotRejectsMalformedAndFutureVersions(t *testing.T) { + for _, version := range []string{"not-a-version", "3"} { + t.Run(version, func(t *testing.T) { + f := schedulingFixture(t) + admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_scheduling'`, version) + attemptCode(t, validateSchedulingSnapshotForTest(t, f), "storage_unavailable") + }) + } +} + +func TestValidateSchedulingSnapshotRequiresPresentDomainMetadata(t *testing.T) { + f := schedulingFixture(t) + admissionSQL(t, f, `DELETE FROM metadata WHERE key='schema:review_scheduling'`) + if err := validateSchedulingSnapshotForTest(t, f); !errors.Is(err, sql.ErrNoRows) { + t.Fatalf("missing optional domain metadata should not be mistaken for a schema version: %v", err) + } +} + +func TestSchedulingWaitSnapshotRequiresActualDraftProof(t *testing.T) { + f := schedulingFixture(t) + r := f.enqueue(t, attemptProject, "scheduling-only-cli", "cli", 2, 1) + a := f.start(t, attemptProject, r) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "pull_scheduling_paused", ""); err != nil { + t.Fatal(err) + } + assertCLIWaitSnapshot(t, f) + o := cliWaitRead(t, f, r.ID) + o.Reason = cliDraftWait + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return validateOperationWaitHistory(ctx, tx, o) + }) + if err == nil { + t.Fatal("scheduling-only history was accepted as draft proof") + } +} diff --git a/internal/reviewexec/schema.go b/internal/reviewexec/schema.go index 31f90e379..470e546c7 100644 --- a/internal/reviewexec/schema.go +++ b/internal/reviewexec/schema.go @@ -94,7 +94,10 @@ func EnsureSchema(ctx context.Context, store *core.Store) error { if err := EnsureSelectionSchema(ctx, store); err != nil { return err } - return EnsureFrontSchema(ctx, store) + if err := EnsureFrontSchema(ctx, store); err != nil { + return err + } + return EnsureSchedulingSchema(ctx, store) } // Execution migration nine rebuilds attempts independently of the comparison 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.go b/internal/reviewexec/supervisor.go index 656abcff8..8a7432405 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -254,6 +254,7 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL JOIN projects p ON p.id=o.project_id LEFT JOIN installed i ON i.id=CASE WHEN json_valid(c.body_json) THEN json_extract(c.body_json,'$.capability_id') END AND i.fingerprint=o.capability_fingerprint WHERE o.state='queued' + AND NOT EXISTS (SELECT 1 FROM review_pull_scheduling s WHERE s.project_id=o.project_id AND s.pull_number=o.pull_number AND s.paused=1) AND NOT EXISTS (SELECT 1 FROM review_operation_waits w WHERE w.operation_id=o.id AND (w.paused=1 OR (w.retry_not_before<>'' AND julianday(w.retry_not_before)>julianday(?)))) AND NOT EXISTS (SELECT 1 FROM review_execution_config latest WHERE latest.project_id=o.project_id AND latest.revision=(SELECT MAX(revision) FROM review_execution_config WHERE project_id=o.project_id) AND json_valid(latest.body_json) AND json_extract(latest.body_json,'$.paused')=1) AND NOT EXISTS (SELECT 1 FROM review_execution_reservations r WHERE r.provider=i.provider AND r.account=i.account AND r.action_class=o.channel AND (o.channel='cli' OR r.repository_id=p.github_repository_id)) @@ -270,7 +271,7 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL readCandidate := func(project, operation string) (Operation, error) { o, err := readOperation(ctx, tx, project, operation) if err != nil { - if e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { return Operation{}, nil } return Operation{}, err @@ -278,11 +279,17 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL if o.State != "queued" { return Operation{}, nil } + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + if automaticProjectRefused(err) { + return Operation{}, nil + } + return Operation{}, err + } configuration, ok := configurations[o.ProjectID] if !ok { c, revision, err := readConfiguration(ctx, tx, o.ProjectID) if err != nil { - if e.skipUnavailableConfiguration(ctx, o, err) { + if e.skipUnavailableConfiguration(ctx, o, err) || automaticProjectRefused(err) { return Operation{}, nil } return Operation{}, err @@ -325,7 +332,7 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL } earlier, err := e.earlierQueuedReviewIntentInSnapshot(ctx, tx, o, c, revision, emptyPredecessors) if err != nil { - if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { return Operation{}, nil } return Operation{}, err @@ -532,12 +539,12 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL func preparationReason(err error) string { var failure *core.Error if errors.As(err, &failure) { - if failure.Code == "review_evidence_pending" || failure.Code == "review_capacity" { + if failure.Code == "review_evidence_pending" || failure.Code == "review_capacity" || failure.Code == "pull_scheduling_paused" || failure.Code == "automation_authorization_changed" { return failure.Code } if details, ok := failure.Details.(map[string]string); failure.Code == "review_held" && ok { switch reason := details["reason"]; reason { - case "pull_draft", "source_changed": + case "pull_draft", "source_changed", "target_changed": return reason case "source_obligations_pending", "repository_changed", "allowance_exhausted", "allowance_unavailable", "target_already_covered", "predecessor_identity_changed", "predecessor_unavailable", "predecessor_unfinished", "execution_binding_changed", "preparation_duplicate", "source_unavailable", "workspace_unavailable", "workspace_changed", "comparison_unavailable", "project_file_limit", "provider_activity_unproven", "provider_review_active", "provider_actor_unproven", "hosted_allowance_unproven", "hosted_allowance_cooldown", "standing_baseline_unproven": return reason @@ -673,6 +680,18 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr return e.processPendingBatch(ctx, drivers, releaseProbe, worker, operations, receipt) } +// A typed scheduling refusal requeues only unused preparation. Other local +// history failures retain the preparation and reservation. +func (e *Engine) classifyUnavailablePreparation(ctx context.Context, o Operation, a Attempt, err error) (bool, error) { + if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + return true, nil + } + if schedulingRefused(err) { + return true, e.finishPreparation(a, "held", "automatic_scheduling_unavailable") + } + return automaticProjectRefused(err) || isStoredUnavailable(err, storedRoundHistory), nil +} + func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Driver, releaseProbe func(), worker int, operations []Operation, receipt pendingExhaustion) error { overloaded := false claimed := false @@ -689,7 +708,7 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return nil } - if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { continue } var refusal *core.Error @@ -711,7 +730,7 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return nil } - if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { continue } var failure *core.Error @@ -749,9 +768,13 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if errors.As(err, &recoverable) { return err } - if ctx.Err() == nil && e.skipUnavailableOperation(ctx, o, err) { - // The retained identity does not support settling this preparation. - continue + if ctx.Err() == nil { + if handled, settleErr := e.classifyUnavailablePreparation(ctx, o, a, err); handled { + if settleErr != nil { + return settleErr + } + continue + } } state := "held" reason := preparationReason(err) @@ -787,12 +810,27 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return e.finishPreparation(a, "cancelled", "supervisor_stopping") } - // Preserve the unused preparation and reservation on damaged retained - // history, without stopping unrelated candidates. - if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + // Preserve the existing recovery for a proven project-wide source + // obligation fault at admission. The retained reason keeps old + // detached attempts compatible with snapshot validation. + if isSourceObligationProjectStateError(err) { + if err := e.finishPreparation(a, "held", "automatic_scheduling_unavailable"); err != nil { + return err + } + continue + } + if handled, settleErr := e.classifyUnavailablePreparation(ctx, o, a, err); handled { + if settleErr != nil { + return settleErr + } continue } var refusal *core.Error + if errors.As(err, &refusal) && (refusal.Code == "pull_scheduling_paused" || refusal.Code == "automation_authorization_changed") { + // Admit recorded no intent. Release only this unused attempt and + // retain the queued operation's original identity and wait state. + return e.finishPreparation(a, "held", refusal.Code) + } if errors.As(err, &refusal) && refusal.Code == "review_held" { reason := preparationReason(err) if reason == "source_obligations_pending" || reason == "repository_changed" { diff --git a/internal/reviewexec/supervisor_classification_test.go b/internal/reviewexec/supervisor_classification_test.go new file mode 100644 index 000000000..d675d716c --- /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", "preparing", "", roundUnavailable, 1}, + {"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()) + } + }) + } +} diff --git a/internal/reviewexec/wait_deadline.go b/internal/reviewexec/wait_deadline.go index 72d23e361..f5ae166b7 100644 --- a/internal/reviewexec/wait_deadline.go +++ b/internal/reviewexec/wait_deadline.go @@ -135,7 +135,7 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba return err } defer rows.Close() - var cancelled []string + var cancelled, detachedHolds []string var first string var earliest time.Time tied := false @@ -153,7 +153,9 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba if !state.Valid || !retainedReason.Valid || state.String != "held" || attemptState != "held" { return waitUnavailable() } - if o.Channel == "cli" && retainedReason.String == cliDraftWait { + if retainedReason.String == "pull_scheduling_paused" || retainedReason.String == "automation_authorization_changed" || retainedReason.String == "automatic_scheduling_unavailable" || + o.Channel == "cli" && retainedReason.String == cliDraftWait { + detachedHolds = append(detachedHolds, id) continue } if retainedReason.String != reason { @@ -173,6 +175,22 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba return err } rows.Close() + // Scheduling and Draft guards can detach unused preparations without + // becoming quota baselines, but the final hold alone does not prove that. + // Reuse the same strict journal proof as snapshot validation. + for _, id := range detachedHolds { + a, err := readAttempt(ctx, q, o.ProjectID, id) + if err != nil { + return waitDependencyError(err) + } + _, unused, err := historicalUnusedPreparationOperation(ctx, q, o, a, true) + if err != nil { + return waitDependencyError(err) + } + if !unused { + return waitUnavailable() + } + } for _, id := range cancelled { if err := validateUnqueriedRetryHistory(ctx, q, o, id, baseline); err != nil { return err diff --git a/internal/reviewexec/wait_deadline_runtime_test.go b/internal/reviewexec/wait_deadline_runtime_test.go index 44ca59d43..c63803d42 100644 --- a/internal/reviewexec/wait_deadline_runtime_test.go +++ b/internal/reviewexec/wait_deadline_runtime_test.go @@ -23,10 +23,15 @@ func deadlineRuntimeFixture(t *testing.T, channel string) (*attemptFixture, Atte } func deadlineRuntimeState(t *testing.T, f *attemptFixture) string { + t.Helper() + return deadlineRuntimeStateThrough(t, f.store.DB()) +} + +func deadlineRuntimeStateThrough(t *testing.T, reader snapshotTableReader) string { t.Helper() var result strings.Builder for _, table := range []string{"review_operations", "review_execution_attempts", "review_execution_transitions", "review_operation_waits", "review_cli_preflight", "review_hosted_preflight", "review_execution_reservations", "events", "receipts"} { - result.WriteString(snapshotTable(t, f, table)) + result.WriteString(snapshotTableThrough(t, reader, table)) } return result.String() } From ac1f5ad9104d95fd41c7ba959c4526d35c90ccb8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 14:04:22 +1300 Subject: [PATCH 02/34] Harden review admission, selection, and authorization continuity --- internal/core/project_automation.go | 3 - ...ission_binding_boundary_regression_test.go | 67 +++++++++++++++++++ internal/reviewexec/attempts.go | 7 ++ internal/reviewexec/front_evaluator.go | 4 ++ internal/reviewexec/run_selection.go | 2 +- .../scheduling_authorization_continuity.go | 10 ++- internal/reviewexec/scheduling_automatic.go | 11 ++- .../scheduling_boundary_compatibility_test.go | 64 ++++++++++++++++++ internal/reviewexec/scheduling_snapshot.go | 8 ++- 9 files changed, 164 insertions(+), 12 deletions(-) create mode 100644 internal/reviewexec/admission_binding_boundary_regression_test.go create mode 100644 internal/reviewexec/scheduling_boundary_compatibility_test.go diff --git a/internal/core/project_automation.go b/internal/core/project_automation.go index df217152e..72eeea12a 100644 --- a/internal/core/project_automation.go +++ b/internal/core/project_automation.go @@ -45,8 +45,5 @@ func (s *Store) ProjectAutomationScope(ctx context.Context, tx *sql.Tx, project, if err := s.authorize(ctx, tx, scope, "admin"); err != nil { return Scope{}, err } - if err := CheckActiveWorker(ctx, tx, project, worker); err != nil { - return Scope{}, err - } return scope, nil } 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/attempts.go b/internal/reviewexec/attempts.go index fd272f9e8..5dfadc76f 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -261,6 +261,13 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision return err } if err := e.requireAutomaticOperation(ctx, tx, o); err != nil { + // Only a proved malformed selection-to-operation link can + // release this unused preparation here. Other retained-state and + // custody refusals keep their original classification. + var binding *operationSelectionBindingStateError + if errors.As(err, &binding) { + return &schedulingStateError{err} + } return err } if err := requireSourceObligationsClear(ctx, tx, project, o.PullNumber); err != nil { diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go index 9a04970a8..14bab91e2 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -75,6 +75,10 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i } scheduling, err := readPullScheduling(ctx, q, r.ProjectID, plan.Pull.Number) if err != nil { + var pullState *pullSchedulingStateError + if errors.As(err, &pullState) && pullState.project == r.ProjectID && pullState.pull == plan.Pull.Number { + return evaluatedFront{state: "held", reason: "automatic_scheduling_unavailable", plan: plan}, nil + } return evaluatedFront{}, err } if scheduling.Paused { diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 69c48e7c9..41b71b264 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -89,7 +89,7 @@ func readRun(ctx context.Context, q EvidenceQuery, project, id string) (Run, err return Run{}, err } if child.ActorID != r.ActorID || child.WorkerID != r.WorkerID || child.Channel != r.Channel || child.ConfigurationRevision != r.ConfigurationRevision || child.PolicyRevision != r.PolicyRevision || child.CapabilityFingerprint != r.CapabilityFingerprint || r.ExpectedPullNumber != 0 && child.PullNumber != r.ExpectedPullNumber { - return Run{}, runUnavailable() + return Run{}, &operationSelectionBindingStateError{runUnavailable()} } } return r, nil diff --git a/internal/reviewexec/scheduling_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go index 0b74dfa19..eed254cf3 100644 --- a/internal/reviewexec/scheduling_authorization_continuity.go +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -45,13 +45,17 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision expected := revision for rows.Next() { var retainedRevision any - var actor string + var storedActor any var payload sql.NullString - if err = rows.Scan(&retainedRevision, &actor, &payload); err != nil { + if err = rows.Scan(&retainedRevision, &storedActor, &payload); err != nil { return false, err } recorded, validRevision := retainedRevision.(int64) - if !validRevision || recorded != expected || recorded == revision && actor != originalActor || recorded == current.Revision && actor != current.actor { + actor, nativeText := storedActor.(string) + selectedChild := r.State == "selected" && r.OperationID != "" + if !validRevision || !nativeText || !identifier.MatchString(actor) || recorded != expected || + (!selectedChild || recorded == revision) && actor != originalActor || + recorded == current.Revision && actor != current.actor { return false, nil } var settings schedulingEvent diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 6a560293c..05e64f016 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -86,6 +86,13 @@ func (e *Engine) requireAutomaticRun(ctx context.Context, tx *sql.Tx, r Run) err } return err } + +// operationSelectionBindingStateError identifies a malformed, directly +// observed selection-to-operation link, not a missing or unreadable history. +type operationSelectionBindingStateError struct{ error } + +func (e *operationSelectionBindingStateError) Unwrap() error { return e.error } + func (e *Engine) requireAutomaticOperation(ctx context.Context, tx *sql.Tx, o Operation) error { if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { return err @@ -100,14 +107,14 @@ func (e *Engine) requireAutomaticOperation(ctx context.Context, tx *sql.Tx, o Op } id, validID := selection.(string) if project != o.ProjectID || !validID || !validRunID(id) { - return schedulingUnavailable() + return &operationSelectionBindingStateError{schedulingUnavailable()} } r, err := readRun(ctx, tx, o.ProjectID, id) if err != nil { return err } if r.OperationID != o.ID || r.ActorID != o.ActorID || r.WorkerID != o.WorkerID || r.Channel != o.Channel { - return schedulingUnavailable() + return &operationSelectionBindingStateError{schedulingUnavailable()} } return e.requireAutomaticRun(ctx, tx, r) } diff --git a/internal/reviewexec/scheduling_boundary_compatibility_test.go b/internal/reviewexec/scheduling_boundary_compatibility_test.go new file mode 100644 index 000000000..5053fe5c7 --- /dev/null +++ b/internal/reviewexec/scheduling_boundary_compatibility_test.go @@ -0,0 +1,64 @@ +package reviewexec + +import ( + "context" + "database/sql" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestSchedulingBoundaryExistingChildAndUnselectedOwnership(t *testing.T) { + for _, tc := range []struct { + name, intermediate string + selected, capable bool + }{ + {"unchanged-owner", "test-actor", false, true}, + {"new-selection-requires-continuity", "alternate-authorizer", false, false}, + {"retained-child-keeps-continuity-rule", "alternate-authorizer", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + const settings = `{"automatic_hosted":true}` + if _, 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',?), + ('test-project','test-project','review.scheduling_updated',2,?,?), + ('test-project','test-project','review.scheduling_updated',3,'test-actor',?)`, settings, tc.intermediate, settings, settings); err != nil { + t.Fatal(err) + } + current := schedulingRecord{Scheduling: Scheduling{ProjectID: "test-project", Revision: 3, AutomaticHosted: true}, actor: "test-actor"} + r := Run{ProjectID: "test-project", Channel: "hosted", State: "selecting"} + if tc.selected { + r.State, r.OperationID = "selected", "retained-child" + } + if allowed, err := automaticChannelContinuous(t.Context(), tx, r, 1, "test-actor", current); err != nil || allowed != tc.capable { + t.Fatalf("continuity allowed=%v want=%v err=%v", allowed, tc.capable, err) + } + }) + } +} + +func TestFrontLocalSchedulingHoldPreservesIndependentAndStackedEligibility(t *testing.T) { + f := schedulingFixture(t) + schedulingPause(t, f, 2, 0, true) + admissionSQL(t, f, `UPDATE review_pull_scheduling SET updated_at='' WHERE project_id=? AND pull_number=2`, attemptProject) + parent := SourcePlan{Repository: reviewprovider.Repository{ID: 801}, Pull: reviewprovider.Pull{RepositoryID: 801, Number: 2, State: "open", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("a", 40)}} + independent := SourcePlan{Repository: parent.Repository, Pull: reviewprovider.Pull{RepositoryID: 801, Number: 4, State: "open", HeadSHA: strings.Repeat("b", 40), BaseSHA: strings.Repeat("a", 40)}} + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + r := Run{ProjectID: attemptProject, Channel: "cli"} + got, err := f.e.evaluateFront(ctx, tx, r, 801, []SourcePlan{parent, independent}, true) + if err != nil || got.state != "ready" || got.plan.Pull.Number != 4 { + t.Fatalf("unrelated ready candidate not available: %+v %v", got, err) + } + dependent := independent + dependent.ParentPullNumber, dependent.ParentSHA = 2, parent.Pull.HeadSHA + got, err = f.e.evaluateFront(ctx, tx, r, 801, []SourcePlan{parent, dependent}, true) + if err != nil || got.state != "held" || got.reason != "automatic_scheduling_unavailable" { + t.Fatalf("dependent candidate did not retain upstream hold: %+v %v", got, err) + } + return nil + }); err != nil { + t.Fatal(err) + } +} diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 2119e5b83..29e4a7381 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -208,7 +208,9 @@ const orphanPullSchedulingSQL = `WITH orphan AS ( SELECT e.project_id,e.resource_id,e.revision,e.sequence, CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END AS payload, ROW_NUMBER() OVER (PARTITION BY e.project_id,e.resource_id ORDER BY e.revision DESC,e.sequence DESC) AS newest, - COUNT(*) OVER (PARTITION BY e.project_id,e.resource_id,e.revision) AS matches + COUNT(*) OVER (PARTITION BY e.project_id,e.resource_id,e.revision) AS matches, + MAX(CASE WHEN typeof(e.revision)<>'integer' OR e.revision<1 THEN 1 ELSE 0 END) + OVER (PARTITION BY e.project_id,e.resource_id) AS bad_revision FROM events e LEFT JOIN review_pull_scheduling s ON s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id @@ -222,7 +224,7 @@ const latestOrphanPullResumesSQL = ` func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+` SELECT CASE WHEN typeof(o.project_id)='text' THEN o.project_id END,o.resource_id, - CASE WHEN typeof(o.revision)='integer' THEN o.revision END,o.payload,o.matches, + CASE WHEN o.bad_revision=0 THEN o.revision END,o.payload,o.matches, CASE WHEN typeof(e.actor_id)='text' AND length(CAST(e.actor_id AS BLOB))<=128 THEN e.actor_id END, CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END`+latestOrphanPullResumesSQL) if err != nil { @@ -313,7 +315,7 @@ const pullSchedulingSnapshotEventsSQL = `SELECT s.project_id,s.pull_number,s.rev FROM events e CROSS JOIN review_pull_scheduling s WHERE e.event_type='review.pull_scheduling_updated' AND s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id - AND e.revision>=s.revision + AND (typeof(e.revision)<>'integer' OR e.revision<1 OR e.revision>=s.revision) ORDER BY s.project_id,s.pull_number` func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) error { From 1ee22d2aceac80fd582d96dbc69366a1da045973 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 15:07:53 +1300 Subject: [PATCH 03/34] Preserve explicit review refusal attribution and test scan budgets --- internal/reviewexec/front_evaluator.go | 16 ++++++++++++++-- internal/reviewexec/run_selection_worker.go | 6 +++--- .../scheduling_boundary_compatibility_test.go | 6 ++++++ internal/reviewexec/supervisor_test.go | 11 +++++++++-- 4 files changed, 32 insertions(+), 7 deletions(-) diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go index 14bab91e2..f1cc0ea07 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -12,6 +12,7 @@ import ( type evaluatedFront struct { state, reason string plan *SourcePlan + localRefusal error } func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo int64, plan *SourcePlan) (evaluatedFront, error) { @@ -77,7 +78,7 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i if err != nil { var pullState *pullSchedulingStateError if errors.As(err, &pullState) && pullState.project == r.ProjectID && pullState.pull == plan.Pull.Number { - return evaluatedFront{state: "held", reason: "automatic_scheduling_unavailable", plan: plan}, nil + return evaluatedFront{state: "held", reason: "automatic_scheduling_unavailable", plan: plan, localRefusal: err}, nil } return evaluatedFront{}, err } @@ -162,7 +163,7 @@ func globalFrontHold(reason string) bool { } // runFront preserves existing admission semantics and its zero-on-hold result. -func (e *Engine) runFront(ctx context.Context, q *sql.Tx, r Run, repo int64, prefix []SourcePlan) (int64, string, error) { +func (e *Engine) runFront(ctx context.Context, q *sql.Tx, r Run, repo int64, prefix []SourcePlan, finalPrefix bool) (int64, string, error) { result, err := e.evaluateFront(ctx, q, r, repo, prefix, true) if err != nil { return 0, "", err @@ -173,6 +174,17 @@ func (e *Engine) runFront(ctx context.Context, q *sql.Tx, r Run, repo int64, pre if result.state == "complete" { return 0, "", nil } + if finalPrefix && result.localRefusal != nil { + // Keep the refusal local during traversal, but preserve explicit + // selection attribution and finish rollback when it is the final hold. + reason, err := selectionLocalHoldReason(ctx, q, r) + if err != nil { + return 0, "", err + } + if reason == "local_read_unavailable" { + return 0, "", result.localRefusal + } + } return 0, result.reason, nil } diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 98756bc6b..cb4d04f95 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -362,7 +362,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 bindingHeld = true return nil } - target, reason, err = e.runFront(ctx, tx, current, repo, choice.prefix) + target, reason, err = e.runFront(ctx, tx, current, repo, choice.prefix, i == len(queue)-1) return err }) }) @@ -763,7 +763,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat // settle that newer eligible basis behind a // stale hold. A fresh ordinary selection must reacquire source // facts rather than dispatch directly from this recheck. - _, reason, err := e.runFront(ctx, tx, current, repo, choice.prefix) + _, reason, err := e.runFront(ctx, tx, current, repo, choice.prefix, true) if err != nil { return err } @@ -773,7 +773,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } return updateRun(ctx, tx, current, "held", choice.reason, "") } - front, reason, err := e.runFront(ctx, tx, current, repo, choice.prefix) + front, reason, err := e.runFront(ctx, tx, current, repo, choice.prefix, true) if err != nil { return err } diff --git a/internal/reviewexec/scheduling_boundary_compatibility_test.go b/internal/reviewexec/scheduling_boundary_compatibility_test.go index 5053fe5c7..73955959c 100644 --- a/internal/reviewexec/scheduling_boundary_compatibility_test.go +++ b/internal/reviewexec/scheduling_boundary_compatibility_test.go @@ -51,6 +51,12 @@ func TestFrontLocalSchedulingHoldPreservesIndependentAndStackedEligibility(t *te if err != nil || got.state != "ready" || got.plan.Pull.Number != 4 { t.Fatalf("unrelated ready candidate not available: %+v %v", got, err) } + if target, reason, err := f.e.runFront(ctx, tx, r, 801, []SourcePlan{parent}, false); err != nil || target != 0 || reason != "automatic_scheduling_unavailable" { + t.Fatalf("the first prefix did not retain a traversable local hold: %d %q %v", target, reason, err) + } + if target, reason, err := f.e.runFront(ctx, tx, r, 801, []SourcePlan{parent, independent}, true); err != nil || target != 4 || reason != "" { + t.Fatalf("the final prefix did not select the independent candidate: %d %q %v", target, reason, err) + } dependent := independent dependent.ParentPullNumber, dependent.ParentSHA = 2, parent.Pull.HeadSHA got, err = f.e.evaluateFront(ctx, tx, r, 801, []SourcePlan{parent, dependent}, true) diff --git a/internal/reviewexec/supervisor_test.go b/internal/reviewexec/supervisor_test.go index 13dbe9700..390856c41 100644 --- a/internal/reviewexec/supervisor_test.go +++ b/internal/reviewexec/supervisor_test.go @@ -37,7 +37,14 @@ func TestSupervisorPendingSkipsBusyBeforeLimitAndWakesAfterRelease(t *testing.T) } } before := attemptState(t, f, busy) - operations, err := f.e.pending(context.Background()) + // This test proves traversal ordering and the row cap, not that a race + // instrumented SQLite fixture processes 300 rows in the worker budget. + scan := func() ([]Operation, error) { + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + return f.e.scanPendingForWorker(ctx, true, 256) + } + operations, err := scan() if err != nil || len(operations) != 2 { t.Fatalf("busy prefix hid eligible account/channel: count=%d err=%v", len(operations), err) } @@ -51,7 +58,7 @@ func TestSupervisorPendingSkipsBusyBeforeLimitAndWakesAfterRelease(t *testing.T) if _, err := f.e.Advance(context.Background(), attemptProject, busy.ID, busy.Revision, "cancelled", "synthetic_release", ""); err != nil { t.Fatal(err) } - operations, err = f.e.pending(context.Background()) + operations, err = scan() // The scan may return a partial batch when its snapshot deadline expires, // especially under the race detector. The contract is bounded eligible // work after release, not filling the batch within a wall-clock budget. From 0b128b0ece8bb60b95693d0332b2315692a8a978 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 16:40:39 +1300 Subject: [PATCH 04/34] Require durable automatic acceptance for interrupted source retries --- .../scheduling_source_acceptance_test.go | 38 +++++++++++++++++++ .../reviewexec/scheduling_source_retry.go | 23 ++++++++++- 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 internal/reviewexec/scheduling_source_acceptance_test.go diff --git a/internal/reviewexec/scheduling_source_acceptance_test.go b/internal/reviewexec/scheduling_source_acceptance_test.go new file mode 100644 index 000000000..c23544477 --- /dev/null +++ b/internal/reviewexec/scheduling_source_acceptance_test.go @@ -0,0 +1,38 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" +) + +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) + } +} diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index ec31c09a0..f7235dc90 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -35,9 +35,19 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin return "automation_authorization_changed", nil } initial, err := automaticSourceInitialRead(ctx, tx, r) - if err != nil || initial { + if err != nil { return "", err } + if initial { + proved, err := verifiedInitialAutomaticSourceAcceptance(ctx, tx, r) + if err != nil { + return "", err + } + if !proved { + return "selection_superseded", nil + } + return "", nil + } if accepted != current.Revision { return "automation_authorization_changed", nil } @@ -51,6 +61,17 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin return "", nil } +// An interrupted read can relax exact-revision continuity only when this +// selection durably recorded its automatic acceptance. The common decoder +// validates the unique revision-one event and binds its actor, worker and lane. +func verifiedInitialAutomaticSourceAcceptance(ctx context.Context, q EvidenceQuery, r Run) (bool, error) { + event, err := readSelectionRequestedEvent(ctx, q, r) + if err != nil { + return false, err + } + return event.sequence > 0 && event.Origin == selectionOriginAutomatic, nil +} + // A revision alone cannot distinguish restart recovery from a completed hold. // Prove every retained transition was an unfinished read before relaxing the // exact-revision fence. A held event (whatever its reason), missing/duplicate From 3c6b94bd38c25f858c45a8c81b4b42f8cf4b54f0 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 17:12:55 +1300 Subject: [PATCH 05/34] Validate detached wait custody and fence degraded historical scheduling --- internal/reviewexec/cli_draft_wait.go | 6 +- internal/reviewexec/hosted_wait_validation.go | 9 +- internal/reviewexec/scheduling_automatic.go | 69 ++++++++++-- .../scheduling_historical_basis_test.go | 104 ++++++++++++++++++ 4 files changed, 178 insertions(+), 10 deletions(-) create mode 100644 internal/reviewexec/scheduling_historical_basis_test.go diff --git a/internal/reviewexec/cli_draft_wait.go b/internal/reviewexec/cli_draft_wait.go index fbec0f85b..fbe1a795a 100644 --- a/internal/reviewexec/cli_draft_wait.go +++ b/internal/reviewexec/cli_draft_wait.go @@ -224,9 +224,13 @@ func historicalCLIDraftOperation(ctx context.Context, q EvidenceQuery, o Operati // holds without inventing provider evidence or changing the current operation. func historicalUnusedPreparationOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt, scheduling bool) (Operation, bool, error) { var reason string - if err := q.QueryRowContext(ctx, `SELECT reason FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&reason); err != nil { + var matching int64 + if err := q.QueryRowContext(ctx, `SELECT reason,count(*) OVER () FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&reason, &matching); err != nil { return Operation{}, false, err } + if matching != 1 { + return Operation{}, false, waitUnavailable() + } draft := reason == cliDraftWait if !draft && !(scheduling && (reason == "pull_scheduling_paused" || reason == "automation_authorization_changed" || reason == "automatic_scheduling_unavailable")) { return Operation{}, false, nil diff --git a/internal/reviewexec/hosted_wait_validation.go b/internal/reviewexec/hosted_wait_validation.go index 00c9225d0..53b67effb 100644 --- a/internal/reviewexec/hosted_wait_validation.go +++ b/internal/reviewexec/hosted_wait_validation.go @@ -11,6 +11,8 @@ import ( // without provider calls or current freshness checks. A wait row may remain as // immutable-history attribution after its current scheduling intent has ended. func ValidateOperationWaitsSnapshot(ctx context.Context, tx *sql.Tx) error { + // Discover unused detached attempts from their native ownership and shape; + // the journal proves a valid reason, but is not a prerequisite to visiting. rows, err := tx.QueryContext(ctx, `SELECT coalesce(o.project_id,''),w.operation_id FROM review_operation_waits w LEFT JOIN review_operations o ON o.id=w.operation_id UNION SELECT project_id,id FROM review_operations WHERE reason=? UNION SELECT a.project_id,a.operation_id FROM review_execution_attempts a JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE t.reason=? @@ -18,7 +20,12 @@ func ValidateOperationWaitsSnapshot(ctx context.Context, tx *sql.Tx) error { LEFT JOIN review_operations o ON o.id=a.operation_id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE (o.id IS NULL OR o.attempt_id<>a.id) AND t.reason IN ('allowance_exhausted','hosted_allowance_cooldown') - UNION SELECT o.project_id,o.id FROM review_operations o JOIN review_execution_attempts a ON a.operation_id=o.id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE a.id<>o.attempt_id AND t.reason IN ('pull_scheduling_paused','automation_authorization_changed','automatic_scheduling_unavailable') + UNION SELECT a.project_id,a.operation_id FROM review_execution_attempts a + LEFT JOIN review_operations o ON o.id=a.operation_id + WHERE a.id IS NOT o.attempt_id AND ( + EXISTS(SELECT 1 FROM review_execution_transitions t WHERE t.attempt_id=a.id AND t.reason IN ('pull_scheduling_paused','automation_authorization_changed','automatic_scheduling_unavailable')) + OR (a.state='held' AND a.revision=2 AND a.anchor_json='null' AND a.intent='' AND a.external_id='') + ) ORDER BY 2`, cliDraftWait, cliDraftWait) if err != nil { return err diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 05e64f016..fe6c522ce 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -224,6 +224,12 @@ func automaticAdjudicationBasisSQL(channel string) string { WHERE count IS NULL OR count>0 ORDER BY evidence_id LIMIT 10001` } +// Only a known unreadable pull-local adjudication cell may degrade a pause +// entry; database/query, authorization, and retained predecessor failures cannot. +type automaticPullAdjudicationUnavailable struct{ error } + +func (e *automaticPullAdjudicationUnavailable) Unwrap() error { return e.error } + func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channel string, basisRevision int64) func(string, bool, ...any) error { return func(query string, pinJoins bool, args ...any) error { if channel == "cli" { @@ -265,7 +271,7 @@ func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channe } } if adjudication && values[0] == nil { - return schedulingUnavailable() + return &automaticPullAdjudicationUnavailable{schedulingUnavailable()} } // Keep the original query label and JSON framing. Only the // channel's semantic revision differs after a relevant write. @@ -301,9 +307,14 @@ func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string, {`SELECT id,revision,state,disposition,has_fix FROM review_finding_routes WHERE project_id=? AND (source_pull_number=? OR target_pull_number=?) ORDER BY id LIMIT 10001`, []any{project, pull, pull}}, {`SELECT o.id,o.revision,o.status FROM review_adoption_targets t JOIN review_adoption_obligations o ON o.id=t.obligation_id AND o.project_id=t.project_id WHERE t.project_id=? AND t.pull_number=? ORDER BY o.id LIMIT 10001`, []any{project, pull}}, } + var unavailable error for _, q := range queries { if err := appendRows(q.sql, false, q.args...); err != nil { - return "", err + var local *automaticPullAdjudicationUnavailable + if !errors.As(err, &local) { + return "", err + } + unavailable = err } } if shared.workspace { @@ -321,6 +332,9 @@ func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string, if err != nil { return "", err } + if unavailable != nil { + return "", unavailable + } h.Write([]byte(encoded(dependencies))) return hex.EncodeToString(h.Sum(nil)), nil @@ -417,16 +431,26 @@ func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project st } values := make([]any, 0, len(queue)) remaining := []int64{} + degraded := false for _, pull := range queue { - basis, err := automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) + p, err := readPullScheduling(ctx, tx, project, pull) if err != nil { return "", false, err } - values = append(values, []any{pull, basis}) - p, err := readPullScheduling(ctx, tx, project, pull) + basis, err := automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) if err != nil { - return "", false, err + var unreadable *automaticPullAdjudicationUnavailable + if !p.Paused || !errors.As(err, &unreadable) { + return "", false, err + } + // This is not a per-pull eligibility basis and it is never used + // for a selected pull. Keep the paused row and its revision in + // the degraded queue identity without pretending its hash exists. + values = append(values, []any{pull, nil, p.Revision}) + degraded = true + continue } + values = append(values, []any{pull, basis}) if p.Paused { continue } @@ -445,8 +469,37 @@ func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project st remaining = append(remaining, pull) } } - sum := sha256.Sum256([]byte(encoded([]any{values, remaining}))) - return hex.EncodeToString(sum[:]), len(remaining) > 0, nil + var digestInput any = []any{values, remaining} + if degraded { + // Version the encoding so it cannot be treated as an equivalent + // full-queue basis or rearm a full-digest-only historical intent. + digestInput = []any{"planning_basis_degraded_paused_v1", values, remaining} + } + sum := sha256.Sum256([]byte(encoded(digestInput))) + basis := hex.EncodeToString(sum[:]) + if degraded && len(remaining) > 0 { + // The coordinator treats an unseen basis as a fresh automatic + // selection. An unresolved older lane hold without exact per-pull + // attribution is not proof that the remaining work is distinct. + var unresolved bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM review_automatic_selections a + JOIN review_selections s ON s.id=a.selection_id AND s.project_id=a.project_id + WHERE a.project_id=? AND s.channel=? AND a.selection_id<>? + AND s.state='held' AND s.operation_id IS NULL + AND (typeof(a.pull_number)<>'integer' OR a.pull_number NOT BETWEEN 1 AND 2147483647 + OR typeof(a.pull_basis_sha256)<>'text' OR length(a.pull_basis_sha256)<>64 + OR a.pull_basis_sha256 GLOB '*[^0-9a-f]*') + AND a.basis_sha256<>? AND a.settled_basis_sha256<>? + )`, project, channel, ignoreSelection, basis, basis).Scan(&unresolved) + if err != nil { + return "", false, err + } + if unresolved { + return basis, false, nil + } + } + return basis, len(remaining) > 0, nil } // A waiting request keeps its identity and deadline. Automatic selection may diff --git a/internal/reviewexec/scheduling_historical_basis_test.go b/internal/reviewexec/scheduling_historical_basis_test.go new file mode 100644 index 000000000..21a4ead5e --- /dev/null +++ b/internal/reviewexec/scheduling_historical_basis_test.go @@ -0,0 +1,104 @@ +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) + } + 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") + var unreadable *automaticPullAdjudicationUnavailable + if plan != "" || eligible || !errors.As(err, &unreadable) { + t.Fatalf("active unreadable row was not refused: %q %v %v", plan, eligible, err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} From b11221e6c2d5ba9f3be40413556bee150a014a96 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 18:04:20 +1300 Subject: [PATCH 06/34] Match historical wait tests to the guarded two-column lookup --- internal/reviewexec/cli_draft_wait_test.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/internal/reviewexec/cli_draft_wait_test.go b/internal/reviewexec/cli_draft_wait_test.go index 3d1459add..6b551a8a1 100644 --- a/internal/reviewexec/cli_draft_wait_test.go +++ b/internal/reviewexec/cli_draft_wait_test.go @@ -768,14 +768,15 @@ func TestCLIDraftProbeReadFailuresAreBoundedAndSafe(t *testing.T) { type draftHistoryQuery struct { EvidenceQuery - second string - calls int + second string + matches int + calls int } func (q *draftHistoryQuery) QueryRowContext(ctx context.Context, _ string, _ ...any) *sql.Row { q.calls++ if q.calls == 1 { - return q.EvidenceQuery.QueryRowContext(ctx, `SELECT 'cli_draft_wait'`) + return q.EvidenceQuery.QueryRowContext(ctx, `SELECT 'cli_draft_wait', ?`, q.matches) } return q.EvidenceQuery.QueryRowContext(ctx, q.second) } @@ -787,14 +788,16 @@ func TestHistoricalCLIDraftSeparatesLookupFailureFromInvalidHistory(t *testing.T for _, tc := range []struct { name, query string noRows, invalid bool + matches int }{ - {"missing", `SELECT 1 WHERE 0`, true, false}, - {"storage", `SELECT * FROM nonexistent_draft_history`, false, false}, - {"invalid-time", `SELECT 'invalid', 'invalid', 0`, false, true}, - {"occupied", `SELECT '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', 1`, false, true}, + {"missing", `SELECT 1 WHERE 0`, true, false, 1}, + {"storage", `SELECT * FROM nonexistent_draft_history`, false, false, 1}, + {"invalid-time", `SELECT 'invalid', 'invalid', 0`, false, true, 1}, + {"occupied", `SELECT '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', 1`, false, true, 1}, + {"ambiguous-terminal", `SELECT 'unused second lookup'`, false, true, 2}, } { t.Run(tc.name, func(t *testing.T) { - q := &draftHistoryQuery{EvidenceQuery: f.store.DB(), second: tc.query} + q := &draftHistoryQuery{EvidenceQuery: f.store.DB(), second: tc.query, matches: tc.matches} _, draft, err := historicalCLIDraftOperation(t.Context(), q, o, a) if draft || err == nil { t.Fatal("invalid lookup became retained history", draft, err) @@ -805,6 +808,9 @@ func TestHistoricalCLIDraftSeparatesLookupFailureFromInvalidHistory(t *testing.T if tc.invalid && err.Error() != waitUnavailable().Error() { t.Fatal("invalid history lost its classification", err) } + if tc.matches != 1 && q.calls != 1 { + t.Fatal("ambiguous terminal lookup continued to older history") + } if tc.name == "storage" && !strings.Contains(err.Error(), "nonexistent_draft_history") { t.Fatal("storage error was rewritten as invalid history", err) } From 93fcf15f2eb64bab22c1e6e471d017269f09afda Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 19:45:33 +1300 Subject: [PATCH 07/34] Strengthen retained review scheduling and backup evidence boundaries --- internal/backup/inventory.go | 2 +- ...hosted_detached_preflight_snapshot_test.go | 3 + internal/reviewexec/run_selection_origin.go | 3 + internal/reviewexec/run_selection_worker.go | 49 +++++++++++--- internal/reviewexec/scheduling.go | 27 +++++--- .../scheduling_ancestor_memo_test.go | 43 ++++++++++++ .../scheduling_authorization_continuity.go | 6 +- internal/reviewexec/scheduling_automatic.go | 48 ++++++++++---- .../scheduling_basis_contract_test.go | 46 +++++++++++++ internal/reviewexec/scheduling_snapshot.go | 4 +- .../scheduling_source_acceptance_test.go | 31 +++++++++ .../scheduling_source_hold_basis_test.go | 66 +++++++++++++++++++ .../reviewexec/scheduling_source_retry.go | 13 ++-- internal/reviewexec/scheduling_test.go | 6 -- 14 files changed, 302 insertions(+), 45 deletions(-) create mode 100644 internal/reviewexec/scheduling_ancestor_memo_test.go create mode 100644 internal/reviewexec/scheduling_basis_contract_test.go create mode 100644 internal/reviewexec/scheduling_source_hold_basis_test.go diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index f8b9637c2..d1f066f77 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -1098,7 +1098,7 @@ func validateSnapshotContent(ctx context.Context, dataDir string, m Manifest, al // produced durable controls. Dropping tables cannot erase that history. var used bool if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events WHERE event_type IN ('review.scheduling_updated','review.pull_scheduling_updated'))`).Scan(&used); err != nil { - return err + return unavailable() } if used { return invalid() diff --git a/internal/reviewexec/hosted_detached_preflight_snapshot_test.go b/internal/reviewexec/hosted_detached_preflight_snapshot_test.go index 0f6f9b948..8ca6a54d9 100644 --- a/internal/reviewexec/hosted_detached_preflight_snapshot_test.go +++ b/internal/reviewexec/hosted_detached_preflight_snapshot_test.go @@ -29,6 +29,9 @@ func TestHostedSnapshotRetainsUnusedSchedulingPreflight(t *testing.T) { 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) diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index 4f3d6bf73..a2a0d8490 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -89,6 +89,9 @@ func automaticSelectionBinding(ctx context.Context, tx *sql.Tx, r Run) (automati if err != nil { return automaticSelectionAttribution{}, err } + if r.ExpectedPullNumber != 0 && event.sequence == 0 { + return automaticSelectionAttribution{}, schedulingUnavailable() + } attribution, err := readAutomaticSelectionAttribution(ctx, tx, r) if !errors.Is(err, sql.ErrNoRows) && err != nil { return automaticSelectionAttribution{}, err diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index cb4d04f95..5fc376b2d 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -164,13 +164,14 @@ func (r *runReads) ParentPull(ctx context.Context, repository, branch string) (r } type runChoice struct { - state, reason string - sourceReason string - prefix []SourcePlan - number int64 - head string - automaticQueueLimit *int - automaticBasisRevision int64 + state, reason string + sourceReason string + prefix []SourcePlan + number int64 + head string + automaticQueueLimit *int + automaticBasisRevision int64 + automaticPullScheduling []int64 } // retryRunSelectionLocal retains completed source reads while only retrying @@ -215,6 +216,24 @@ func retryRunSelectionRead(ctx context.Context, local func() error) error { }) } +// The source hold must not settle PR-local revisions that were not read. +func readAutomaticPullSchedulingRevisions(ctx context.Context, tx *sql.Tx, project string, pulls []int64) ([]int64, error) { + revisions := make([]int64, 0, len(pulls)) + for _, pull := range pulls { + current, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + var local *pullSchedulingStateError + if !errors.As(err, &local) { + return nil, err + } + revisions = append(revisions, -1) + continue + } + revisions = append(revisions, current.Revision) + } + return revisions, nil +} + func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader) (runChoice, error) { return e.chooseRunWithSourceBudget(ctx, r, repo, c, reader, e.runSourceBudget) } @@ -223,9 +242,11 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 var automaticQueueLimit *int var basisRevision int64 + var pullScheduling []int64 defer func() { result.automaticQueueLimit = automaticQueueLimit result.automaticBasisRevision = basisRevision + result.automaticPullScheduling = pullScheduling }() // Bound source work before metadata lookahead. Local suppression still // rechecks the live prefix at admission if queued work changes afterward. @@ -233,6 +254,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 err := retryRunSelectionRead(ctx, func() error { // An expired snapshot must not shorten a later retry's input. limit, automatic, basisRevision = len(c.Queue), false, 0 + pullScheduling = nil return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { attribution, err := automaticSelectionBinding(ctx, tx, r) if err != nil { @@ -250,6 +272,10 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 return schedulingUnavailable() } basisRevision, err = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) + if err != nil { + return err + } + pullScheduling, err = readAutomaticPullSchedulingRevisions(ctx, tx, r.ProjectID, c.Queue[:limit]) return err }) }) @@ -685,6 +711,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return err } bindingValidated := false + var boundPrefix []int64 defer func() { if resultErr == nil && bindingValidated { var pull int64 @@ -694,12 +721,17 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return } settle := state != "queued" && reason != "selection_changed" - if settle && pull == 0 && choice.automaticBasisRevision != 0 { + if settle && pull == 0 && choice.automaticQueueLimit != nil && choice.automaticBasisRevision != 0 { var currentBasis int64 currentBasis, resultErr = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) // An old no-child result is still retained as history, but // it cannot suppress the source read of a newly rearmed lane. settle = resultErr == nil && currentBasis == choice.automaticBasisRevision + if settle { + var revisions []int64 + revisions, resultErr = readAutomaticPullSchedulingRevisions(ctx, tx, r.ProjectID, boundPrefix) + settle = resultErr == nil && slices.Equal(revisions, choice.automaticPullScheduling) + } } if settle { resultErr = e.settleAutomaticBasis(ctx, tx, r, pull) @@ -749,6 +781,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat if limit != *choice.automaticQueueLimit { return updateRun(ctx, tx, current, "held", "selection_changed", "") } + boundPrefix = c.Queue[:limit] } if err = publishSourcePlans(ctx, tx, core.Scope{ProjectID: current.ProjectID, PrincipalID: current.ActorID, WorkerID: current.WorkerID}, repo, metadataPins, choice.prefix); err != nil { return err diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index c649dcc93..039374418 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -101,6 +101,22 @@ type schedulingEvent struct { CLIBasis json.RawMessage `json:"cli_basis_revision"` } +// Decode the historical event at its own revision. A legacy event has a +// Hosted bit and may omit both basis fields and the additive CLI bit. +func readSchedulingEventPayload(payload sql.NullString, revision int64) (schedulingEvent, int64, int64, bool) { + var event schedulingEvent + if revision < 1 || !payload.Valid || strictjson.Decode([]byte(payload.String), &event) != nil || event.Hosted == nil { + return event, 0, 0, false + } + hosted, cli := revision, revision + if len(event.HostedBasis) != 0 || len(event.CLIBasis) != 0 { + if json.Unmarshal(event.HostedBasis, &hosted) != nil || json.Unmarshal(event.CLIBasis, &cli) != nil || string(event.HostedBasis) == "null" || string(event.CLIBasis) == "null" || hosted < 1 || cli < 1 || hosted > revision || cli > revision { + return event, 0, 0, false + } + } + return event, hosted, cli, true +} + // Channel basis revisions are carried in the current scheduling event, not in // the authorization revision. Legacy events retain the shared revision verbatim: // deploying this change must not regenerate cancelled or failed intent digests. @@ -121,17 +137,12 @@ func schedulingBasisRevisions(ctx context.Context, tx *sql.Tx, s schedulingRecor if err = rows.Scan(&nativeActor, &payload); err != nil { return 0, 0, err } - var event schedulingEvent + event, eventHosted, eventCLI, valid := readSchedulingEventPayload(payload, s.Revision) actor, textActor := nativeActor.(string) - if count != 1 || !textActor || actor != s.actor || !payload.Valid || strictjson.Decode([]byte(payload.String), &event) != nil || event.Hosted == nil || *event.Hosted != s.AutomaticHosted || event.CLI == nil && s.AutomaticCLI || event.CLI != nil && *event.CLI != s.AutomaticCLI { + if count != 1 || !textActor || actor != s.actor || !valid || *event.Hosted != s.AutomaticHosted || event.CLI == nil && s.AutomaticCLI || event.CLI != nil && *event.CLI != s.AutomaticCLI { return 0, 0, schedulingUnavailable() } - hosted, cli = s.Revision, s.Revision - if len(event.HostedBasis) != 0 || len(event.CLIBasis) != 0 { - if json.Unmarshal(event.HostedBasis, &hosted) != nil || json.Unmarshal(event.CLIBasis, &cli) != nil || string(event.HostedBasis) == "null" || string(event.CLIBasis) == "null" || hosted < 1 || cli < 1 || hosted > s.Revision || cli > s.Revision { - return 0, 0, schedulingUnavailable() - } - } + hosted, cli = eventHosted, eventCLI } if err = rows.Err(); err != nil { return 0, 0, err diff --git a/internal/reviewexec/scheduling_ancestor_memo_test.go b/internal/reviewexec/scheduling_ancestor_memo_test.go new file mode 100644 index 000000000..f5a162f23 --- /dev/null +++ b/internal/reviewexec/scheduling_ancestor_memo_test.go @@ -0,0 +1,43 @@ +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) + 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 := automaticDependenciesWithFrame(ctx, tx, attemptProject, pull, "hosted", frame, true, index, memo) + 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 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_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go index eed254cf3..41180d551 100644 --- a/internal/reviewexec/scheduling_authorization_continuity.go +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -3,8 +3,6 @@ package reviewexec import ( "context" "database/sql" - - "github.com/benhook1013/FireController/internal/strictjson" ) // A configuration owner change governs new selections. It need not replace an @@ -58,8 +56,8 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision recorded == current.Revision && actor != current.actor { return false, nil } - var settings schedulingEvent - if !payload.Valid || strictjson.Decode([]byte(payload.String), &settings) != nil { + settings, _, _, valid := readSchedulingEventPayload(payload, recorded) + if !valid { return false, nil } enabled := settings.Hosted diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index fe6c522ce..ec75b1890 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -140,11 +140,13 @@ func automaticPullBasis(ctx context.Context, tx *sql.Tx, project string, pull in } type automaticBasisRead struct { - prefix []byte - revision int64 - workspace bool - frame frontFrame - hasFrame bool + prefix []byte + revision int64 + workspace bool + frame frontFrame + hasFrame bool + parentFacts map[int64][]any + frontByNumber map[int64]frontPull } // The channel semantic revision is independent of unrelated control edits. @@ -187,6 +189,10 @@ func readAutomaticBasis(ctx context.Context, tx *sql.Tx, project, channel string } } out.prefix = prefix.Bytes() + if out.hasFrame { + out.parentFacts = make(map[int64][]any) + out.frontByNumber = frontPullIndex(out.frame) + } return out, nil } @@ -328,7 +334,7 @@ func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string, return "", err } } - dependencies, err := automaticDependenciesWithFrame(ctx, tx, project, pull, channel, shared.frame, shared.hasFrame) + dependencies, err := automaticDependenciesWithFrame(ctx, tx, project, pull, channel, shared.frame, shared.hasFrame, shared.frontByNumber, shared.parentFacts) if err != nil { return "", err } @@ -352,17 +358,24 @@ func automaticDependenciesChannel(ctx context.Context, tx *sql.Tx, project strin if err != nil { return nil, err } - return automaticDependenciesWithFrame(ctx, tx, project, pull, channel, frame, found) + return automaticDependenciesWithFrame(ctx, tx, project, pull, channel, frame, found, nil, nil) +} + +func frontPullIndex(frame frontFrame) map[int64]frontPull { + byNumber := make(map[int64]frontPull, len(frame.prefix)) + for _, p := range frame.prefix { + byNumber[p.Number] = p + } + return byNumber } -func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, frame frontFrame, found bool) ([]any, error) { +func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, frame frontFrame, found bool, byNumber map[int64]frontPull, parentFacts map[int64][]any) ([]any, error) { out := []any{} if !found { return out, nil } - byNumber := make(map[int64]frontPull, len(frame.prefix)) - for _, p := range frame.prefix { - byNumber[p.Number] = p + if byNumber == nil { + byNumber = frontPullIndex(frame) } current, found := byNumber[pull] if !found { @@ -379,6 +392,13 @@ func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project str out = append(out, []any{parent, "source_prefix_incomplete"}) break } + // One planning snapshot owns this memo and immutable frame. Never + // cache an error or skip the current pull's own chain/cycle checks. + if facts, present := parentFacts[parent]; present { + out = append(out, facts) + parent = p.ParentPullNumber + continue + } progress, err := channelProgress(ctx, tx, project, frame.repository, parent, channel) if err != nil { return nil, err @@ -399,7 +419,11 @@ func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project str if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM review_comparison_proofs WHERE project_id=? AND pull_number=? AND channel='`+channel+`' AND state='ready'`, project, parent).Scan(&completed); err != nil { return nil, err } - out = append(out, []any{parent, p.HeadSHA, p.ParentPullNumber, p.ParentSHA, progress, control.Configured, control.Epoch, control.grantRevision, control.Closed, control.Used, control.Dry, control.Tapered, completed, obligations, routes}) + facts := []any{parent, p.HeadSHA, p.ParentPullNumber, p.ParentSHA, progress, control.Configured, control.Epoch, control.grantRevision, control.Closed, control.Used, control.Dry, control.Tapered, completed, obligations, routes} + if parentFacts != nil { + parentFacts[parent] = facts + } + out = append(out, facts) parent = p.ParentPullNumber } return out, nil diff --git a/internal/reviewexec/scheduling_basis_contract_test.go b/internal/reviewexec/scheduling_basis_contract_test.go new file mode 100644 index 000000000..e0a49deb8 --- /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}) + 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_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 29e4a7381..c35141904 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -67,8 +67,8 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { var ahead bool err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events e LEFT JOIN review_scheduling s ON s.project_id=e.project_id - WHERE e.event_type='review.scheduling_updated' AND e.resource_id=e.project_id - AND (s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) + WHERE e.event_type='review.scheduling_updated' + AND (typeof(e.resource_id)<>'text' OR e.resource_id<>e.project_id OR s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) if err != nil { return err } diff --git a/internal/reviewexec/scheduling_source_acceptance_test.go b/internal/reviewexec/scheduling_source_acceptance_test.go index c23544477..e2fb445c3 100644 --- a/internal/reviewexec/scheduling_source_acceptance_test.go +++ b/internal/reviewexec/scheduling_source_acceptance_test.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "testing" + "time" ) func TestInitialAutomaticSourceAcceptanceRequiresCanonicalEvidence(t *testing.T) { @@ -36,3 +37,33 @@ func TestInitialAutomaticSourceAcceptanceRequiresCanonicalEvidence(t *testing.T) 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..4bf3f2a64 --- /dev/null +++ b/internal/reviewexec/scheduling_source_hold_basis_test.go @@ -0,0 +1,66 @@ +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 settled string + if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, receipt.ID).Scan(&settled); err != nil { + t.Fatal(err) + } + if edited && settled != "" || !edited && !hash.MatchString(settled) { + t.Fatalf("unexpected settled basis after lawful source hold: edited=%v basis=%q", edited, settled) + } + }) + } +} diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index f7235dc90..9a72394d2 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -75,16 +75,21 @@ func verifiedInitialAutomaticSourceAcceptance(ctx context.Context, q EvidenceQue // A revision alone cannot distinguish restart recovery from a completed hold. // Prove every retained transition was an unfinished read before relaxing the // exact-revision fence. A held event (whatever its reason), missing/duplicate -// revision or malformed payload keeps that fence. Aggregate in SQL rather than +// revision, non-increasing event sequence or malformed payload keeps that fence. Aggregate in SQL rather than // copying an unbounded event history into each admission snapshot. func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, error) { var count, distinct, first, last, invalid int64 - err := tx.QueryRowContext(ctx, `SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( - CASE WHEN typeof(revision)='integer' AND json_valid(payload_json) THEN + err := tx.QueryRowContext(ctx, `WITH transitions AS ( + SELECT revision,sequence,payload_json,lag(sequence) OVER (ORDER BY revision,sequence) AS previous_sequence + FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' AND revision BETWEEN 2 AND ? + ) + SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( + CASE WHEN typeof(revision)='integer' AND typeof(sequence)='integer' AND sequence>0 AND + (previous_sequence IS NULL OR sequence>previous_sequence) AND json_valid(payload_json) THEN CASE WHEN json_extract(payload_json,'$.state')=CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END AND json_extract(payload_json,'$.reason')='' AND (revision<>? OR json_extract(payload_json,'$.state')=?) THEN 0 ELSE 1 END ELSE 1 END),0) - FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' AND revision BETWEEN 2 AND ?`, r.Revision, r.State, r.ProjectID, r.ID, r.Revision).Scan(&count, &distinct, &first, &last, &invalid) + FROM transitions`, r.ProjectID, r.ID, r.Revision, r.Revision, r.State).Scan(&count, &distinct, &first, &last, &invalid) if err != nil { return false, err } diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index 303f3bce1..dacd93e57 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -442,12 +442,6 @@ func TestValidateSchedulingSnapshotRejectsStaleProjectProjection(t *testing.T) { (?,'review.scheduling_updated',?,1,?,'{"automatic_hosted":true,"automatic_cli":false}',?), (?,'review.scheduling_updated',?,2,?,'{"automatic_hosted":false,"automatic_cli":false}',?)`, attemptProject, attemptProject, scope.PrincipalID, at, attemptProject, attemptProject, scope.PrincipalID, at) - for _, identity := range [][2]string{{otherAttemptProject, attemptProject}, {attemptProject, otherAttemptProject}} { - admissionSQL(t, f, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) - SELECT ?,event_type,?,revision+1,actor_id,payload_json,created_at FROM events - WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision=2`, - identity[0], identity[1], attemptProject, attemptProject) - } if err := validateSchedulingSnapshotForTest(t, f); err != nil { t.Fatalf("healthy rev-2 projection rejected: %v", err) } From 56d6b94435ece3049d916adb8f7c436ab42048ae Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 20:02:43 +1300 Subject: [PATCH 08/34] Bound optional queued diagnostics to the selection response deadline --- internal/reviewexec/operation_wait.go | 6 ++- internal/reviewexec/queued_diagnostic.go | 23 ++++++++++-- internal/reviewexec/run_http.go | 10 +++-- internal/reviewexec/run_http_test.go | 48 +++++++++++++++++++++++- 4 files changed, 77 insertions(+), 10 deletions(-) diff --git a/internal/reviewexec/operation_wait.go b/internal/reviewexec/operation_wait.go index 3b1531c00..f93945698 100644 --- a/internal/reviewexec/operation_wait.go +++ b/internal/reviewexec/operation_wait.go @@ -175,8 +175,12 @@ func operationPreference(r *http.Request, defaultSeconds int) (int, error) { return seconds, nil } +func operationResultWriteDeadline(seconds int) time.Time { + return time.Now().Add(time.Duration(seconds+5) * time.Second) +} + func operationResponseDeadline(w http.ResponseWriter, seconds int) error { - return operationResponseDeadlineAt(w, time.Now().Add(time.Duration(seconds+5)*time.Second)) + return operationResponseDeadlineAt(w, operationResultWriteDeadline(seconds)) } func operationResponseDeadlineAt(w http.ResponseWriter, deadline time.Time) error { diff --git a/internal/reviewexec/queued_diagnostic.go b/internal/reviewexec/queued_diagnostic.go index f53e66284..de2960460 100644 --- a/internal/reviewexec/queued_diagnostic.go +++ b/internal/reviewexec/queued_diagnostic.go @@ -27,14 +27,31 @@ type queuedReservation struct { // admission authority. Drift or unavailable facts omit the header, not the // original response/receipt. The exact operation is reauthorized and compared // with the response revision before consulting any current scheduling facts. +const queuedDiagnosticBudget = 250 * time.Millisecond + func (e *Engine) queuedResponseHeader(w http.ResponseWriter, r *http.Request, scope core.Scope, id, state, channel string, revision int64) { + e.queuedResponseHeaderBefore(w, r, scope, id, state, channel, revision, time.Time{}) +} + +func (e *Engine) queuedResponseHeaderBefore(w http.ResponseWriter, r *http.Request, scope core.Scope, id, state, channel string, revision int64, responseDeadline time.Time) { if state != "queued" { return } // Optional diagnostics must not consume another two-second Store read // after the two required selection/operation reads in the five-second // response budget. Leave headroom for encoding and network writes. - ctx, cancel := context.WithTimeout(r.Context(), 250*time.Millisecond) + deadline := time.Now().Add(queuedDiagnosticBudget) + if !responseDeadline.IsZero() { + // SetWriteDeadline bounds the socket, not the request context. + // Leave a separate window for encoding and writing the retained result. + if latest := responseDeadline.Add(-queuedDiagnosticBudget); latest.Before(deadline) { + deadline = latest + } + } + if !deadline.After(time.Now()) { + return + } + ctx, cancel := context.WithDeadline(r.Context(), deadline) defer cancel() cause, reservation := e.queuedDiagnosticDetails(ctx, scope, id, revision) if cause == "queue_order" && channel == "cli" && r.Header.Get(operationWaitHeader) != "2" && r.Header.Get(operationWaitHeader) != "3" && r.Header.Get(operationWaitHeader) != "4" && r.Header.Get(operationWaitHeader) != "5" { @@ -214,9 +231,9 @@ func queuedReservationHolder(ctx context.Context, tx *sql.Tx, waiting Operation, func reservationLiveState(state string) bool { return state == "preparing" || state == "posting" || state == "active" || state == "uncertain" } -func (e *Engine) queuedRunResponseHeader(w http.ResponseWriter, r *http.Request, scope core.Scope, state RunState) { +func (e *Engine) queuedRunResponseHeader(w http.ResponseWriter, r *http.Request, scope core.Scope, state RunState, responseDeadline time.Time) { if state.Operation != nil { o := state.Operation - e.queuedResponseHeader(w, r, scope, o.ID, o.State, o.Channel, o.Revision) + e.queuedResponseHeaderBefore(w, r, scope, o.ID, o.State, o.Channel, o.Revision, responseDeadline) } } diff --git a/internal/reviewexec/run_http.go b/internal/reviewexec/run_http.go index 40de29052..9230d9063 100644 --- a/internal/reviewexec/run_http.go +++ b/internal/reviewexec/run_http.go @@ -140,7 +140,8 @@ func (e *Engine) enqueueRunHTTP(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } - if err = operationResponseDeadline(w, seconds); err != nil { + responseDeadline := operationResultWriteDeadline(seconds) + if err = operationResponseDeadlineAt(w, responseDeadline); err != nil { core.WriteError(w, err) return } @@ -168,7 +169,7 @@ func (e *Engine) enqueueRunHTTP(w http.ResponseWriter, r *http.Request) { return } if terminal { - e.queuedRunResponseHeader(w, r, scope, state) + e.queuedRunResponseHeader(w, r, scope, state, responseDeadline) core.WriteJSON(w, http.StatusOK, runStateForResponse(state, r.Header.Get(operationWaitHeader))) return } @@ -197,7 +198,8 @@ func (e *Engine) readRunHTTP(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } - if err = operationResponseDeadline(w, seconds); err != nil { + responseDeadline := operationResultWriteDeadline(seconds) + if err = operationResponseDeadlineAt(w, responseDeadline); err != nil { core.WriteError(w, err) return } @@ -207,6 +209,6 @@ func (e *Engine) readRunHTTP(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } - e.queuedRunResponseHeader(w, r, scope, state) + e.queuedRunResponseHeader(w, r, scope, state, responseDeadline) core.WriteJSON(w, http.StatusOK, runStateForResponse(state, r.Header.Get(operationWaitHeader))) } diff --git a/internal/reviewexec/run_http_test.go b/internal/reviewexec/run_http_test.go index 379335c7e..8872215a3 100644 --- a/internal/reviewexec/run_http_test.go +++ b/internal/reviewexec/run_http_test.go @@ -224,12 +224,13 @@ func TestQueuedRunDiagnosticPreservesNetworkResponseUnderContention(t *testing.T } server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Model the remaining budget after required selection and operation reads. - if err := operationResponseDeadlineAt(w, time.Now().Add(750*time.Millisecond)); err != nil { + deadline := time.Now().Add(750 * time.Millisecond) + if err := operationResponseDeadlineAt(w, deadline); err != nil { t.Error(err) return } e := f.e - e.queuedRunResponseHeader(w, r, scope, RunState{Operation: &Operation{ID: "review_operation_test", State: "queued", Channel: "cli", Revision: 1}}) + e.queuedRunResponseHeader(w, r, scope, RunState{Operation: &Operation{ID: "review_operation_test", State: "queued", Channel: "cli", Revision: 1}}, deadline) w.Write([]byte("retained response")) })) defer func() { @@ -254,6 +255,49 @@ func TestQueuedRunDiagnosticPreservesNetworkResponseUnderContention(t *testing.T } } +func TestQueuedRunDiagnosticOmitsHintBeforeRetainedResponseDeadline(t *testing.T) { + f := selectionFixture(t) + receipt, _ := selectionEnqueue(t, f, "queued-diagnostic-deadline", "cli", nil) + selectionNext(t, f, &refreshTestReader{}) + scope := selectionScope(t, f, attemptProject, f.writer, "read") + state, terminal, err := f.e.readRunState(t.Context(), scope, receipt.ID) + if err != nil || terminal || state.Operation == nil || state.Operation.State != "queued" { + t.Fatalf("expected the original pending queued child: %+v (%v)", state, err) + } + + // A normal hint proves this fixture is otherwise eligible for diagnostics. + req := httptest.NewRequest(http.MethodGet, "/", nil) + w := httptest.NewRecorder() + f.e.queuedRunResponseHeader(w, req, scope, state, time.Now().Add(time.Second)) + if w.Header().Get(queuedDiagnosticHeader) == "" { + t.Fatal("eligible queued diagnostic missing with ample budget") + } + + // A lawful retained response has already used most of its write budget. + // The optional diagnostic must not wait for the reserved reader connection. + f.store.DB().SetMaxOpenConns(1) + conn, err := f.store.DB().Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + before := f.store.DB().Stats().WaitCount + w = httptest.NewRecorder() + deadline := time.Now().Add(queuedDiagnosticBudget / 2) + f.e.queuedRunResponseHeader(w, req, scope, state, deadline) + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode(state); err != nil { + t.Fatal(err) + } + var result RunState + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil || result.Selection.ID != receipt.ID || result.Operation == nil || result.Operation.ID != state.Operation.ID || w.Code != http.StatusOK { + t.Fatalf("could not return original retained child: %s (%v)", w.Body, err) + } + if w.Header().Get(queuedDiagnosticHeader) != "" || f.store.DB().Stats().WaitCount != before { + t.Fatal("optional diagnostic should be omitted without trying reader admission") + } +} + func TestRunHTTPProjectsSelectedCLIWait(t *testing.T) { f := selectionFixture(t) receipt, _ := selectionEnqueue(t, f, "selected-cli-wait", "cli", nil) From 234b15ea5e6b9f301869225f3f2b1742f7b2f39b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 20:33:55 +1300 Subject: [PATCH 09/34] Roll back provisional selection frame on a typed finish refusal --- internal/reviewexec/run_selection_worker.go | 10 ++++++---- internal/reviewexec/scheduling_basis_contract_test.go | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 5fc376b2d..77fa230bd 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -217,13 +217,13 @@ func retryRunSelectionRead(ctx context.Context, local func() error) error { } // The source hold must not settle PR-local revisions that were not read. -func readAutomaticPullSchedulingRevisions(ctx context.Context, tx *sql.Tx, project string, pulls []int64) ([]int64, error) { +func readAutomaticPullSchedulingRevisions(ctx context.Context, tx *sql.Tx, project string, pulls []int64, tolerateUnreadable bool) ([]int64, error) { revisions := make([]int64, 0, len(pulls)) for _, pull := range pulls { current, err := readPullScheduling(ctx, tx, project, pull) if err != nil { var local *pullSchedulingStateError - if !errors.As(err, &local) { + if !tolerateUnreadable || !errors.As(err, &local) { return nil, err } revisions = append(revisions, -1) @@ -275,7 +275,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 if err != nil { return err } - pullScheduling, err = readAutomaticPullSchedulingRevisions(ctx, tx, r.ProjectID, c.Queue[:limit]) + pullScheduling, err = readAutomaticPullSchedulingRevisions(ctx, tx, r.ProjectID, c.Queue[:limit], true) return err }) }) @@ -729,7 +729,9 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat settle = resultErr == nil && currentBasis == choice.automaticBasisRevision if settle { var revisions []int64 - revisions, resultErr = readAutomaticPullSchedulingRevisions(ctx, tx, r.ProjectID, boundPrefix) + // A newly unreadable row must roll back the provisional + // front frame; it is not equivalent to an ordinary revision change. + revisions, resultErr = readAutomaticPullSchedulingRevisions(ctx, tx, r.ProjectID, boundPrefix, false) settle = resultErr == nil && slices.Equal(revisions, choice.automaticPullScheduling) } } diff --git a/internal/reviewexec/scheduling_basis_contract_test.go b/internal/reviewexec/scheduling_basis_contract_test.go index e0a49deb8..edd02a312 100644 --- a/internal/reviewexec/scheduling_basis_contract_test.go +++ b/internal/reviewexec/scheduling_basis_contract_test.go @@ -14,7 +14,7 @@ func TestPlanningSnapshotPinsOrdinaryPullPauseRevisions(t *testing.T) { 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}) + got, err = readAutomaticPullSchedulingRevisions(ctx, tx, attemptProject, []int64{2, 4}, false) return err }) if err != nil { From d8a5148b38c9f1d14a68df1c6c6d6e72dc3f93fe Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 20:51:42 +1300 Subject: [PATCH 10/34] Settle only unused preparation with typed round-history refusal --- internal/reviewexec/supervisor.go | 8 ++++---- internal/reviewexec/supervisor_classification_test.go | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 8a7432405..615631610 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -680,16 +680,16 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr return e.processPendingBatch(ctx, drivers, releaseProbe, worker, operations, receipt) } -// A typed scheduling refusal requeues only unused preparation. Other local -// history failures retain the preparation and reservation. +// A typed scheduling or round-control refusal requeues only unused +// preparation. Other local history failures retain the reservation. func (e *Engine) classifyUnavailablePreparation(ctx context.Context, o Operation, a Attempt, err error) (bool, error) { if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { return true, nil } - if schedulingRefused(err) { + if schedulingRefused(err) || isStoredUnavailable(err, storedRoundHistory) { return true, e.finishPreparation(a, "held", "automatic_scheduling_unavailable") } - return automaticProjectRefused(err) || isStoredUnavailable(err, storedRoundHistory), nil + return automaticProjectRefused(err), nil } func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Driver, releaseProbe func(), worker int, operations []Operation, receipt pendingExhaustion) error { diff --git a/internal/reviewexec/supervisor_classification_test.go b/internal/reviewexec/supervisor_classification_test.go index d675d716c..1efa0eda6 100644 --- a/internal/reviewexec/supervisor_classification_test.go +++ b/internal/reviewexec/supervisor_classification_test.go @@ -13,7 +13,7 @@ func TestSupervisorTypedPreparationRefusals(t *testing.T) { reservations int }{ {"scheduling", "queued", "automatic_scheduling_unavailable", schedulingRecordUnavailable, 0}, - {"round-history", "preparing", "", roundUnavailable, 1}, + {"round-history", "queued", "automatic_scheduling_unavailable", roundUnavailable, 0}, {"retained-history", "preparing", "", func() error { return automaticProjectStateFailure("storage_unavailable", "Synthetic retained history unavailable.", 503) }, 1}, From c377c5a633bc02ab578270dbde7984cd3eeb8627 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 17:03:35 +1300 Subject: [PATCH 11/34] Keep selected review children from settling a rearmed lane --- internal/reviewexec/run_selection_worker.go | 8 +- .../scheduling_selected_basis_guard_test.go | 80 +++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 internal/reviewexec/scheduling_selected_basis_guard_test.go diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 77fa230bd..23f98b9de 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -721,13 +721,13 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return } settle := state != "queued" && reason != "selection_changed" - if settle && pull == 0 && choice.automaticQueueLimit != nil && choice.automaticBasisRevision != 0 { + if settle && choice.automaticQueueLimit != nil && choice.automaticBasisRevision != 0 { var currentBasis int64 currentBasis, resultErr = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) - // An old no-child result is still retained as history, but - // it cannot suppress the source read of a newly rearmed lane. + // Retain an older result and any selected child as history. + // It must not mark a newly rearmed lane basis served. settle = resultErr == nil && currentBasis == choice.automaticBasisRevision - if settle { + if settle && pull == 0 { var revisions []int64 // A newly unreadable row must roll back the provisional // front frame; it is not equivalent to an ordinary revision change. diff --git a/internal/reviewexec/scheduling_selected_basis_guard_test.go b/internal/reviewexec/scheduling_selected_basis_guard_test.go new file mode 100644 index 000000000..71106f6f1 --- /dev/null +++ b/internal/reviewexec/scheduling_selected_basis_guard_test.go @@ -0,0 +1,80 @@ +package reviewexec + +import ( + "context" + "database/sql" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestSelectedChildDoesNotSettleRearmedLaneBasis(t *testing.T) { + for _, rearm := range []bool{false, true} { + name := "stable-basis" + if rearm { + name = "rearmed-during-valid-read" + } + t.Run(name, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + 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, "hosted_basis_revision": 1, "cli_basis_revision": 1}); 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) + } + edited := false + reader := &refreshTestReader{repository: func(ctx context.Context, id int64) (reviewprovider.Repository, error) { + if rearm && !edited { + err := f.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `UPDATE review_scheduling SET revision=2, updated_at=? WHERE project_id=? AND revision=1`, stamp(), scope.ProjectID); err != nil { + return err + } + return core.AppendEvent(ctx, tx, scope, "review.scheduling_updated", scope.ProjectID, 2, map[string]any{"automatic_hosted": true, "automatic_cli": false, "hosted_basis_revision": 2, "cli_basis_revision": 1}) + }) + if err != nil { + return reviewprovider.Repository{}, err + } + edited = true + } + return reviewprovider.Repository{ID: id, FullName: "owner/repo", DefaultBranch: "main"}, nil + }} + selectionNext(t, f, reader) + got := selectionRead(t, f, receipt.ID) + if edited != rearm || got.State != "selected" || got.OperationID == "" { + t.Fatalf("legitimate selection did not keep its linked child: rearm=%v callback=%v got=%+v", rearm, edited, got) + } + var settled, pullBasis string + var pull int64 + if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256,pull_number,pull_basis_sha256 FROM review_automatic_selections WHERE selection_id=? AND project_id=?`, receipt.ID, scope.ProjectID).Scan(&settled, &pull, &pullBasis); err != nil { + t.Fatal(err) + } + if rearm { + if settled != "" || pull != 0 || pullBasis != "" { + t.Fatalf("old selection incorrectly marked a rearmed lane served") + } + } else if !hash.MatchString(settled) || pull != 2 || !hash.MatchString(pullBasis) { + t.Fatalf("stable selection did not settle its own lane/pull basis") + } + }) + } +} From fba69781c683dabc4f60fc5792492d031c2a1744 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 10:47:22 +1300 Subject: [PATCH 12/34] Isolate unreadable review planning and settle proven unused CLI attempts --- internal/reviewexec/allowance_observation.go | 1 + internal/reviewexec/attempts.go | 151 ++++++++++++------ .../reviewexec/cli_policy_settlement_test.go | 80 ++++++++++ internal/reviewexec/policy.go | 2 +- internal/reviewexec/scheduling.go | 6 +- internal/reviewexec/scheduling_automatic.go | 14 +- .../scheduling_boundary_compatibility_test.go | 8 + internal/reviewexec/supervisor.go | 13 +- 8 files changed, 224 insertions(+), 51 deletions(-) create mode 100644 internal/reviewexec/cli_policy_settlement_test.go diff --git a/internal/reviewexec/allowance_observation.go b/internal/reviewexec/allowance_observation.go index f24d2e9ff..f86d6a1c6 100644 --- a/internal/reviewexec/allowance_observation.go +++ b/internal/reviewexec/allowance_observation.go @@ -28,6 +28,7 @@ const ( storedConfigurationHistory storedOperationIdentity storedRoundHistory + storedPolicyHistory ) type storedUnavailableError struct { diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 5dfadc76f..2c3dac33b 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -234,11 +234,20 @@ func readAttempt(ctx context.Context, tx EvidenceQuery, project, id string) (Att // Admit persists the exact comparison and external intent before the adapter // may post or start its command. The caller owns fresh queue/allowance proof. func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision int64, anchor Anchor, intent string) (Attempt, error) { + return e.admit(ctx, project, id, expectedRevision, anchor, intent, false) +} + +type preparedCLIAdmissionRefusal struct{ error } + +func (e *preparedCLIAdmissionRefusal) Unwrap() error { return e.error } + +func (e *Engine) admit(ctx context.Context, project, id string, expectedRevision int64, anchor Anchor, intent string, settlePreparedCLI bool) (Attempt, error) { observed, err := time.Parse(time.RFC3339Nano, anchor.ObservedAt) if err != nil || time.Since(observed) > time.Minute || observed.After(time.Now().Add(5*time.Second)) || anchor.RepositoryID <= 0 || anchor.ParentPullNumber < 0 || anchor.ParentPullNumber > 2147483647 || !safeText(anchor.BaseRef, 256) || anchor.BaseRef == "" || !repository.MatchString(anchor.Repository) || !sha.MatchString(anchor.CandidateSHA) || !sha.MatchString(anchor.BaseSHA) || !sha.MatchString(anchor.ParentSHA) || !sha.MatchString(anchor.MergeBaseSHA) || !hash.MatchString(anchor.PatchSHA256) || !safeText(intent, 4096) { return Attempt{}, invalid() } var result Attempt + var handlingPreparedRefusal bool err = e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { a, err := readAttempt(ctx, tx, project, id) if err != nil { @@ -268,6 +277,11 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision if errors.As(err, &binding) { return &schedulingStateError{err} } + var schedulingHistory *schedulingHistoryUnavailable + if settlePreparedCLI && o.Channel == "cli" && intent == "" && !schedulingRefused(err) && errors.As(err, &schedulingHistory) { + handlingPreparedRefusal = true + result, err = e.settleCLIAdmissionRefusal(ctx, tx, o, a, anchor, err) + } return err } if err := requireSourceObligationsClear(ctx, tx, project, o.PullNumber); err != nil { @@ -301,6 +315,10 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision } _, reason, err := boundPolicy(ctx, tx, o) if err != nil { + if settlePreparedCLI && o.Channel == "cli" && intent == "" && isStoredUnavailable(err, storedPolicyHistory) { + handlingPreparedRefusal = true + result, err = e.settleCLIAdmissionRefusal(ctx, tx, o, a, anchor, err) + } return err } if reason != "" { @@ -343,10 +361,47 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision }) if err == nil { e.notifyOperation(result.OperationID) + } else if handlingPreparedRefusal { + // Guard or transaction failures must not enter generic admission + // settlement, even if the caller is also shutting down. + return Attempt{}, &preparedCLIAdmissionRefusal{err} } return result, err } +// Keep the original request queued when admission could not read its policy +// or automatic scheduling history and its prepared CLI attempt is provably unused. +func (e *Engine) settleCLIAdmissionRefusal(ctx context.Context, tx *sql.Tx, o Operation, a Attempt, anchor Anchor, refusal error) (Attempt, error) { + if o.Channel != "cli" || o.State != "preparing" || o.AttemptID != a.ID || + a.State != "preparing" || a.Revision != 1 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { + return Attempt{}, refusal + } + record, err := readCLIAllowanceRecord(ctx, tx, o, a) + if errors.Is(err, errAllowanceObservationAbsent) { + return Attempt{}, refusal + } + if err != nil { + return Attempt{}, err + } + if record.Observation.Remaining <= 0 || record.Observation.Anchor != anchor { + return Attempt{}, refusal + } + var unused bool + err = tx.QueryRowContext(ctx, `SELECT + EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=? AND provider=? AND account=? AND repository_id=? AND pull_number=? AND action_class='cli') + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=1 AND state='preparing' AND reason='preparing' AND external_id='') + AND NOT EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision<>1) + AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, + a.ID, a.Provider, a.Account, anchor.RepositoryID, o.PullNumber, a.ID, a.ID, a.ID).Scan(&unused) + if err != nil { + return Attempt{}, err + } + if !unused { + return Attempt{}, refusal + } + return e.advanceAttempt(ctx, tx, o, a, "held", "automatic_scheduling_unavailable", "") +} + func safeText(s string, max int) bool { if len(s) > max || !utf8.ValidString(s) { return false @@ -389,51 +444,8 @@ func (e *Engine) Advance(ctx context.Context, project, id string, expectedRevisi if err != nil { return err } - at, err := attemptRecordingStamp(ctx, tx, o, &a, e.sampleAttemptTime()) - if err != nil { - return err - } - if externalID != "" { - a.ExternalID = externalID - } - if a.State == "posting" && state == "active" && a.ExternalID == "" { - return invalid() - } - a.State = state - a.Revision++ - if _, err = tx.ExecContext(ctx, `UPDATE review_execution_attempts SET state=?,revision=?,external_id=? WHERE id=?`, state, a.Revision, a.ExternalID, a.ID); err != nil { - return err - } - operationState, operationAttempt := state, o.AttemptID - // Only an unused preparation may detach and retain the same queued intent. - retainQueued := o.Channel == "cli" && reason == cliDraftWait || reason == "pull_scheduling_paused" || reason == "automation_authorization_changed" || reason == "automatic_scheduling_unavailable" - if retainQueued && state == "held" && o.State == "preparing" && o.AttemptID == a.ID && a.Anchor == nil && a.Intent == "" && a.ExternalID == "" { - operationState, operationAttempt = "queued", "" - } - if _, err = tx.ExecContext(ctx, `UPDATE review_operations SET state=?,revision=revision+1,reason=?,attempt_id=?,updated_at=? WHERE id=?`, operationState, reason, operationAttempt, at, a.OperationID); err != nil { - return err - } - if state != "posting" && state != "active" && state != "uncertain" { - if _, err = tx.ExecContext(ctx, `DELETE FROM review_execution_reservations WHERE attempt_id=?`, a.ID); err != nil { - return err - } - } - if err = e.transitionRow(ctx, tx, a, reason, at); err != nil { - return err - } - if err = core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}); err != nil { - return err - } - if state == "completed" { - if err = refreshComparisonProof(ctx, tx, project, a.OperationID); err != nil { - return err - } - if err = completeRoundControl(ctx, tx, project, a.OperationID); err != nil { - return err - } - } - result = a - return nil + result, err = e.advanceAttempt(ctx, tx, o, a, state, reason, externalID) + return err }) if err == nil { e.notifyOperation(result.OperationID) @@ -441,6 +453,55 @@ func (e *Engine) Advance(ctx context.Context, project, id string, expectedRevisi return result, err } +// advanceAttempt records a transition for the attempt and operation already +// checked in this write transaction. +func (e *Engine) advanceAttempt(ctx context.Context, tx *sql.Tx, o Operation, a Attempt, state, reason, externalID string) (Attempt, error) { + at, err := attemptRecordingStamp(ctx, tx, o, &a, e.sampleAttemptTime()) + if err != nil { + return Attempt{}, err + } + if externalID != "" { + a.ExternalID = externalID + } + if a.State == "posting" && state == "active" && a.ExternalID == "" { + return Attempt{}, invalid() + } + a.State = state + a.Revision++ + if _, err = tx.ExecContext(ctx, `UPDATE review_execution_attempts SET state=?,revision=?,external_id=? WHERE id=?`, state, a.Revision, a.ExternalID, a.ID); err != nil { + return Attempt{}, err + } + operationState, operationAttempt := state, o.AttemptID + // Only an unused preparation may detach and retain the same queued intent. + retainQueued := o.Channel == "cli" && reason == cliDraftWait || reason == "pull_scheduling_paused" || reason == "automation_authorization_changed" || reason == "automatic_scheduling_unavailable" + if retainQueued && state == "held" && o.State == "preparing" && o.AttemptID == a.ID && a.Anchor == nil && a.Intent == "" && a.ExternalID == "" { + operationState, operationAttempt = "queued", "" + } + if _, err = tx.ExecContext(ctx, `UPDATE review_operations SET state=?,revision=revision+1,reason=?,attempt_id=?,updated_at=? WHERE id=?`, operationState, reason, operationAttempt, at, a.OperationID); err != nil { + return Attempt{}, err + } + if state != "posting" && state != "active" && state != "uncertain" { + if _, err = tx.ExecContext(ctx, `DELETE FROM review_execution_reservations WHERE attempt_id=?`, a.ID); err != nil { + return Attempt{}, err + } + } + if err = e.transitionRow(ctx, tx, a, reason, at); err != nil { + return Attempt{}, err + } + if err = core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, "review.operation_updated", o.ID, o.Revision+1, struct{}{}); err != nil { + return Attempt{}, err + } + if state == "completed" { + if err = refreshComparisonProof(ctx, tx, a.ProjectID, a.OperationID); err != nil { + return Attempt{}, err + } + if err = completeRoundControl(ctx, tx, a.ProjectID, a.OperationID); err != nil { + return Attempt{}, err + } + } + return a, nil +} + func allowedTransition(from, to string) bool { switch from { case "preparing": diff --git a/internal/reviewexec/cli_policy_settlement_test.go b/internal/reviewexec/cli_policy_settlement_test.go new file mode 100644 index 000000000..65e2d65c6 --- /dev/null +++ b/internal/reviewexec/cli_policy_settlement_test.go @@ -0,0 +1,80 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "strings" + "testing" +) + +func TestPreparedCLIAdmissionRefusalSettlement(t *testing.T) { + for _, scenario := range []string{"policy", "scheduling", "absent", "exhausted", "different-comparison", "publication-failure"} { + t.Run(scenario, func(t *testing.T) { + f, a, input := cliAllowanceFixture(t) + anchor := input.Anchor + switch scenario { + case "absent": + case "exhausted": + input.Remaining = 0 + if err := f.e.RecordCLIExhaustion(t.Context(), a.ProjectID, a.ID, a.Revision, input); err != nil { + t.Fatal(err) + } + default: + if err := f.e.RecordCLIAllowance(t.Context(), a.ProjectID, a.ID, a.Revision, input); err != nil { + t.Fatal(err) + } + } + if scenario == "different-comparison" { + anchor.PatchSHA256 = strings.Repeat("9", 64) + } + refusal := newStoredUnavailable(storedPolicyHistory, "Policy history unavailable in fixture.") + if scenario == "scheduling" { + refusal = schedulingUnavailable() + } + publicationFailure := errors.New("attempt projection unavailable in fixture") + if scenario == "publication-failure" { + f.e.publishAttempt = func(context.Context, *sql.Tx, Attempt) error { + return publicationFailure + } + } + before := cliAllowanceState(t, f, a) + original := roundOperation(t, f, a.OperationID) + var settled Attempt + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + op, err := readOperationBase(ctx, tx, a.ProjectID, a.OperationID) + if err != nil { + return err + } + settled, err = f.e.settleCLIAdmissionRefusal(ctx, tx, op, a, anchor, refusal) + if scenario == "publication-failure" && !errors.Is(err, publicationFailure) { + t.Errorf("expected attempt publication to fail, got %v", err) + } + return err + }) + if scenario != "policy" && scenario != "scheduling" { + if err == nil || scenario != "publication-failure" && !errors.Is(err, refusal) { + t.Fatalf("expected settlement to be refused, got %v", err) + } + if after := cliAllowanceState(t, f, a); after != before { + t.Fatal("refused settlement changed the journal, allowance, or reservation") + } + return + } + if err != nil { + t.Fatal(err) + } + queued := roundOperation(t, f, a.OperationID) + if settled.ID != a.ID || settled.Revision != 2 || settled.State != "held" || + queued.ID != original.ID || queued.Revision != original.Revision+1 || queued.State != "queued" || + queued.AttemptID != "" || queued.Reason != "automatic_scheduling_unavailable" { + t.Fatalf("expected the original request to be queued with its unused attempt held, got %+v and %+v", queued, settled) + } + if attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != 0 { + t.Fatal("unused attempt retained its reservation") + } + assertCLIWaitSnapshot(t, f) + assertCLIWaitNoCredit(t, f) + }) + } +} diff --git a/internal/reviewexec/policy.go b/internal/reviewexec/policy.go index eb0230529..8e9995779 100644 --- a/internal/reviewexec/policy.go +++ b/internal/reviewexec/policy.go @@ -124,7 +124,7 @@ func readPolicy(ctx context.Context, tx *sql.Tx, project string) (PolicyRecord, body, validBody = bodyValue.(string) record.Revision, validRevision = revisionValue.(int64) if !validBody || !validRevision || record.Revision < 1 || len(body) > 1024 || strictjson.Decode([]byte(body), &record.Policy) != nil || !validPolicy(record.Policy) { - return PolicyRecord{}, automaticProjectStateFailure("storage_unavailable", "Stored project review policy is unavailable.", 500) + return PolicyRecord{}, &automaticProjectStateError{newStoredUnavailable(storedPolicyHistory, "Stored project review policy is unavailable.")} } return record, nil } diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index 039374418..afa8ff24e 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -51,8 +51,12 @@ type schedulingStateError struct{ error } func (e *schedulingStateError) Unwrap() error { return e.error } +type schedulingHistoryUnavailable struct{ error } + +func (e *schedulingHistoryUnavailable) Unwrap() error { return e.error } + func schedulingUnavailable() error { - return automaticProjectStateFailure("storage_unavailable", "Stored review scheduling is unavailable.", 503) + return &automaticProjectStateError{&schedulingHistoryUnavailable{core.Fail("storage_unavailable", "Stored review scheduling is unavailable.", 503)}} } func schedulingRecordUnavailable() error { diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index ec75b1890..5eeae8f20 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -459,7 +459,15 @@ func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project st for _, pull := range queue { p, err := readPullScheduling(ctx, tx, project, pull) if err != nil { - return "", false, err + var local *pullSchedulingStateError + if !errors.As(err, &local) || local.project != project || local.pull != pull { + return "", false, err + } + // A missing readable control cannot establish this PR's basis. + // Keep its position in the degraded digest and assess later PRs. + values = append(values, []any{pull, nil, nil}) + degraded = true + continue } basis, err := automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) if err != nil { @@ -495,8 +503,8 @@ func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project st } var digestInput any = []any{values, remaining} if degraded { - // Version the encoding so it cannot be treated as an equivalent - // full-queue basis or rearm a full-digest-only historical intent. + // Preserve the paused-row encoding. An unreadable control has no + // verified revision, so its null revision cannot match that case. digestInput = []any{"planning_basis_degraded_paused_v1", values, remaining} } sum := sha256.Sum256([]byte(encoded(digestInput))) diff --git a/internal/reviewexec/scheduling_boundary_compatibility_test.go b/internal/reviewexec/scheduling_boundary_compatibility_test.go index 73955959c..ab9f4c625 100644 --- a/internal/reviewexec/scheduling_boundary_compatibility_test.go +++ b/internal/reviewexec/scheduling_boundary_compatibility_test.go @@ -47,6 +47,14 @@ func TestFrontLocalSchedulingHoldPreservesIndependentAndStackedEligibility(t *te independent := SourcePlan{Repository: parent.Repository, Pull: reviewprovider.Pull{RepositoryID: 801, Number: 4, State: "open", HeadSHA: strings.Repeat("b", 40), BaseSHA: strings.Repeat("a", 40)}} if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { r := Run{ProjectID: attemptProject, Channel: "cli"} + basis, eligible, err := automaticPlanningBasisForPrefix(ctx, tx, attemptProject, []int64{2, 4}, "", r.Channel) + if err != nil || !eligible || !hash.MatchString(basis) { + t.Fatalf("independent PR did not produce an eligible planning basis: %q %v %v", basis, eligible, err) + } + basis, eligible, err = automaticPlanningBasisForPrefix(ctx, tx, attemptProject, []int64{2}, "", r.Channel) + if err != nil || eligible || !hash.MatchString(basis) { + t.Fatalf("unreadable PR was not excluded from planning: %q %v %v", basis, eligible, err) + } got, err := f.e.evaluateFront(ctx, tx, r, 801, []SourcePlan{parent, independent}, true) if err != nil || got.state != "ready" || got.plan.Pull.Number != 4 { t.Fatalf("unrelated ready candidate not available: %+v %v", got, err) diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 615631610..99a82039a 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -805,8 +805,16 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri } return e.finishPreparation(a, state, reason) } - admitted, err := e.Admit(ctx, o.ProjectID, a.ID, a.Revision, prepared.Anchor, prepared.Intent) + admitted, err := e.admit(ctx, o.ProjectID, a.ID, a.Revision, prepared.Anchor, prepared.Intent, true) if err != nil { + var preparedRefusal *preparedCLIAdmissionRefusal + if errors.As(err, &preparedRefusal) { + var schedulingHistory *schedulingHistoryUnavailable + if isStoredUnavailable(err, storedPolicyHistory) || errors.As(err, &schedulingHistory) { + continue + } + return persistenceFailure() + } if ctx.Err() != nil { return e.finishPreparation(a, "cancelled", "supervisor_stopping") } @@ -842,6 +850,9 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri } return persistenceFailure() } + if admitted.State == "held" { + continue + } a = admitted var progressMu sync.Mutex recordTrigger := func(progressCtx context.Context, externalID string) error { From f959d763176d3bab8a01213631310c6e47874b0d Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 17:37:56 +1300 Subject: [PATCH 13/34] Fix Hosted review evidence and CLI preparation recovery Retain exact scheduling evidence and selected-run identity. Settle unused CLI preparation only with the original proof, preserving normal authorization checks. --- internal/backup/inventory.go | 3 +- internal/backup/review_selection_test.go | 50 +++++++++ internal/reviewexec/attempts.go | 79 ++++++++++++-- internal/reviewexec/cli_preflight.go | 13 ++- .../live_cli_preparation_settlement_test.go | 100 ++++++++++++++++++ internal/reviewexec/run_selection.go | 3 + internal/reviewexec/run_selection_origin.go | 4 +- internal/reviewexec/run_selection_snapshot.go | 25 +++++ internal/reviewexec/run_selection_worker.go | 19 +++- internal/reviewexec/scheduling_automatic.go | 4 + internal/reviewexec/scheduling_snapshot.go | 31 +++--- internal/reviewexec/supervisor.go | 80 ++++++++++++++ internal/reviewruntime/cli_driver.go | 65 ++++++++---- 13 files changed, 426 insertions(+), 50 deletions(-) create mode 100644 internal/reviewexec/live_cli_preparation_settlement_test.go diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index d1f066f77..3fe764f7c 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -1097,7 +1097,8 @@ func validateSnapshotContent(ctx context.Context, dataDir string, m Manifest, al // An optional predecessor domain may be absent only before it has // produced durable controls. Dropping tables cannot erase that history. var used bool - if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events WHERE event_type IN ('review.scheduling_updated','review.pull_scheduling_updated'))`).Scan(&used); err != nil { + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events WHERE event_type IN ('review.scheduling_updated','review.pull_scheduling_updated') + OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT) IN ('review.scheduling_updated','review.pull_scheduling_updated')))`).Scan(&used); err != nil { return unavailable() } if used { diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index 57f95014c..a30505f53 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -398,3 +398,53 @@ func TestSelectionQuarantineInventoryRejectsDanglingEmptyV2Marker(t *testing.T) SET state='held',reason='linked_selection_quarantined',revision=2`) assertCurrentSummaryInventoryRefused(t, bundle, false) } + +// A physical v1 database can already contain selected runs and front frames. +func TestSelectionV1UpgradePreservesSelectedRunAndFront(t *testing.T) { + f, id := selectionInventoryFixture(t, "selected") + db := f.store.DB() + var count int + if err := db.QueryRow(`SELECT count(*) FROM review_selections WHERE id=? AND state='selected'`, id).Scan(&count); err != nil || count != 1 { + t.Fatal("missing selected predecessor", count, err) + } + if err := db.QueryRow(`SELECT count(*) FROM review_front_frames`).Scan(&count); err != nil || count < 1 { + t.Fatal("missing predecessor front frame", count, err) + } + if _, err := db.Exec(`DROP TABLE review_selection_quarantine; + UPDATE metadata SET value='1' WHERE key='schema:review_selection'`); err != nil { + t.Fatal(err) + } + before := backupRows(t, db) + const schema = `SELECT type,name,tbl_name,sql FROM sqlite_schema + WHERE name NOT LIKE 'sqlite_%' AND tbl_name<>'review_selection_quarantine' ORDER BY type,name` + physical := restoreRows(t, db, schema) + const metadata = `SELECT key,value FROM metadata WHERE key<>'schema:review_selection' ORDER BY key` + parentMetadata := restoreRows(t, db, metadata) + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal(err) + } + if _, err := Restore(t.Context(), bundle.Path, filepath.Join(t.TempDir(), "inactive-selection-v1")); err != nil { + t.Fatal(err) + } + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + after := backupRows(t, db) + for table, hash := range before { + if table != "metadata" && after[table] != hash { + t.Fatal("upgrade changed retained rows", table) + } + } + if len(after) != len(before)+1 || !reflect.DeepEqual(physical, restoreRows(t, db, schema)) || + !reflect.DeepEqual(parentMetadata, restoreRows(t, db, metadata)) { + t.Fatal("upgrade changed unrelated schema or metadata") + } + if err := db.QueryRow(`SELECT count(*) FROM review_selection_quarantine`).Scan(&count); err != nil || count != 0 { + t.Fatal("upgrade manufactured quarantine records", count, err) + } + var version string + if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:review_selection'`).Scan(&version); err != nil || version != "2" { + t.Fatal("wrong upgraded selection version", version, err) + } +} diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 2c3dac33b..3b057c561 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -386,13 +386,7 @@ func (e *Engine) settleCLIAdmissionRefusal(ctx context.Context, tx *sql.Tx, o Op if record.Observation.Remaining <= 0 || record.Observation.Anchor != anchor { return Attempt{}, refusal } - var unused bool - err = tx.QueryRowContext(ctx, `SELECT - EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=? AND provider=? AND account=? AND repository_id=? AND pull_number=? AND action_class='cli') - AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=1 AND state='preparing' AND reason='preparing' AND external_id='') - AND NOT EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision<>1) - AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, - a.ID, a.Provider, a.Account, anchor.RepositoryID, o.PullNumber, a.ID, a.ID, a.ID).Scan(&unused) + unused, err := untouchedCLIReservation(ctx, tx, o, a, anchor.RepositoryID) if err != nil { return Attempt{}, err } @@ -402,6 +396,77 @@ func (e *Engine) settleCLIAdmissionRefusal(ctx context.Context, tx *sql.Tx, o Op return e.advanceAttempt(ctx, tx, o, a, "held", "automatic_scheduling_unavailable", "") } +func untouchedCLIReservation(ctx context.Context, tx *sql.Tx, o Operation, a Attempt, repositoryID int64) (bool, error) { + var unused bool + err := tx.QueryRowContext(ctx, `SELECT + EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=? AND provider=? AND account=? AND repository_id=? AND pull_number=? AND action_class='cli') + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=1 AND state='preparing' AND reason='preparing' AND external_id='') + AND NOT EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision<>1) + AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, + a.ID, a.Provider, a.Account, repositoryID, o.PullNumber, a.ID, a.ID, a.ID).Scan(&unused) + return unused, err +} + +// The driver has finished its exclusively owned preparation before usage. +// Release only the original revision-1 reservation and retain the queued request. +func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operation, captured Attempt) error { + err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + a, err := readAttempt(ctx, tx, captured.ProjectID, captured.ID) + if err != nil { + return err + } + o, err := readOperation(ctx, tx, captured.ProjectID, captured.OperationID) + if err != nil { + return err + } + if a != captured || a.State != "preparing" || a.Revision != 1 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" || + !sameCLIClaim(original, o, a, original.Revision+1) || !sameCLIWait(original.Wait, o.Wait) { + return conflict() + } + var repositoryID int64 + if err := tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, o.ProjectID).Scan(&repositoryID); err != nil { + return err + } + unused, err := untouchedCLIReservation(ctx, tx, o, a, repositoryID) + if err != nil { + return err + } + _, err = readCLIAllowanceRecord(ctx, tx, o, a) + if !unused || err == nil { + return conflict() + } + if !errors.Is(err, errAllowanceObservationAbsent) { + return err + } + _, err = e.advanceAttempt(ctx, tx, o, a, "held", "automatic_scheduling_unavailable", "") + return err + }) + if err == nil { + e.notifyOperation(captured.OperationID) + } + return err +} + +func sameCLIClaim(original, current Operation, a Attempt, expectedRevision int64) bool { + return original.Channel == "cli" && current.Channel == "cli" && + original.ProjectID == current.ProjectID && current.ProjectID == a.ProjectID && + original.ID == current.ID && current.ID == a.OperationID && + original.ActorID == current.ActorID && original.WorkerID == current.WorkerID && + original.ConfigurationRevision == current.ConfigurationRevision && original.PolicyRevision == current.PolicyRevision && + original.CapabilityFingerprint == current.CapabilityFingerprint && original.PullNumber == current.PullNumber && + original.HeadSHA == current.HeadSHA && original.AllowOutOfOrder == current.AllowOutOfOrder && + original.OverrideFileLimit == current.OverrideFileLimit && current.State == "preparing" && current.AttemptID == a.ID && + current.Revision == expectedRevision +} + +func sameCLIWait(original, current *OperationWait) bool { + if original == nil || current == nil { + return original == current + } + return original.BaselineAttemptID == current.BaselineAttemptID && + original.RetryNotBefore == current.RetryNotBefore && original.Paused == current.Paused +} + func safeText(s string, max int) bool { if len(s) > max || !utf8.ValidString(s) { return false diff --git a/internal/reviewexec/cli_preflight.go b/internal/reviewexec/cli_preflight.go index c6479b2b4..0be62cf74 100644 --- a/internal/reviewexec/cli_preflight.go +++ b/internal/reviewexec/cli_preflight.go @@ -183,6 +183,10 @@ func WithCLIExhaustionRecovery(source CLIExhaustionRecoverySource) EngineOption // Current authority is deliberately not consulted: the subsequent retry still // requires normal admission. The journal write and cooldown are one transaction. func (e *Engine) ReplayCLIExhaustion(ctx context.Context, r CLIExhaustionRecovery) error { + return e.replayCLIExhaustion(ctx, r, false) +} + +func (e *Engine) replayCLIExhaustion(ctx context.Context, r CLIExhaustionRecovery, live bool) error { if err := ValidateCLIExhaustionRecovery(r); err != nil { return err } @@ -238,11 +242,14 @@ func (e *Engine) ReplayCLIExhaustion(ctx context.Context, r CLIExhaustionRecover if a.State != "preparing" || a.Revision != 1 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" || o.State != "preparing" || o.AttemptID != a.ID || o.Revision != original.Revision { return invalid() } - var reserved int - if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM review_execution_reservations WHERE attempt_id=? AND provider=? AND account=? AND repository_id=? AND pull_number=? AND action_class='cli'`, a.ID, a.Provider, a.Account, repository, o.PullNumber).Scan(&reserved); err != nil { + if live && (!sameCLIClaim(original, o, a, original.Revision) || !sameCLIWait(original.Wait, o.Wait)) { + return invalid() + } + unused, err := untouchedCLIReservation(ctx, tx, o, a, repository) + if err != nil { return err } - if reserved != 1 { + if !unused { return invalid() } if !exists { 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..caef5db5b --- /dev/null +++ b/internal/reviewexec/live_cli_preparation_settlement_test.go @@ -0,0 +1,100 @@ +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 != found { + 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) + } + }) + } +} diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 41b71b264..d8df8d69c 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -533,6 +533,9 @@ func quarantineNativeSelection(ctx context.Context, tx *sql.Tx, project, id any, if err != nil { return false, err } + if native, ok := originalRevision.(int64); originalLink == nil && ok && native < 1 { + return false, &unprovedSelectionCustodyError{runUnavailable()} + } linkGuard := ` AND operation_id IS NULL` holdReason := "local_read_unavailable" args := []any{project, id, state, revision} diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index a2a0d8490..9695d9064 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -202,8 +202,8 @@ func selectionPredatesAutomation(ctx context.Context, tx *sql.Tx, r Run, accepte if err := rows.Scan(&sequence, &revision, &body); err != nil { return false, err } - var control schedulingEvent - if revision != expected || !body.Valid || strictjson.Decode([]byte(body.String), &control) != nil || control.Hosted == nil { + control, _, _, valid := readSchedulingEventPayload(body, expected) + if revision != expected || !valid { return false, nil } enabled := control.Hosted diff --git a/internal/reviewexec/run_selection_snapshot.go b/internal/reviewexec/run_selection_snapshot.go index df01c2a83..ae823eaa8 100644 --- a/internal/reviewexec/run_selection_snapshot.go +++ b/internal/reviewexec/run_selection_snapshot.go @@ -235,6 +235,31 @@ func validateSelectionQuarantine(ctx context.Context, q EvidenceQuery) error { if inconsistent { return runUnavailable() } + // Older snapshots can lack the optional scheduling domain. If retained + // attribution exists, validate it here as well as in the scheduling scan. + var automaticTable bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema + WHERE type='table' AND name='review_automatic_selections')`).Scan(&automaticTable); err != nil { + return err + } + if automaticTable { + if err := q.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM review_selection_quarantine d + JOIN review_selections s ON s.id=d.selection_id + JOIN review_automatic_selections a ON a.selection_id=d.selection_id + LEFT JOIN review_operations o ON o.id=d.original_operation_id + WHERE a.project_id<>d.project_id OR a.actor_id<>s.actor_id OR a.worker_id<>s.worker_id + OR typeof(a.pull_number)<>'integer' OR a.pull_number<0 OR a.pull_number>2147483647 + OR (a.pull_number=0 AND a.pull_basis_sha256<>'') + OR (a.pull_number<>0 AND (o.id IS NULL OR o.project_id<>d.project_id OR o.pull_number<>a.pull_number)) + )`).Scan(&inconsistent); err != nil { + return err + } + if inconsistent { + return runUnavailable() + } + } + rows, err := q.QueryContext(ctx, `SELECT CASE WHEN typeof(d.original_operation_id)='text' AND length(CAST(d.original_operation_id AS BLOB))<=128 THEN d.original_operation_id END, d.original_state,d.observed_revision,s.state,s.reason,s.operation_id,s.revision,s.project_id,d.project_id FROM review_selection_quarantine d LEFT JOIN review_selections s ON s.id=d.selection_id`) diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 23f98b9de..acdeffa51 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -218,12 +218,17 @@ func retryRunSelectionRead(ctx context.Context, local func() error) error { // The source hold must not settle PR-local revisions that were not read. func readAutomaticPullSchedulingRevisions(ctx context.Context, tx *sql.Tx, project string, pulls []int64, tolerateUnreadable bool) ([]int64, error) { + return readAutomaticPullSchedulingRevisionsBound(ctx, tx, project, pulls, tolerateUnreadable, nil) +} + +func readAutomaticPullSchedulingRevisionsBound(ctx context.Context, tx *sql.Tx, project string, pulls []int64, tolerateUnreadable bool, expected []int64) ([]int64, error) { revisions := make([]int64, 0, len(pulls)) - for _, pull := range pulls { + for i, pull := range pulls { current, err := readPullScheduling(ctx, tx, project, pull) if err != nil { var local *pullSchedulingStateError - if !tolerateUnreadable || !errors.As(err, &local) { + if !tolerateUnreadable || !errors.As(err, &local) || local.project != project || local.pull != pull || + (expected != nil && (i >= len(expected) || expected[i] != -1)) { return nil, err } revisions = append(revisions, -1) @@ -731,7 +736,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat var revisions []int64 // A newly unreadable row must roll back the provisional // front frame; it is not equivalent to an ordinary revision change. - revisions, resultErr = readAutomaticPullSchedulingRevisions(ctx, tx, r.ProjectID, boundPrefix, false) + revisions, resultErr = readAutomaticPullSchedulingRevisionsBound(ctx, tx, r.ProjectID, boundPrefix, true, choice.automaticPullScheduling) settle = resultErr == nil && slices.Equal(revisions, choice.automaticPullScheduling) } } @@ -788,8 +793,12 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat if err = publishSourcePlans(ctx, tx, core.Scope{ProjectID: current.ProjectID, PrincipalID: current.ActorID, WorkerID: current.WorkerID}, repo, metadataPins, choice.prefix); err != nil { return err } - if err = writeFrontFrame(ctx, tx, current, repo, c, choice); err != nil { - return err + zeroPrefixHold := choice.state == "held" && choice.automaticQueueLimit != nil && + *choice.automaticQueueLimit == 0 && len(c.Queue) > 0 && len(choice.prefix) == 0 + if !zeroPrefixHold { + if err = writeFrontFrame(ctx, tx, current, repo, c, choice); err != nil { + return err + } } if choice.state == "held" { if choice.sourceReason == "" && !globalFrontHold(choice.reason) && choice.reason != "expected_pr_mismatch" && choice.reason != "source_prefix_incomplete" && choice.reason != "local_read_unavailable" { diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 5eeae8f20..572da95a1 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -588,6 +588,10 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) } r, err := readRun(ctx, tx, project, id) if err != nil { + var bindingState *operationSelectionBindingStateError + if errors.As(err, &bindingState) { + continue + } return 0, err } if err = e.requireAutomaticRun(ctx, tx, r); err != nil { diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index c35141904..d1cca4ffa 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -204,18 +204,25 @@ func scanSchedulingSnapshot(row interface{ Scan(...any) error }, destinations .. // retained event instead proves a pause or cannot be read as that identity. // Rank every event before projecting its native revision; never fall back to // an older valid resume when the winning revision cannot be trusted. -const orphanPullSchedulingSQL = `WITH orphan AS ( - SELECT e.project_id,e.resource_id,e.revision,e.sequence, - CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END AS payload, - ROW_NUMBER() OVER (PARTITION BY e.project_id,e.resource_id ORDER BY e.revision DESC,e.sequence DESC) AS newest, - COUNT(*) OVER (PARTITION BY e.project_id,e.resource_id,e.revision) AS matches, - MAX(CASE WHEN typeof(e.revision)<>'integer' OR e.revision<1 THEN 1 ELSE 0 END) - OVER (PARTITION BY e.project_id,e.resource_id) AS bad_revision - FROM events e LEFT JOIN review_pull_scheduling s - ON s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) - AND CAST(s.pull_number AS TEXT)=e.resource_id - WHERE e.event_type='review.pull_scheduling_updated' AND s.pull_number IS NULL - )` +const orphanPullSchedulingSQL = `WITH orphan_history AS ( + SELECT e.project_id,e.resource_id,e.revision,e.sequence,e.event_type, + CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END AS payload, + LAG(e.revision) OVER (PARTITION BY e.project_id,e.resource_id ORDER BY e.sequence) AS previous_revision + FROM events e LEFT JOIN review_pull_scheduling s + ON s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) + AND CAST(s.pull_number AS TEXT)=e.resource_id + WHERE (e.event_type='review.pull_scheduling_updated' + OR (typeof(e.event_type)='blob' AND CAST(e.event_type AS TEXT)='review.pull_scheduling_updated')) + AND s.pull_number IS NULL + ), orphan AS ( + SELECT project_id,resource_id,revision,sequence,payload, + ROW_NUMBER() OVER (PARTITION BY project_id,resource_id ORDER BY revision DESC,sequence DESC) AS newest, + COUNT(*) OVER (PARTITION BY project_id,resource_id,revision) AS matches, + MAX(CASE WHEN typeof(event_type)<>'text' OR typeof(revision)<>'integer' OR revision<1 + OR (previous_revision IS NOT NULL AND revision<=previous_revision) THEN 1 ELSE 0 END) + OVER (PARTITION BY project_id,resource_id) AS bad_revision + FROM orphan_history + )` const latestOrphanPullResumesSQL = ` FROM orphan o JOIN events e ON e.sequence=o.sequence diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 99a82039a..15bda4473 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -23,6 +23,76 @@ type Preparation struct { Intent string } +// CLIPreparationHandoff transfers a finished, exclusively owned CLI +// preparation to the supervisor for guarded local settlement. +type CLIPreparationHandoff struct { + recovery *PreparationRecoveryError + source CLIExhaustionRecoverySource + release func() +} + +func (h *CLIPreparationHandoff) Error() string { return h.recovery.Error() } +func (h *CLIPreparationHandoff) Unwrap() error { return h.recovery } + +// CLIRefusalBeforeUsage marks only classified project-local history refusals. +// The concrete driver calls it after acquiring ownership and before quota usage. +func CLIRefusalBeforeUsage(err error, release func()) error { + if isLinkedSelectionCustodyHeld(err) { + return &PreparationRecoveryError{Err: err} + } + if CLIProjectHistoryRefused(err) { + return &CLIPreparationHandoff{recovery: &PreparationRecoveryError{Err: err}, release: release} + } + return err +} + +// CLIProjectHistoryRefused reports typed project-local history failures. +func CLIProjectHistoryRefused(err error) bool { + return automaticProjectRefused(err) || isStoredUnavailable(err, storedRoundHistory) || isStoredUnavailable(err, storedPolicyHistory) +} + +// CLIExhaustionAuthorityRefused identifies explicit authority/history refusal +// of a normal zero-observation write. Only capture-only recovery may follow. +func CLIExhaustionAuthorityRefused(err error) bool { + if isLinkedSelectionCustodyHeld(err) { + return false + } + var failure *core.Error + return CLIProjectHistoryRefused(err) || errors.As(err, &failure) && + (failure.Code == "forbidden" || failure.Code == "pull_scheduling_paused" || failure.Code == "automation_authorization_changed") +} + +// RetainedCLIExhaustionHandoff requires an already-saved private observation. +// A failure to save the capture cannot use this path. +func RetainedCLIExhaustionHandoff(err error, source CLIExhaustionRecoverySource, release func()) error { + return &CLIPreparationHandoff{recovery: &PreparationRecoveryError{Err: err}, source: source, release: release} +} + +func (e *Engine) settleCLIPreparationHandoff(ctx context.Context, original Operation, a Attempt, h *CLIPreparationHandoff) error { + local, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + defer cancel() + if h.source == nil { + return retryRunSelectionLocal(local, func() error { + return e.settleUnusedCLIPreparation(local, original, a) + }) + } + record, found, err := h.source.LoadCLIExhaustion(local, a.ID) + if err != nil { + return err + } + if !found || a != record.Attempt || !sameCLIClaim(original, record.Operation, a, original.Revision+1) || + !sameCLIWait(original.Wait, record.Operation.Wait) { + return conflict() + } + err = retryRunSelectionLocal(local, func() error { + return e.replayCLIExhaustion(local, record, true) + }) + if err == nil { + e.notifyOperation(a.OperationID) + } + return err +} + // Result describes external execution only. Completed is not policy credit or // merge readiness. The adapter must retain its bounded capture/evidence before // returning a proven terminal result; unresolved outcomes return uncertain. @@ -764,6 +834,16 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri prepared, err := driver.Prepare(prepareCtx, o, c, a) cancel() if err != nil { + var handoff *CLIPreparationHandoff + if o.Channel == "cli" && errors.As(err, &handoff) { + if err := e.settleCLIPreparationHandoff(ctx, o, a, handoff); err != nil { + return &PreparationRecoveryError{Err: err} + } + if handoff.release != nil { + handoff.release() + } + continue + } var recoverable *PreparationRecoveryError if errors.As(err, &recoverable) { return err diff --git a/internal/reviewruntime/cli_driver.go b/internal/reviewruntime/cli_driver.go index 732c45589..a548669cb 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -31,6 +31,7 @@ type CLIDriver struct { review func(context.Context, reviewworkspace.Workspace) (reviewprocess.Capture, error) mu sync.Mutex prepared map[string]*cliPrepared + settling map[string]struct{} } func (*CLIDriver) String() string { return "CLIDriver{private}" } @@ -78,7 +79,7 @@ func NewCLIDriver(store *core.Store, engine *reviewexec.Engine, capability Opera if err != nil { return nil, err } - return &CLIDriver{store: store, engine: engine, capability: capability, manager: manager, captures: captures, exhaustions: exhaustions, reader: reader, fetch: manager.Fetch, verify: manager.Verify, usage: runner.Usage, review: runner.Review, prepared: map[string]*cliPrepared{}}, nil + return &CLIDriver{store: store, engine: engine, capability: capability, manager: manager, captures: captures, exhaustions: exhaustions, reader: reader, fetch: manager.Fetch, verify: manager.Verify, usage: runner.Usage, review: runner.Review, prepared: map[string]*cliPrepared{}, settling: map[string]struct{}{}}, nil } // A successful preflight can be held by admission before Dispatch. Expire only @@ -93,33 +94,50 @@ func (d *CLIDriver) purgePrepared() { } func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, configuration reviewexec.Configuration, attempt reviewexec.Attempt) (preparation reviewexec.Preparation, failure error) { - d.mu.Lock() - d.purgePrepared() - d.mu.Unlock() - current, err := d.engine.ExecutionContext(ctx, operation.ProjectID, operation.ID) - if err != nil { - return preparation, err - } - if !sameOperation(operation, current.Operation) || !reflect.DeepEqual(configuration, current.Configuration) || configuration.CapabilityID != d.capability.ID || operation.Channel != "cli" || attempt.Provider != "coderabbit" || attempt.Account != d.capability.Account || attempt.ProjectID != operation.ProjectID || attempt.OperationID != operation.ID || attempt.ID != current.Operation.AttemptID || attempt.State != "preparing" || attempt.Revision != 1 { - return preparation, reviewHold("execution_binding_changed") + if configuration.CapabilityID != d.capability.ID || operation.Channel != "cli" || attempt.Provider != "coderabbit" || attempt.Account != d.capability.Account || attempt.ProjectID != operation.ProjectID || attempt.OperationID != operation.ID || attempt.State != "preparing" || attempt.Revision != 1 { + return preparation, &reviewexec.PreparationRecoveryError{Err: reviewHold("execution_binding_changed")} } d.mu.Lock() d.purgePrepared() _, exists := d.prepared[attempt.ID] - if !exists { + _, settling := d.settling[attempt.ID] + if !exists && !settling { d.prepared[attempt.ID] = nil } d.mu.Unlock() - if exists { - return preparation, reviewHold("preparation_duplicate") + if exists || settling { + return preparation, &reviewexec.PreparationRecoveryError{Err: reviewHold("preparation_duplicate")} + } + releaseSettlement := func() { + d.mu.Lock() + delete(d.settling, attempt.ID) + d.mu.Unlock() } + usageStarted := false defer func() { - if failure != nil { - d.mu.Lock() - delete(d.prepared, attempt.ID) - d.mu.Unlock() + if failure == nil { + return + } + if !usageStarted { + failure = reviewexec.CLIRefusalBeforeUsage(failure, releaseSettlement) + } + d.mu.Lock() + defer d.mu.Unlock() + delete(d.prepared, attempt.ID) + var handoff *reviewexec.CLIPreparationHandoff + if errors.As(failure, &handoff) { + // Keep out duplicate Prepare calls while the supervisor records + // the bounded local handoff. This entry is never a dispatch permit. + d.settling[attempt.ID] = struct{}{} } }() + current, err := d.engine.ExecutionContext(ctx, operation.ProjectID, operation.ID) + if err != nil { + return preparation, err + } + if !sameOperation(operation, current.Operation) || !reflect.DeepEqual(configuration, current.Configuration) || attempt.ID != current.Operation.AttemptID { + return preparation, &reviewexec.PreparationRecoveryError{Err: reviewHold("execution_binding_changed")} + } reads := newSourceReads(d.reader) plan, _, err := resolveReviewSource(ctx, d.engine, reads, current.RepositoryID, current.Configuration, current.Operation) if err != nil { @@ -140,6 +158,7 @@ func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, if baseline != nil && !sameHostedRetryComparison(*baseline, anchor) { return preparation, reviewHold("source_changed") } + usageStarted = true usage, err := d.usage(ctx, workspace, plan.Repository.FullName, d.capability.Organization) if err != nil { var failure *reviewprocess.Error @@ -164,11 +183,14 @@ func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, if err := retryAllowanceRetention(ctx, waitPreparation, func() error { return core.NormalizeStorageError(d.engine.RecordCLIExhaustion(ctx, operation.ProjectID, attempt.ID, attempt.Revision, observation)) }); err != nil { - if retryableHostedRetention(err) || ctx.Err() != nil { + if retryableHostedRetention(err) || ctx.Err() != nil || reviewexec.CLIExhaustionAuthorityRefused(err) { + return preparation, reviewexec.RetainedCLIExhaustionHandoff(err, d.exhaustions, releaseSettlement) + } + var refusal *core.Error + if reviewexec.CLIProjectHistoryRefused(err) || errors.As(err, &refusal) && refusal.Code == "review_conflict" { return preparation, &reviewexec.PreparationRecoveryError{Err: err} } - var held *core.Error - if errors.As(err, &held) && held.Code == "review_held" { + if errors.As(err, &refusal) && refusal.Code == "review_held" { return preparation, err } return preparation, reviewHold("allowance_unavailable") @@ -181,6 +203,9 @@ func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, return preparation, err } if err := publishPreparedAttempt(ctx, d.engine, operation.ProjectID, attempt.ID, plan); err != nil { + if reviewexec.CLIProjectHistoryRefused(err) { + return preparation, &reviewexec.PreparationRecoveryError{Err: err} + } return preparation, err } d.mu.Lock() From f81266724fad0a38b9f955ce7cbd4276e4c8d432 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 20:32:43 +1300 Subject: [PATCH 14/34] Harden review scheduling and retained attempt recovery Validate scheduling history before restore, preserve bounded source reads and isolate typed local refusals. Transfer recovery responsibility only for attempts with retained evidence. Keep ambiguous or unsupported historical cases held for separate qualification. --- internal/backup/restore.go | 11 +++- internal/backup/scheduling_test.go | 39 +++++++++++ internal/core/auth.go | 2 +- internal/core/project_automation.go | 2 +- internal/core/types.go | 1 + .../adoption_holds_integration_test.go | 14 ++-- internal/reviewexec/attempts.go | 9 +++ internal/reviewexec/hosted_priority.go | 6 ++ .../live_cli_preparation_settlement_test.go | 52 ++++++++++++++- internal/reviewexec/run_selection.go | 51 ++++++++++++++- internal/reviewexec/run_selection_origin.go | 3 + internal/reviewexec/run_selection_schema.go | 14 ++++ internal/reviewexec/run_selection_worker.go | 64 +++++++++++++++---- internal/reviewexec/scheduling_automatic.go | 15 ++++- .../scheduling_selected_basis_guard_test.go | 3 + internal/reviewexec/scheduling_snapshot.go | 36 +++++++---- .../scheduling_source_hold_basis_test.go | 14 +++- .../reviewexec/scheduling_source_retry.go | 14 ++-- internal/reviewexec/supervisor.go | 18 ++++-- 19 files changed, 319 insertions(+), 49 deletions(-) diff --git a/internal/backup/restore.go b/internal/backup/restore.go index cd8549ef2..2f83ba97f 100644 --- a/internal/backup/restore.go +++ b/internal/backup/restore.go @@ -250,9 +250,9 @@ func restoreIdentity(ctx context.Context, dir string, m Manifest, id, key string } var failure *core.Error if errors.As(err, &failure) && failure.Code == "storage_unavailable" { - return invalid() + return historicalResumeRestoreError{public: invalid(), cause: err} } - return unavailable() + return historicalResumeRestoreError{public: unavailable(), cause: err} } if err = tx.Commit(); err != nil { return unavailable() @@ -328,3 +328,10 @@ func restoreParent(path string) error { path = next } } + +// historicalResumeRestoreError preserves the operational cause without exposing +// storage internals through the public restore message. +type historicalResumeRestoreError struct{ public, cause error } + +func (e historicalResumeRestoreError) Error() string { return e.public.Error() } +func (e historicalResumeRestoreError) Unwrap() []error { return []error{e.public, e.cause} } diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index 379d53d25..e64a35ee2 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -119,3 +119,42 @@ func TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { t.Fatal("restore mutated source controls or validated bundle") } } + +func TestSchedulingInventoryAcceptsLegacyHostedAndItsActualMigration(t *testing.T) { + f := newRestoreFixture(t) + db := f.store.DB() + if _, err := db.Exec(`DROP TABLE review_scheduling; + UPDATE metadata SET value='1' WHERE key='schema:review_scheduling';` + reviewexec.SchedulingSchemaSQL()[0]); err != nil { + t.Fatal(err) + } + if 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`, f.principal).Scan(&credential); err != nil { + return err + } + at := time.Now().UTC().Format(time.RFC3339Nano) + if _, err := tx.ExecContext(ctx, `INSERT INTO review_scheduling + (project_id,revision,automatic_hosted,actor_id,worker_id,credential_id,updated_at) + VALUES(?,1,1,?,?,?,?)`, f.project, f.principal, f.worker, credential, at); err != nil { + return err + } + _, err := tx.ExecContext(ctx, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) + VALUES(?,'review.scheduling_updated',?,1,?,'{"automatic_hosted":true}',?)`, f.project, f.project, f.principal, at) + return err + }); err != nil { + t.Fatal(err) + } + if _, err := Inspect(t.Context(), restoreBundle(t, f).Path); err != nil { + t.Fatal("legacy Hosted scheduling inventory refused", err) + } + if err := reviewexec.EnsureSchedulingSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + var hosted, cli bool + if err := db.QueryRow(`SELECT automatic_hosted,automatic_cli FROM review_scheduling WHERE project_id=?`, f.project).Scan(&hosted, &cli); err != nil || !hosted || cli { + t.Fatal("migration changed legacy scheduling authority", hosted, cli, err) + } + if _, err := Inspect(t.Context(), restoreBundle(t, f).Path); err != nil { + t.Fatal("actual migrated scheduling inventory refused", err) + } +} diff --git a/internal/core/auth.go b/internal/core/auth.go index 5ee5e4051..6a8188a0b 100644 --- a/internal/core/auth.go +++ b/internal/core/auth.go @@ -132,7 +132,7 @@ func (s *Store) authorize(ctx context.Context, q querier, scope Scope, permissio var principal, credential string var admin int err := q.QueryRowContext(ctx, "SELECT id,principal_id,is_admin FROM credentials WHERE token_sha256=? AND revoked=0", scope.tokenHash).Scan(&credential, &principal, &admin) - if errors.Is(err, sql.ErrNoRows) || (err == nil && principal != scope.PrincipalID) { + if errors.Is(err, sql.ErrNoRows) || (err == nil && (principal != scope.PrincipalID || scope.automationCredential != "" && credential != scope.automationCredential)) { return Fail("unauthorized", "A valid bearer credential is required.", 401) } if err != nil { diff --git a/internal/core/project_automation.go b/internal/core/project_automation.go index 72eeea12a..ba8f3f6f7 100644 --- a/internal/core/project_automation.go +++ b/internal/core/project_automation.go @@ -41,7 +41,7 @@ func (s *Store) ProjectAutomationScope(ctx context.Context, tx *sql.Tx, project, if err != nil { return Scope{}, storageError(err) } - scope := Scope{ProjectID: project, PrincipalID: principal, WorkerID: worker, tokenHash: hash, instanceID: s.instanceID, admin: true, activeWorkerRequired: true} + scope := Scope{ProjectID: project, PrincipalID: principal, WorkerID: worker, tokenHash: hash, automationCredential: credential, instanceID: s.instanceID, admin: true, activeWorkerRequired: true} if err := s.authorize(ctx, tx, scope, "admin"); err != nil { return Scope{}, err } diff --git a/internal/core/types.go b/internal/core/types.go index 570e48f63..6a621a133 100644 --- a/internal/core/types.go +++ b/internal/core/types.go @@ -15,6 +15,7 @@ type Scope struct { ProjectID string WorkerID string tokenHash string + automationCredential string instanceID string admin bool activeWorkerRequired bool diff --git a/internal/reviewexec/adoption_holds_integration_test.go b/internal/reviewexec/adoption_holds_integration_test.go index e6c787f3d..df8dca9c7 100644 --- a/internal/reviewexec/adoption_holds_integration_test.go +++ b/internal/reviewexec/adoption_holds_integration_test.go @@ -662,8 +662,11 @@ func TestAdoptionHoldsIntegrationSupervisorSettlesRepositoryChangeDuringPrepare( t.Fatal(err) } f.configure(t, otherAttemptProject, "test-capability", 0, false) - f.enqueue(t, otherAttemptProject, "other-after-corrupt-source", channel, 2, 1) - other := &controlledDriver{dispatch: func(_ context.Context, _ Operation, _ Attempt, _ func(context.Context, string) error) (Result, error) { + healthy := f.enqueue(t, otherAttemptProject, "other-after-corrupt-source", channel, 2, 1) + other := &controlledDriver{dispatch: func(_ context.Context, operation Operation, _ Attempt, _ func(context.Context, string) error) (Result, error) { + if operation.ID != healthy.ID || operation.ProjectID != otherAttemptProject { + t.Fatalf("dispatched %s/%s instead of healthy operation %s", operation.ProjectID, operation.ID, healthy.ID) + } return Result{State: "failed", Reason: "synthetic_no_post"}, nil }} if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": other}); err != nil || other.calls.Load() != 1 { @@ -689,8 +692,11 @@ func TestAdoptionHoldsIntegrationSupervisorSettlesRepositoryChangeDuringPrepare( // A repository identity change is local to its retained source. The // next supervisor pass must remain able to serve another project. f.configure(t, otherAttemptProject, "test-capability", 0, false) - f.enqueue(t, otherAttemptProject, "other-project-after-source-change", channel, 2, 1) - other := &controlledDriver{dispatch: func(_ context.Context, _ Operation, _ Attempt, _ func(context.Context, string) error) (Result, error) { + healthy := f.enqueue(t, otherAttemptProject, "other-project-after-source-change", channel, 2, 1) + other := &controlledDriver{dispatch: func(_ context.Context, operation Operation, _ Attempt, _ func(context.Context, string) error) (Result, error) { + if operation.ID != healthy.ID || operation.ProjectID != otherAttemptProject { + t.Fatalf("dispatched %s/%s instead of healthy operation %s", operation.ProjectID, operation.ID, healthy.ID) + } return Result{State: "failed", Reason: "synthetic_no_post"}, nil }} if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": other}); err != nil || other.calls.Load() != 1 { diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 3b057c561..513fcf52a 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -173,6 +173,15 @@ func (e *Engine) startAttempt(ctx context.Context, project, id string, draftRead if o.Reason == cliDraftWait && o.Revision != draftReadyRevision { return nil } + if o.Channel == "cli" { + var dirty bool + if err := tx.QueryRowContext(ctx, "SELECT "+comparisonDirtyExists, project, o.PullNumber, o.Channel).Scan(&dirty); err != nil { + return err + } + if dirty { + return &automaticProjectStateError{adjudicationStorageError()} + } + } if err = tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, project).Scan(&repositoryID); err != nil { return err } diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 4ace0da9a..5edd9bbec 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -125,6 +125,12 @@ func (e *Engine) hostedPriorityBinding(ctx context.Context, tx *sql.Tx, o Operat if err == nil { return true, nil } + // A proved mismatch removes only this candidate's priority. Its own + // admission remains refused, and operational storage errors still return. + var binding *operationSelectionBindingStateError + if errors.As(err, &binding) { + return false, nil + } var refusal *core.Error if errors.As(err, &refusal) && refusal.Status >= 400 && refusal.Status < 500 { return false, nil diff --git a/internal/reviewexec/live_cli_preparation_settlement_test.go b/internal/reviewexec/live_cli_preparation_settlement_test.go index caef5db5b..1cf1899f1 100644 --- a/internal/reviewexec/live_cli_preparation_settlement_test.go +++ b/internal/reviewexec/live_cli_preparation_settlement_test.go @@ -81,7 +81,7 @@ func TestLiveCLIPreparationReplaysOnlyRetainedExactZero(t *testing.T) { 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 != found { + if d.prepares.Load() != 1 || d.calls.Load() != 0 || !released { t.Fatal("local replay performed provider work") } if !found { @@ -98,3 +98,53 @@ func TestLiveCLIPreparationReplaysOnlyRetainedExactZero(t *testing.T) { }) } } + +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) + } +} diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index d8df8d69c..df13d7ff6 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -241,6 +241,14 @@ func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configurati WHERE p.project_id=o.project_id AND p.pull_number=o.pull_number AND typeof(p.paused)='integer' AND p.paused=1)))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { return c, 0, "", err } + if !busy && r.Channel == "hosted" { + // The SQL predicate is only a shortlist. A queued operation + // may yield its turn only on a fully validated pull pause. + busy, err = unprovedQueuedHostedPause(ctx, tx, r.ProjectID) + if err != nil { + return c, 0, "", err + } + } if busy { var automatic bool if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id=?)`, r.ProjectID, r.ID).Scan(&automatic); err != nil { @@ -502,6 +510,46 @@ func AbandonReviewRuns(ctx context.Context, tx *sql.Tx, at time.Time) (int64, er return int64(len(selected)), nil } +func unprovedQueuedHostedPause(ctx context.Context, tx *sql.Tx, project string) (bool, error) { + rows, err := tx.QueryContext(ctx, `SELECT DISTINCT pull_number FROM review_operations + WHERE project_id=? AND channel='hosted' AND state='queued' ORDER BY pull_number LIMIT 101`, project) + if err != nil { + return false, err + } + defer rows.Close() + var pulls []int64 + for rows.Next() { + var pull int64 + if err := rows.Scan(&pull); err != nil { + return false, err + } + pulls = append(pulls, pull) + } + if err := rows.Err(); err != nil { + return false, err + } + if len(pulls) > 100 { + return true, nil + } + if err := rows.Close(); err != nil { + return false, err + } + for _, pull := range pulls { + s, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + var invalid *pullSchedulingStateError + if errors.As(err, &invalid) { + return true, nil + } + return false, err + } + if !s.Paused { + return true, nil + } + } + return false, nil +} + // A corrupt revision is an opaque retained value, never an arithmetic operand. const selectionClaimRevision = `CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision ELSE 0 END` @@ -533,9 +581,6 @@ func quarantineNativeSelection(ctx context.Context, tx *sql.Tx, project, id any, if err != nil { return false, err } - if native, ok := originalRevision.(int64); originalLink == nil && ok && native < 1 { - return false, &unprovedSelectionCustodyError{runUnavailable()} - } linkGuard := ` AND operation_id IS NULL` holdReason := "local_read_unavailable" args := []any{project, id, state, revision} diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index 9695d9064..547b79909 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -97,6 +97,9 @@ func automaticSelectionBinding(ctx context.Context, tx *sql.Tx, r Run) (automati return automaticSelectionAttribution{}, err } hasAttribution := err == nil + if hasAttribution && event.sequence == 0 { + return automaticSelectionAttribution{}, schedulingUnavailable() + } switch event.Origin { case selectionOriginAutomatic: if !hasAttribution || r.ExpectedPullNumber != 0 { diff --git a/internal/reviewexec/run_selection_schema.go b/internal/reviewexec/run_selection_schema.go index 0a7ac861d..d5862c42f 100644 --- a/internal/reviewexec/run_selection_schema.go +++ b/internal/reviewexec/run_selection_schema.go @@ -61,6 +61,20 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro LEFT JOIN review_operations o ON o.id=d.original_operation_id WHERE d.project_id=? AND d.original_operation_id=?`, project, operation).Scan(&proved) if errors.Is(err, sql.ErrNoRows) { + // A detached marker without its diagnostic has lost the only + // exact child link. Do not infer ordinary authority for any + // child in that project from the absent link. + var unproved bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS ( + SELECT 1 FROM review_selections s + WHERE s.project_id=? AND s.reason='linked_selection_quarantined' + AND NOT EXISTS (SELECT 1 FROM review_selection_quarantine d + WHERE d.project_id=s.project_id AND d.selection_id=s.id))`, project).Scan(&unproved); err != nil { + return err + } + if unproved { + return automaticProjectStateFailure(linkedSelectionCustodyHeld, "A review operation is held for selection custody recovery in this project.", 403) + } return nil } if err != nil { diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index acdeffa51..12df85d4b 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -164,14 +164,16 @@ func (r *runReads) ParentPull(ctx context.Context, repository, branch string) (r } type runChoice struct { - state, reason string - sourceReason string - prefix []SourcePlan - number int64 - head string - automaticQueueLimit *int - automaticBasisRevision int64 - automaticPullScheduling []int64 + state, reason string + sourceReason string + prefix []SourcePlan + number int64 + head string + automaticQueueLimit *int + claimAutomaticQueueLimit *int + automaticBasisRevision int64 + automaticPullScheduling []int64 + automaticGrantRevisions []int64 } // retryRunSelectionLocal retains completed source reads while only retrying @@ -239,6 +241,28 @@ func readAutomaticPullSchedulingRevisionsBound(ctx context.Context, tx *sql.Tx, return revisions, nil } +// Read the exact round grants included in a source-held choice's pull basis. +func readAutomaticGrantRevisions(ctx context.Context, tx *sql.Tx, project, channel string, pulls []int64) ([]int64, error) { + revisions := make([]int64, 0, len(pulls)) + for _, pull := range pulls { + var native any + err := tx.QueryRowContext(ctx, `SELECT grant_revision FROM review_round_controls WHERE project_id=? AND channel=? AND pull_number=?`, project, channel, pull).Scan(&native) + if errors.Is(err, sql.ErrNoRows) { + revisions = append(revisions, -1) + continue + } + if err != nil { + return nil, err + } + revision, ok := native.(int64) + if !ok || revision < 0 { + return nil, schedulingUnavailable() + } + revisions = append(revisions, revision) + } + return revisions, nil +} + func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader) (runChoice, error) { return e.chooseRunWithSourceBudget(ctx, r, repo, c, reader, e.runSourceBudget) } @@ -247,11 +271,12 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 var automaticQueueLimit *int var basisRevision int64 - var pullScheduling []int64 + var pullScheduling, grantRevisions []int64 defer func() { result.automaticQueueLimit = automaticQueueLimit result.automaticBasisRevision = basisRevision result.automaticPullScheduling = pullScheduling + result.automaticGrantRevisions = grantRevisions }() // Bound source work before metadata lookahead. Local suppression still // rechecks the live prefix at admission if queued work changes afterward. @@ -259,7 +284,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 err := retryRunSelectionRead(ctx, func() error { // An expired snapshot must not shorten a later retry's input. limit, automatic, basisRevision = len(c.Queue), false, 0 - pullScheduling = nil + pullScheduling, grantRevisions = nil, nil return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { attribution, err := automaticSelectionBinding(ctx, tx, r) if err != nil { @@ -281,6 +306,10 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 return err } pullScheduling, err = readAutomaticPullSchedulingRevisions(ctx, tx, r.ProjectID, c.Queue[:limit], true) + if err != nil { + return err + } + grantRevisions, err = readAutomaticGrantRevisions(ctx, tx, r.ProjectID, r.Channel, c.Queue[:limit]) return err }) }) @@ -537,6 +566,7 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target var selected *Run var configuration Configuration var metadataPins map[int64]reviews.SourceMetadataPin + var claimAutomaticQueueLimit *int var repo int64 var changed string var project, id string @@ -617,6 +647,7 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target if err != nil { return err } + claimAutomaticQueueLimit = &limit queue = queue[:limit] } metadataPins, err = reviews.PinSourceMetadata(ctx, tx, r.ProjectID, queue) @@ -654,6 +685,7 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target if readErr != nil { return true, readErr } + choice.claimAutomaticQueueLimit = claimAutomaticQueueLimit worked, err := e.finishRunChoice(ctx, r, repo, metadataPins, choice) if automaticProjectRefused(err) { return e.holdRunLocalRefusal(ctx, r) @@ -716,6 +748,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return err } bindingValidated := false + zeroPrefixHold := false var boundPrefix []int64 defer func() { if resultErr == nil && bindingValidated { @@ -725,7 +758,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat resultErr = err return } - settle := state != "queued" && reason != "selection_changed" + settle := !zeroPrefixHold && state != "queued" && reason != "selection_changed" if settle && choice.automaticQueueLimit != nil && choice.automaticBasisRevision != 0 { var currentBasis int64 currentBasis, resultErr = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) @@ -738,6 +771,11 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat // front frame; it is not equivalent to an ordinary revision change. revisions, resultErr = readAutomaticPullSchedulingRevisionsBound(ctx, tx, r.ProjectID, boundPrefix, true, choice.automaticPullScheduling) settle = resultErr == nil && slices.Equal(revisions, choice.automaticPullScheduling) + if settle && choice.sourceReason != "" { + grants, err := readAutomaticGrantRevisions(ctx, tx, r.ProjectID, r.Channel, boundPrefix) + resultErr = err + settle = err == nil && slices.Equal(grants, choice.automaticGrantRevisions) + } } } if settle { @@ -785,7 +823,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat if err != nil { return err } - if limit != *choice.automaticQueueLimit { + if limit != *choice.automaticQueueLimit || (choice.claimAutomaticQueueLimit != nil && limit > *choice.claimAutomaticQueueLimit) { return updateRun(ctx, tx, current, "held", "selection_changed", "") } boundPrefix = c.Queue[:limit] @@ -793,7 +831,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat if err = publishSourcePlans(ctx, tx, core.Scope{ProjectID: current.ProjectID, PrincipalID: current.ActorID, WorkerID: current.WorkerID}, repo, metadataPins, choice.prefix); err != nil { return err } - zeroPrefixHold := choice.state == "held" && choice.automaticQueueLimit != nil && + zeroPrefixHold = choice.state == "held" && choice.automaticQueueLimit != nil && *choice.automaticQueueLimit == 0 && len(c.Queue) > 0 && len(choice.prefix) == 0 if !zeroPrefixHold { if err = writeFrontFrame(ctx, tx, current, repo, c, choice); err != nil { diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 572da95a1..b8a3087f9 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -546,7 +546,7 @@ func (e *Engine) automaticHostedQueuedPrefixChannel(ctx context.Context, tx *sql if err != nil { return 0, err } - rows, err := tx.QueryContext(ctx, `SELECT q.key,s.id,s.project_id,o.id,EXISTS(SELECT 1 FROM review_selection_quarantine d WHERE d.project_id=o.project_id AND d.original_operation_id=o.id) FROM review_operations o + rows, err := tx.QueryContext(ctx, `SELECT q.key,o.pull_number,s.id,s.project_id,o.id,EXISTS(SELECT 1 FROM review_selection_quarantine d WHERE d.project_id=o.project_id AND d.original_operation_id=o.id) FROM review_operations o JOIN json_each(?) q ON q.value=o.pull_number LEFT JOIN review_selections s ON s.operation_id=o.id WHERE o.project_id=? AND o.channel=? AND o.state='queued' @@ -563,10 +563,11 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) return 0, schedulingUnavailable() } var position int + var pull int64 var selection, selectionProject any var operation string var custodyPresent bool - if err := rows.Scan(&position, &selection, &selectionProject, &operation, &custodyPresent); err != nil { + if err := rows.Scan(&position, &pull, &selection, &selectionProject, &operation, &custodyPresent); err != nil { return 0, err } if custodyPresent { @@ -578,8 +579,16 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) } return 0, runUnavailable() } - // A direct operation has no parent selection and keeps its position. + // A readable direct operation keeps its fence. A locally + // unavailable control cannot prevent independent pulls being assessed. if selection == nil { + if _, err := readPullScheduling(ctx, tx, project, pull); err != nil { + var local *pullSchedulingStateError + if errors.As(err, &local) && local.project == project && local.pull == pull { + continue + } + return 0, err + } return position, nil } id, validID := selection.(string) diff --git a/internal/reviewexec/scheduling_selected_basis_guard_test.go b/internal/reviewexec/scheduling_selected_basis_guard_test.go index 71106f6f1..0e631d51c 100644 --- a/internal/reviewexec/scheduling_selected_basis_guard_test.go +++ b/internal/reviewexec/scheduling_selected_basis_guard_test.go @@ -75,6 +75,9 @@ func TestSelectedChildDoesNotSettleRearmedLaneBasis(t *testing.T) { } else if !hash.MatchString(settled) || pull != 2 || !hash.MatchString(pullBasis) { t.Fatalf("stable selection did not settle its own lane/pull basis") } + if err := f.e.readAdmission(t.Context(), ValidateSchedulingSnapshot); err != nil { + t.Fatal("valid linked child could not be retained in a scheduling snapshot", err) + } }) } } diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index d1cca4ffa..8ac695cf6 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -67,8 +67,9 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { var ahead bool err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events e LEFT JOIN review_scheduling s ON s.project_id=e.project_id - WHERE e.event_type='review.scheduling_updated' - AND (typeof(e.resource_id)<>'text' OR e.resource_id<>e.project_id OR s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) + WHERE (e.event_type='review.scheduling_updated' OR + (typeof(e.event_type)='blob' AND CAST(e.event_type AS TEXT)='review.scheduling_updated')) + AND (typeof(e.event_type)<>'text' OR typeof(e.resource_id)<>'text' OR e.resource_id<>e.project_id OR s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) if err != nil { return err } @@ -131,9 +132,11 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections a LEFT JOIN review_selections s ON s.id=a.selection_id`+custodyJoin+` LEFT JOIN review_scheduling c ON c.project_id=a.project_id LEFT JOIN review_operations o ON o.id=`+linked+` WHERE s.id IS NULL OR s.project_id<>a.project_id OR s.channel NOT IN(`+channels+`) OR s.actor_id<>a.actor_id OR s.worker_id<>a.worker_id OR c.project_id IS NULL - OR a.scheduling_revision>c.revision OR (a.pull_number=0 AND (a.pull_basis_sha256<>'' OR s.state='selected')) - OR (a.pull_number<>0 AND ((s.state<>'selected' AND NOT `+held+`) OR o.id IS NULL OR o.pull_number<>a.pull_number - OR o.project_id<>a.project_id OR o.channel<>s.channel OR o.actor_id<>a.actor_id OR o.worker_id<>a.worker_id)))`).Scan(&bad) + OR a.scheduling_revision>c.revision + OR (a.pull_number=0 AND (a.pull_basis_sha256<>'' OR (s.state='selected' AND a.settled_basis_sha256<>''))) + OR ((s.state='selected' OR a.pull_number<>0) AND (o.id IS NULL + OR o.project_id<>a.project_id OR o.channel<>s.channel OR o.actor_id<>a.actor_id OR o.worker_id<>a.worker_id)) + OR (a.pull_number<>0 AND ((s.state<>'selected' AND NOT `+held+`) OR o.pull_number<>a.pull_number)))`).Scan(&bad) if err != nil { return err } @@ -317,13 +320,24 @@ func validPullSchedulingPayload(payload sql.NullString, pull int64, paused bool) // outer side of this join, SQLite can seek the control's composite primary key // rather than reading the same project's event history once for each control. // Ordered qualifying matches keep duplicate detection constant-space. -const pullSchedulingSnapshotEventsSQL = `SELECT s.project_id,s.pull_number,s.revision,s.paused,s.actor_id, - e.revision,e.actor_id,CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END +const pullSchedulingSnapshotEventsSQL = `WITH represented_history AS ( + SELECT s.project_id,s.pull_number,s.revision AS control_revision,s.paused,s.actor_id AS control_actor, + e.revision,e.actor_id,e.event_type, + CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END AS payload, + LAG(e.revision) OVER (PARTITION BY s.project_id,s.pull_number ORDER BY e.sequence) AS prev_revision FROM events e CROSS JOIN review_pull_scheduling s - WHERE e.event_type='review.pull_scheduling_updated' AND s.project_id=e.project_id - AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id - AND (typeof(e.revision)<>'integer' OR e.revision<1 OR e.revision>=s.revision) - ORDER BY s.project_id,s.pull_number` + WHERE (e.event_type='review.pull_scheduling_updated' OR + (typeof(e.event_type)='blob' AND CAST(e.event_type AS TEXT)='review.pull_scheduling_updated')) + AND s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id + ), relevant AS ( + SELECT *, (typeof(event_type)<>'text' OR typeof(revision)<>'integer' OR revision<1 OR + (prev_revision IS NOT NULL AND revision<=prev_revision)) AS invalid_event + FROM represented_history + ) + SELECT project_id,pull_number,control_revision,paused,control_actor, + CASE WHEN NOT invalid_event THEN revision END,actor_id,payload + FROM relevant WHERE invalid_event OR revision>=control_revision + ORDER BY project_id,pull_number` func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) error { if controls == 0 { diff --git a/internal/reviewexec/scheduling_source_hold_basis_test.go b/internal/reviewexec/scheduling_source_hold_basis_test.go index 4bf3f2a64..79c217379 100644 --- a/internal/reviewexec/scheduling_source_hold_basis_test.go +++ b/internal/reviewexec/scheduling_source_hold_basis_test.go @@ -42,6 +42,18 @@ func TestAutomaticSourceHoldRetainsOnlyItsBoundPullSchedulingBasis(t *testing.T) if err != nil { t.Fatal(err) } + var expected string + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + config, _, err := readConfiguration(ctx, tx, scope.ProjectID) + if err != nil { + return err + } + expected, _, err = f.e.automaticPlanningBasisChannel(ctx, tx, scope.ProjectID, config, receipt.ID, "hosted") + return err + }) + if err != nil || !hash.MatchString(expected) { + t.Fatalf("compute fixture's bound basis: %q (%v)", expected, err) + } reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { if edited { schedulingPause(t, f, 2, 0, true) @@ -58,7 +70,7 @@ func TestAutomaticSourceHoldRetainsOnlyItsBoundPullSchedulingBasis(t *testing.T) if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, receipt.ID).Scan(&settled); err != nil { t.Fatal(err) } - if edited && settled != "" || !edited && !hash.MatchString(settled) { + if edited && settled != "" || !edited && settled != expected { t.Fatalf("unexpected settled basis after lawful source hold: edited=%v basis=%q", edited, settled) } }) diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index 9a72394d2..ac3bcfc3f 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -78,18 +78,22 @@ func verifiedInitialAutomaticSourceAcceptance(ctx context.Context, q EvidenceQue // revision, non-increasing event sequence or malformed payload keeps that fence. Aggregate in SQL rather than // copying an unbounded event history into each admission snapshot. func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, error) { + acceptance, err := readSelectionRequestedEvent(ctx, tx, r) + if err != nil || acceptance.sequence == 0 { + return false, err + } var count, distinct, first, last, invalid int64 - err := tx.QueryRowContext(ctx, `WITH transitions AS ( + err = tx.QueryRowContext(ctx, `WITH transitions AS ( SELECT revision,sequence,payload_json,lag(sequence) OVER (ORDER BY revision,sequence) AS previous_sequence FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' AND revision BETWEEN 2 AND ? ) SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( - CASE WHEN typeof(revision)='integer' AND typeof(sequence)='integer' AND sequence>0 AND + CASE WHEN typeof(revision)='integer' AND typeof(sequence)='integer' AND sequence>? AND (previous_sequence IS NULL OR sequence>previous_sequence) AND json_valid(payload_json) THEN CASE WHEN json_extract(payload_json,'$.state')=CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END AND json_extract(payload_json,'$.reason')='' AND (revision<>? OR json_extract(payload_json,'$.state')=?) THEN 0 ELSE 1 END ELSE 1 END),0) - FROM transitions`, r.ProjectID, r.ID, r.Revision, r.Revision, r.State).Scan(&count, &distinct, &first, &last, &invalid) + FROM transitions`, r.ProjectID, r.ID, r.Revision, acceptance.sequence, r.Revision, r.State).Scan(&count, &distinct, &first, &last, &invalid) if err != nil { return false, err } @@ -115,10 +119,10 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er var superseded bool err = tx.QueryRowContext(ctx, `SELECT EXISTS( SELECT 1 FROM review_selections s WHERE s.project_id=? AND s.channel=? AND s.id<>? - AND (julianday(s.created_at) IS NULL OR julianday(s.created_at)>=julianday(?)) + AND (typeof(s.created_at)<>'text' OR length(s.created_at)<19 OR substr(s.created_at,11,1) NOT IN ('T',' ') OR julianday(s.created_at) IS NULL OR julianday(s.created_at)>=julianday(?)) AND NOT EXISTS(SELECT 1 FROM events e WHERE e.project_id=s.project_id AND e.resource_id=s.id AND e.event_type='review.selection_requested' AND e.revision=1) ) OR EXISTS( - SELECT 1 FROM review_operations o WHERE o.project_id=? AND o.channel=? AND (julianday(o.created_at) IS NULL OR julianday(o.created_at)>=julianday(?)) + SELECT 1 FROM review_operations o WHERE o.project_id=? AND o.channel=? AND (typeof(o.created_at)<>'text' OR length(o.created_at)<19 OR substr(o.created_at,11,1) NOT IN ('T',' ') OR julianday(o.created_at) IS NULL OR julianday(o.created_at)>=julianday(?)) AND NOT EXISTS(SELECT 1 FROM events e WHERE e.project_id=o.project_id AND e.resource_id=o.id AND e.event_type='review.requested' AND e.revision=1) ) OR EXISTS( SELECT 1 FROM events e JOIN review_selections s ON s.project_id=e.project_id AND s.id=e.resource_id diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 15bda4473..d10da9f2c 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -836,12 +836,16 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if err != nil { var handoff *CLIPreparationHandoff if o.Channel == "cli" && errors.As(err, &handoff) { - if err := e.settleCLIPreparationHandoff(ctx, o, a, handoff); err != nil { - return &PreparationRecoveryError{Err: err} - } - if handoff.release != nil { + settleErr := e.settleCLIPreparationHandoff(ctx, o, a, handoff) + // A saved capture remains available to the next recovery owner. + // Release only the process-local marker, not the journal or its + // reservation. A failed volatile no-usage handoff is different. + if handoff.release != nil && (settleErr == nil || handoff.source != nil) { handoff.release() } + if settleErr != nil { + return &PreparationRecoveryError{Err: settleErr} + } continue } var recoverable *PreparationRecoveryError @@ -849,6 +853,12 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri return err } if ctx.Err() == nil { + if o.Channel == "hosted" && isSourceObligationProjectStateError(err) { + if err := e.finishPreparation(a, "held", "automatic_scheduling_unavailable"); err != nil { + return err + } + continue + } if handled, settleErr := e.classifyUnavailablePreparation(ctx, o, a, err); handled { if settleErr != nil { return settleErr From b87b252bda0c2a543f836ebb7215373c38225048 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 16:32:56 +1300 Subject: [PATCH 15/34] Require durable review authorization and enqueue proof Check pending CLI continuity against its explicit authorization basis and require a matching public enqueue receipt before classifying an unlinked operation as direct. Reconcile only an exact already-committed preparation settlement readback. --- docs/review-scheduling.md | 2 + internal/reviewexec/attempts.go | 40 ++++++++++++++- .../live_cli_preparation_settlement_test.go | 18 +++++++ .../operation_direct_receipt_test.go | 49 ++++++++++++++++++ internal/reviewexec/run_selection_origin.go | 50 ++++++++++++++++--- .../scheduling_authorization_continuity.go | 18 ++++++- internal/reviewexec/scheduling_automatic.go | 21 ++++++++ .../scheduling_boundary_compatibility_test.go | 34 +++++++++++++ 8 files changed, 221 insertions(+), 11 deletions(-) create mode 100644 internal/reviewexec/operation_direct_receipt_test.go diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index 108d5c918..6e70613bb 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -12,6 +12,8 @@ Project scheduling is read-only. `GET /api/v1/projects/{project_id}/reviews/sche ## Accepted work +A pending operation without a retained selection link is eligible as a direct request only when the exact public enqueue receipt matches its original project, principal, worker, configuration revision, channel, pull request, and head. The same rule applies when counting a direct request as a queue fence. If neither a valid selection link nor a direct receipt establishes origin, the controller does not admit the operation as direct. This requirement does not change settled history or recovery of already-admitted work. + Explicit selection uses the existing durable queue. Automatic origin in retained state requires matching attribution, an authorized original worker and complete relevant scheduling history. Queued or selecting work retains its original authorizer. An already selected operation can retain that original authorizer through a manager change when both authorizers remain valid and the intervening history proves continuous enablement of its channel. Missing or conflicting attribution and ambiguous legacy selections hold for operator investigation. Legacy explicit origin can be proven by an exact retained mutation receipt, a caller-supplied PR pin or complete history from before automatic scheduling for that channel. Current queued diagnostics identify an earlier accepted Hosted request before the later request's independent cooldown. The bounded local read uses compatible active queue and quota bindings. A paused, cancelled or invalid earlier request releases that turn. CLI shared-account quota diagnostics retain the original deadline while the accepted account and current configuration still agree. diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 513fcf52a..a9316db4f 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -419,6 +419,7 @@ func untouchedCLIReservation(ctx context.Context, tx *sql.Tx, o Operation, a Att // The driver has finished its exclusively owned preparation before usage. // Release only the original revision-1 reservation and retain the queued request. func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operation, captured Attempt) error { + var proposed Attempt err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { a, err := readAttempt(ctx, tx, captured.ProjectID, captured.ID) if err != nil { @@ -447,15 +448,52 @@ func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operat if !errors.Is(err, errAllowanceObservationAbsent) { return err } - _, err = e.advanceAttempt(ctx, tx, o, a, "held", "automatic_scheduling_unavailable", "") + proposed, err = e.advanceAttempt(ctx, tx, o, a, "held", "automatic_scheduling_unavailable", "") return err }) + // A nonzero proposal means the entire transaction callback completed; + // only then can this caller have lost the acknowledgement of a commit. + if err != nil && proposed.ID != "" && e.unusedCLISettlementCommitted(ctx, original, captured, proposed) { + err = nil + } if err == nil { e.notifyOperation(captured.OperationID) } return err } +// Reconcile only the exact guarded transaction whose acknowledgement was +// uncertain. The observations come from one snapshot and cannot grant work. +func (e *Engine) unusedCLISettlementCommitted(ctx context.Context, original Operation, captured, proposed Attempt) bool { + tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return false + } + defer tx.Rollback() + a, err := readAttempt(ctx, tx, captured.ProjectID, captured.ID) + if err != nil || a != proposed || a.State != "held" || a.Revision != captured.Revision+1 { + return false + } + o, err := readOperation(ctx, tx, captured.ProjectID, captured.OperationID) + if err != nil || o.State != "queued" || o.AttemptID != "" || o.Reason != "automatic_scheduling_unavailable" || !sameCLIWait(original.Wait, o.Wait) { + return false + } + // Compare the same immutable claim fields as the settlement writer. + claimed := o + claimed.State, claimed.AttemptID = "preparing", captured.ID + if !sameCLIClaim(original, claimed, captured, original.Revision+2) { + return false + } + var exact bool + err = tx.QueryRowContext(ctx, `SELECT + EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=? AND state='held' AND reason='automatic_scheduling_unavailable' AND external_id='') + AND NOT EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=?) + AND NOT EXISTS(SELECT 1 FROM review_cli_preflight WHERE attempt_id=?) + AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, + a.ID, a.Revision, a.ID, a.ID, a.ID).Scan(&exact) + return err == nil && exact +} + func sameCLIClaim(original, current Operation, a Attempt, expectedRevision int64) bool { return original.Channel == "cli" && current.Channel == "cli" && original.ProjectID == current.ProjectID && current.ProjectID == a.ProjectID && diff --git a/internal/reviewexec/live_cli_preparation_settlement_test.go b/internal/reviewexec/live_cli_preparation_settlement_test.go index 1cf1899f1..4381f5336 100644 --- a/internal/reviewexec/live_cli_preparation_settlement_test.go +++ b/internal/reviewexec/live_cli_preparation_settlement_test.go @@ -148,3 +148,21 @@ func TestLiveCLIPreparationRetainedHandoffTransfersToSameEngineRecovery(t *testi 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") + } +} diff --git a/internal/reviewexec/operation_direct_receipt_test.go b/internal/reviewexec/operation_direct_receipt_test.go new file mode 100644 index 000000000..2a3be00c4 --- /dev/null +++ b/internal/reviewexec/operation_direct_receipt_test.go @@ -0,0 +1,49 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func TestDirectOperationAdmissionUsesAtomicEnqueueReceipt(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + t.Run(channel, func(t *testing.T) { + f := schedulingFixture(t) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + request := Request{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: channel, HeadSHA: strings.Repeat("a", 40)} + reply, err := f.e.Enqueue(t.Context(), scope, core.NewID("request"), request) + if err != nil { + t.Fatal(err) + } + var receipt Receipt + if err := json.Unmarshal(reply, &receipt); err != nil { + t.Fatal(err) + } + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + o, err := readOperationIdentity(ctx, tx, attemptProject, receipt.ID) + if err != nil { + return err + } + if err := f.e.requireAutomaticOperation(ctx, tx, o); err != nil { + return err + } + config, _, err := readConfiguration(ctx, tx, attemptProject) + if err != nil { + return err + } + prefix, err := f.e.automaticHostedQueuedPrefixChannel(ctx, tx, attemptProject, config, channel) + if err != nil || prefix != 0 { + t.Fatalf("direct fence = %v, %v", prefix, err) + } + return nil + }); err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index 547b79909..c7c59aa14 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -140,16 +140,10 @@ func automaticSelectionBinding(ctx context.Context, tx *sql.Tx, r Run) (automati // Only a positive match proves legacy explicit origin; normal current // authorization is still independently required to admit the retained work. func legacyExplicitSelection(ctx context.Context, q EvidenceQuery, r Run) (bool, error) { - var hasHistory bool - if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='restore_history')`).Scan(&hasHistory); err != nil { + origins, err := operationReceiptOrigins(ctx, q) + if err != nil { return false, err } - origins := `SELECT value FROM metadata WHERE key IN ('instance_id','restore:source_instance_id')` - if hasHistory { - // Startup validates the connected recovery provenance of this table. - origins += ` UNION SELECT instance_id FROM restore_history - UNION SELECT CASE WHEN json_valid(body_json) THEN json_extract(body_json,'$."restore:source_instance_id"') END FROM restore_history` - } fingerprint, err := core.MutationRequestFingerprint(RunRequest{Channel: r.Channel}, r.WorkerID) if err != nil { return false, err @@ -167,6 +161,46 @@ func legacyExplicitSelection(ctx context.Context, q EvidenceQuery, r Run) (bool, return explicit, err } +// Receipt origins include verified backup ancestry, not arbitrary stored instances. +func operationReceiptOrigins(ctx context.Context, q EvidenceQuery) (string, error) { + var hasHistory bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='restore_history')`).Scan(&hasHistory); err != nil { + return "", err + } + origins := `SELECT value FROM metadata WHERE key IN ('instance_id','restore:source_instance_id')` + if hasHistory { + // Startup validates the connected recovery provenance of this table. + origins += ` UNION SELECT instance_id FROM restore_history + UNION SELECT CASE WHEN json_valid(body_json) THEN json_extract(body_json,'$."restore:source_instance_id"') END FROM restore_history` + } + return origins, nil +} + +// Only the public Enqueue mutation writes this exact receipt, in the same +// transaction as the operation. A selection child never writes it. +func hasDirectOperationReceipt(ctx context.Context, q EvidenceQuery, o Operation) (bool, error) { + origins, err := operationReceiptOrigins(ctx, q) + if err != nil { + return false, err + } + fp, err := core.MutationRequestFingerprint(Request{ + ExpectedConfigurationRevision: o.ConfigurationRevision, + PullNumber: o.PullNumber, + Channel: o.Channel, + HeadSHA: o.HeadSHA, + }, o.WorkerID) + if err != nil { + return false, err + } + response := encoded(Receipt{ID: o.ID, State: "queued", Revision: 1}) + var direct bool + err = q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM receipts + WHERE instance_id IN (`+origins+`) AND principal_id=? AND project_id=? AND operation='reviews.request' + AND target='requests' AND fingerprint=? AND response_json=?)`, + o.ActorID, o.ProjectID, fp, response).Scan(&direct) + return direct, err +} + func selectionLocalHoldReason(ctx context.Context, q EvidenceQuery, r Run) (string, error) { event, err := readSelectionRequestedEvent(ctx, q, r) if err != nil && !automaticProjectRefused(err) { diff --git a/internal/reviewexec/scheduling_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go index 41180d551..e89e23d2c 100644 --- a/internal/reviewexec/scheduling_authorization_continuity.go +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -41,6 +41,8 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision } defer rows.Close() expected := revision + selectedChild := r.State == "selected" && r.OperationID != "" + var acceptedCLIBasis int64 for rows.Next() { var retainedRevision any var storedActor any @@ -50,16 +52,28 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision } recorded, validRevision := retainedRevision.(int64) actor, nativeText := storedActor.(string) - selectedChild := r.State == "selected" && r.OperationID != "" if !validRevision || !nativeText || !identifier.MatchString(actor) || recorded != expected || (!selectedChild || recorded == revision) && actor != originalActor || recorded == current.Revision && actor != current.actor { return false, nil } - settings, _, _, valid := readSchedulingEventPayload(payload, recorded) + settings, _, cliBasis, valid := readSchedulingEventPayload(payload, recorded) if !valid { return false, nil } + // A pending CLI selection may survive an unrelated edit only when + // each event carries the same explicit writer-owned lane basis. + // The legacy decoder fallback is not continuity evidence. + if !selectedChild && r.Channel == "cli" { + if len(settings.CLIBasis) == 0 { + return false, nil + } + if recorded == revision { + acceptedCLIBasis = cliBasis + } else if cliBasis != acceptedCLIBasis { + return false, nil + } + } enabled := settings.Hosted if r.Channel == "cli" { enabled = settings.CLI diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index b8a3087f9..c7f95529d 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -100,6 +100,13 @@ func (e *Engine) requireAutomaticOperation(ctx context.Context, tx *sql.Tx, o Op var project, selection any err := tx.QueryRowContext(ctx, `SELECT project_id,id FROM review_selections WHERE operation_id=?`, o.ID).Scan(&project, &selection) if errors.Is(err, sql.ErrNoRows) { + direct, err := hasDirectOperationReceipt(ctx, tx, o) + if err != nil { + return err + } + if !direct { + return &operationSelectionBindingStateError{schedulingUnavailable()} + } return nil } if err != nil { @@ -582,6 +589,20 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) // A readable direct operation keeps its fence. A locally // unavailable control cannot prevent independent pulls being assessed. if selection == nil { + o, err := readOperationIdentity(ctx, tx, project, operation) + if err != nil { + if isRetainedOperationDecodeError(err) { + continue + } + return 0, err + } + direct, err := hasDirectOperationReceipt(ctx, tx, o) + if err != nil { + return 0, err + } + if !direct { + continue + } if _, err := readPullScheduling(ctx, tx, project, pull); err != nil { var local *pullSchedulingStateError if errors.As(err, &local) && local.project == project && local.pull == pull { diff --git a/internal/reviewexec/scheduling_boundary_compatibility_test.go b/internal/reviewexec/scheduling_boundary_compatibility_test.go index ab9f4c625..28f09700d 100644 --- a/internal/reviewexec/scheduling_boundary_compatibility_test.go +++ b/internal/reviewexec/scheduling_boundary_compatibility_test.go @@ -76,3 +76,37 @@ func TestFrontLocalSchedulingHoldPreservesIndependentAndStackedEligibility(t *te t.Fatal(err) } } + +func TestPendingCLISchedulingRequiresExplicitStableBasis(t *testing.T) { + const initial = `{"automatic_hosted":true,"automatic_cli":true,"hosted_basis_revision":1,"cli_basis_revision":1}` + const unrelated = `{"automatic_hosted":false,"automatic_cli":true,"hosted_basis_revision":2,"cli_basis_revision":1}` + const changed = `{"automatic_hosted":false,"automatic_cli":true,"hosted_basis_revision":2,"cli_basis_revision":2}` + const legacy = `{"automatic_hosted":true,"automatic_cli":true}` + for _, tc := range []struct { + name, before, after string + selected, want bool + }{ + {"unrelated-setting", initial, unrelated, false, true}, + {"changed-lane-basis", initial, changed, false, false}, + {"legacy-is-not-continuity-proof", legacy, unrelated, false, false}, + {"selected-child-keeps-its-own-contract", initial, changed, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + if _, 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',?), + ('test-project','test-project','review.scheduling_updated',2,'test-actor',?)`, tc.before, tc.after); err != nil { + t.Fatal(err) + } + current := schedulingRecord{Scheduling: Scheduling{ProjectID: "test-project", Revision: 2, AutomaticCLI: true}, actor: "test-actor"} + r := Run{ProjectID: "test-project", Channel: "cli", State: "selecting"} + if tc.selected { + r.State, r.OperationID = "selected", "retained-child" + } + got, err := automaticChannelContinuous(t.Context(), tx, r, 1, "test-actor", current) + if err != nil || got != tc.want { + t.Fatalf("continuity = %v, %v; want %v, nil", got, err, tc.want) + } + }) + } +} From 4e3c300d5c27289bd61adc1c2711d447de2469b1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 16:48:56 +1300 Subject: [PATCH 16/34] Retry exact CLI settlement after transient contention Preserve the original owner guard across a bounded same-process recovery window without preparing or dispatching again. Check direct enqueue proof against the original accepted revision, and qualify the scheduler's synthetic direct-operation fixtures with their matching receipts. --- docs/review-execution.md | 2 +- internal/reviewexec/attempts_test.go | 1 + internal/reviewexec/cli_draft_wait_test.go | 1 + internal/reviewexec/cli_preflight_test.go | 2 +- internal/reviewexec/hosted_preflight_test.go | 2 +- .../operation_direct_receipt_test.go | 23 +++++++++++ .../owned_cli_settlement_retry_test.go | 40 +++++++++++++++++++ .../retained_configuration_scan_test.go | 1 + internal/reviewexec/run_selection_origin.go | 8 +++- internal/reviewexec/supervisor.go | 25 ++++++++++-- internal/reviewexec/supervisor_test.go | 2 + 11 files changed, 100 insertions(+), 7 deletions(-) create mode 100644 internal/reviewexec/owned_cli_settlement_retry_test.go diff --git a/docs/review-execution.md b/docs/review-execution.md index 3091d65d3..8985ea04a 100644 --- a/docs/review-execution.md +++ b/docs/review-execution.md @@ -96,7 +96,7 @@ Hosted allowance attribution uses the same [current-source actor policy](provide When native projection is enabled, each journal transition updates its browser attempt in the same transaction. Preparing and held are distinct states; held attempts retain their actual stop time. Interrupted active or posting work becomes uncertain without an invented finish time. A missing current PR observation leaves the transition ledger-only; a trusted fresh observation can establish that first row. Publication preserves current PR facts and imported history, and exact replay creates no new snapshot. Initial metadata is a fallback inside the publication transaction: if another observation creates current PR facts after a missing-row read, those current facts take precedence over the prepared fallback. If retained attempt capacity is already full, the request is durably held before creating an attempt or reservation. If a later administrator observation replaces the snapshot, omits the live native attempt and fills its capacity, automatic transitions remain ledger-only; they neither copy snapshot rows nor block execution or restart recovery. Existing native rows still update at capacity. Explicit publication retains its atomic capacity refusal. Other projection failures roll back the journal transition as well. -Attempt settlement retries only the same guarded local journal transition within a finite budget. It reconciles an already committed transition before retrying and never repeats provider dispatch. If the outcome cannot be recorded, the supervisor reports a failure, cancels its other work and retains reservations for inspection and recovery. +Attempt settlement retries only the same guarded local journal transition within a finite budget. It reconciles an already committed transition before retrying and never repeats provider dispatch. For a source-less CLI refusal that the original driver certified before usage, a live supervisor may give the same guarded settlement one additional bounded window after a local timeout or overload. The original ownership marker remains in place, and neither preparation nor dispatch runs again. If the outcome cannot be recorded, the supervisor reports a failure, cancels its other work and retains reservations for inspection and recovery. ## Hosted adapter diff --git a/internal/reviewexec/attempts_test.go b/internal/reviewexec/attempts_test.go index 5b599294e..2d500b858 100644 --- a/internal/reviewexec/attempts_test.go +++ b/internal/reviewexec/attempts_test.go @@ -613,6 +613,7 @@ func TestAttemptExactTargetReservationRejectsDirectQueuedFixture(t *testing.T) { // on another account must still be stopped by StartAttempt's target lock. id := core.NewID("review_operation") admissionSQL(t, f, `INSERT INTO review_operations(id,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision) SELECT ?,project_id,actor_id,worker_id,2,pull_number,channel,head_sha,'queued',1,'','',created_at,updated_at,?,policy_revision FROM review_operations WHERE id=?`, id, f.e.capabilities["other-account"].Fingerprint, first.OperationID) + seedDirectOperationReceipt(t, f, attemptProject, id) before := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_execution_reservations") _, err := f.e.StartAttempt(t.Context(), attemptProject, id) attemptCode(t, err, "review_busy") diff --git a/internal/reviewexec/cli_draft_wait_test.go b/internal/reviewexec/cli_draft_wait_test.go index 6b551a8a1..cec797cf7 100644 --- a/internal/reviewexec/cli_draft_wait_test.go +++ b/internal/reviewexec/cli_draft_wait_test.go @@ -83,6 +83,7 @@ func TestCLIDraftProbePassIsBoundedAndRotatesAfterTimeout(t *testing.T) { seed := f.enqueue(t, attemptProject, "rotating-draft-probes", "cli", 2, 1) for i := range 2 { schedulerQueuedCopy(t, f, seed.ID, fmt.Sprintf("review_operation_rotate%03d", i)) + seedDirectOperationReceipt(t, f, attemptProject, fmt.Sprintf("review_operation_rotate%03d", i)) } admissionSQL(t, f, `UPDATE review_operations SET reason=?`, cliDraftWait) now := time.Now() diff --git a/internal/reviewexec/cli_preflight_test.go b/internal/reviewexec/cli_preflight_test.go index 2d6269fa2..f463e1b79 100644 --- a/internal/reviewexec/cli_preflight_test.go +++ b/internal/reviewexec/cli_preflight_test.go @@ -226,7 +226,7 @@ func TestCLIAllowanceRechecksCurrentAdmissionBeforeFirstRecord(t *testing.T) { }, "forbidden"}, "worker": {func(t *testing.T, f *attemptFixture, a Attempt) { admissionSQL(t, f, `UPDATE review_operations SET worker_id='absent-worker' WHERE id=?`, a.OperationID) - }, "forbidden"}, + }, "storage_unavailable"}, "channel": {func(t *testing.T, f *attemptFixture, a Attempt) { admissionSQL(t, f, `UPDATE review_operations SET channel='hosted' WHERE id=?`, a.OperationID) }, "review_conflict"}, diff --git a/internal/reviewexec/hosted_preflight_test.go b/internal/reviewexec/hosted_preflight_test.go index dad190ef4..d16e89cce 100644 --- a/internal/reviewexec/hosted_preflight_test.go +++ b/internal/reviewexec/hosted_preflight_test.go @@ -196,7 +196,7 @@ func TestHostedAllowanceNewRecordRequiresCurrentEligibilityAndConfirmedQuery(t * }, "review_conflict"}, "worker": {func(t *testing.T, f *attemptFixture, a Attempt, _ HostedAllowanceQuery) { admissionSQL(t, f, `UPDATE review_operations SET worker_id='missing-worker' WHERE id=?`, a.OperationID) - }, "forbidden"}, + }, "storage_unavailable"}, } { t.Run(name, func(t *testing.T) { f, a, q, in := hostedAllowanceFixture(t) diff --git a/internal/reviewexec/operation_direct_receipt_test.go b/internal/reviewexec/operation_direct_receipt_test.go index 2a3be00c4..9a159655d 100644 --- a/internal/reviewexec/operation_direct_receipt_test.go +++ b/internal/reviewexec/operation_direct_receipt_test.go @@ -47,3 +47,26 @@ func TestDirectOperationAdmissionUsesAtomicEnqueueReceipt(t *testing.T) { }) } } + +// These fixtures bypass public queue capacity or uniqueness solely to test +// later scheduler boundaries. Give them the direct receipt real Enqueue rows carry. +func seedDirectOperationReceipt(t *testing.T, f *attemptFixture, project, id string) { + t.Helper() + var o Operation + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + o, err = readOperationIdentity(ctx, tx, project, id) + return err + }); err != nil { + t.Fatal(err) + } + fp, err := core.MutationRequestFingerprint(Request{ + ExpectedConfigurationRevision: o.ConfigurationRevision, PullNumber: o.PullNumber, + Channel: o.Channel, HeadSHA: o.HeadSHA, + }, o.WorkerID) + if err != nil { + t.Fatal(err) + } + admissionSQL(t, f, `INSERT INTO receipts(instance_id,principal_id,project_id,operation,target,key,fingerprint,response_json) + VALUES(?,?,?,'reviews.request','requests',?,?,?)`, f.store.InstanceID(), o.ActorID, project, core.NewID("fixture-key"), fp, encoded(Receipt{ID: id, State: "queued", Revision: 1})) +} 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/retained_configuration_scan_test.go b/internal/reviewexec/retained_configuration_scan_test.go index d2a3c5454..cf4ca21f2 100644 --- a/internal/reviewexec/retained_configuration_scan_test.go +++ b/internal/reviewexec/retained_configuration_scan_test.go @@ -168,6 +168,7 @@ func TestPendingScanDoesNotSkipReturnedBatch(t *testing.T) { seed := f.enqueue(t, attemptProject, "batch-seed", "cli", 2, 1) for i := range 2 { admissionSQL(t, f, `INSERT INTO review_operations (id,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision) SELECT ?,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision FROM review_operations WHERE id=?`, fmt.Sprintf("batch-%03d", i), seed.ID) + seedDirectOperationReceipt(t, f, attemptProject, fmt.Sprintf("batch-%03d", i)) } // Force a full batch with an unreturned successor without relying on // hundreds of SQLite reads fitting within the worker throughput budget. diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index c7c59aa14..b6b2a7136 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -183,8 +183,14 @@ func hasDirectOperationReceipt(ctx context.Context, q EvidenceQuery, o Operation if err != nil { return false, err } + // Negative allowance recording compares against the current configuration + // using a local copy. Origin always uses the immutable accepted revision. + var acceptedRevision int64 + if err := q.QueryRowContext(ctx, `SELECT configuration_revision FROM review_operations WHERE project_id=? AND id=?`, o.ProjectID, o.ID).Scan(operationValue(&acceptedRevision)); err != nil { + return false, err + } fp, err := core.MutationRequestFingerprint(Request{ - ExpectedConfigurationRevision: o.ConfigurationRevision, + ExpectedConfigurationRevision: acceptedRevision, PullNumber: o.PullNumber, Channel: o.Channel, HeadSHA: o.HeadSHA, diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index d10da9f2c..1d2af10ce 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -69,13 +69,13 @@ func RetainedCLIExhaustionHandoff(err error, source CLIExhaustionRecoverySource, } func (e *Engine) settleCLIPreparationHandoff(ctx context.Context, original Operation, a Attempt, h *CLIPreparationHandoff) error { - local, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) - defer cancel() if h.source == nil { - return retryRunSelectionLocal(local, func() error { + return settleOwnedCLIWithinWindows(ctx, func(local context.Context) error { return e.settleUnusedCLIPreparation(local, original, a) }) } + local, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + defer cancel() record, found, err := h.source.LoadCLIExhaustion(local, a.ID) if err != nil { return err @@ -93,6 +93,25 @@ func (e *Engine) settleCLIPreparationHandoff(ctx context.Context, original Opera return err } +// Recovery keeps the original driver ownership marker across both windows. +// Only explicit local contention may enter the recovery window; ownership, +// history and unclassified storage errors do not grant a new attempt. +func settleOwnedCLIWithinWindows(ctx context.Context, settle func(context.Context) error) error { + first, stop := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + err := retryRunSelectionLocal(first, func() error { return settle(first) }) + stop() + if err == nil || ctx.Err() != nil { + return err + } + var refusal *core.Error + if !errors.Is(err, context.DeadlineExceeded) && !(errors.As(err, &refusal) && refusal.Code == "overloaded") { + return err + } + second, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + return retryRunSelectionLocal(second, func() error { return settle(second) }) +} + // Result describes external execution only. Completed is not policy credit or // merge readiness. The adapter must retain its bounded capture/evidence before // returning a proven terminal result; unresolved outcomes return uncertain. diff --git a/internal/reviewexec/supervisor_test.go b/internal/reviewexec/supervisor_test.go index 390856c41..85728d9e3 100644 --- a/internal/reviewexec/supervisor_test.go +++ b/internal/reviewexec/supervisor_test.go @@ -93,6 +93,8 @@ func TestSupervisorPendingUsesRetainedAccountAndStableTarget(t *testing.T) { if _, err := f.store.DB().Exec(`UPDATE review_operations SET configuration_revision=2,capability_fingerprint=? WHERE id IN ('reserved-target-other-account','free-target-other-account')`, f.e.capabilities["other-account"].Fingerprint); err != nil { t.Fatal(err) } + seedDirectOperationReceipt(t, f, attemptProject, "reserved-target-other-account") + seedDirectOperationReceipt(t, f, attemptProject, "free-target-other-account") free := Receipt{ID: "free-target-other-account"} hosted := f.enqueue(t, attemptProject, "independent-channel", "hosted", 2, 2) if _, err := f.store.DB().Exec(`UPDATE projects SET repository='renamed/repository' WHERE id=?`, attemptProject); err != nil { From 814f13bb75dbc6712633bc4ca108fbd5449b1e0c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 17:01:48 +1300 Subject: [PATCH 17/34] Settle proven unused CLI work after a prewrite refusal Recognize only a typed allowance refusal before a write. Retire the exact privately held native permit before handing off the original attempt to its guarded settlement. Preserve uncertain outcomes. --- docs/review-execution.md | 2 +- internal/reviewexec/attempts.go | 2 +- internal/reviewexec/cli_preflight.go | 27 +++++++++++++++++++++++ internal/reviewexec/cli_preflight_test.go | 18 +++++++++++++++ internal/reviewprocess/process.go | 12 ++++++++++ internal/reviewprocess/process_test.go | 13 +++++++++++ internal/reviewruntime/cli_driver.go | 7 ++++-- 7 files changed, 77 insertions(+), 4 deletions(-) diff --git a/docs/review-execution.md b/docs/review-execution.md index 8985ea04a..34f17b2b8 100644 --- a/docs/review-execution.md +++ b/docs/review-execution.md @@ -96,7 +96,7 @@ Hosted allowance attribution uses the same [current-source actor policy](provide When native projection is enabled, each journal transition updates its browser attempt in the same transaction. Preparing and held are distinct states; held attempts retain their actual stop time. Interrupted active or posting work becomes uncertain without an invented finish time. A missing current PR observation leaves the transition ledger-only; a trusted fresh observation can establish that first row. Publication preserves current PR facts and imported history, and exact replay creates no new snapshot. Initial metadata is a fallback inside the publication transaction: if another observation creates current PR facts after a missing-row read, those current facts take precedence over the prepared fallback. If retained attempt capacity is already full, the request is durably held before creating an attempt or reservation. If a later administrator observation replaces the snapshot, omits the live native attempt and fills its capacity, automatic transitions remain ledger-only; they neither copy snapshot rows nor block execution or restart recovery. Existing native rows still update at capacity. Explicit publication retains its atomic capacity refusal. Other projection failures roll back the journal transition as well. -Attempt settlement retries only the same guarded local journal transition within a finite budget. It reconciles an already committed transition before retrying and never repeats provider dispatch. For a source-less CLI refusal that the original driver certified before usage, a live supervisor may give the same guarded settlement one additional bounded window after a local timeout or overload. The original ownership marker remains in place, and neither preparation nor dispatch runs again. If the outcome cannot be recorded, the supervisor reports a failure, cancels its other work and retains reservations for inspection and recovery. +Attempt settlement retries only the same guarded local journal transition within a finite budget. It reconciles an already committed transition before retrying and never repeats provider dispatch. For a source-less CLI refusal that the original driver certified before usage, a live supervisor may give the same guarded settlement one additional bounded window after a local timeout or overload. The original ownership marker remains in place, and neither preparation nor dispatch runs again. A completed positive allowance query can use the same guarded settlement only when the allowance writer explicitly refused before its first write and the native driver retires the exact unconsumed review permit. Unknown outcomes are not proof of non-use. If the outcome cannot be recorded, the supervisor reports a failure, cancels its other work and retains reservations for inspection and recovery. ## Hosted adapter diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index a9316db4f..a94b21866 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -416,7 +416,7 @@ func untouchedCLIReservation(ctx context.Context, tx *sql.Tx, o Operation, a Att return unused, err } -// The driver has finished its exclusively owned preparation before usage. +// The driver has finished its exclusively owned preparation without authorizing review. // Release only the original revision-1 reservation and retain the queued request. func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operation, captured Attempt) error { var proposed Attempt diff --git a/internal/reviewexec/cli_preflight.go b/internal/reviewexec/cli_preflight.go index 0be62cf74..6de948c46 100644 --- a/internal/reviewexec/cli_preflight.go +++ b/internal/reviewexec/cli_preflight.go @@ -74,6 +74,30 @@ func (e *Engine) RecordCLIExhaustion(ctx context.Context, project, attemptID str return e.recordCLIAllowance(ctx, project, attemptID, expectedRevision, input) } +// Positive allowance is not a review. This marker certifies only that the +// exact preparing attempt was refused before any allowance write. +type unrecordedPositiveCLIAllowance struct{ error } + +func (e *unrecordedPositiveCLIAllowance) Unwrap() error { return e.error } + +func prewritePositiveCLIRefusal(err error) error { + var binding *operationSelectionBindingStateError + if err == nil || isLinkedSelectionCustodyHeld(err) || errors.As(err, &binding) || !CLIProjectHistoryRefused(err) { + return err + } + return &unrecordedPositiveCLIAllowance{err} +} + +// CLIPreflightUnusedHandoff requires concrete driver proof that its exact +// private permit was retired before a review was authorized. +func CLIPreflightUnusedHandoff(err error, retire func() bool, release func()) error { + var refused *unrecordedPositiveCLIAllowance + if !errors.As(err, &refused) || retire == nil || !retire() { + return err + } + return &CLIPreparationHandoff{recovery: &PreparationRecoveryError{Err: err}, release: release} +} + func (e *Engine) recordCLIAllowance(ctx context.Context, project, attemptID string, expectedRevision int64, input CLIAllowanceObservation) error { if !identifier.MatchString(project) || !identifier.MatchString(attemptID) || expectedRevision < 1 || !validCLIAllowanceObservation(input) { return invalid() @@ -132,6 +156,9 @@ func (e *Engine) recordCLIAllowance(ctx context.Context, project, attemptID stri } current, err := e.executionContext(ctx, tx, checked, input.Remaining == 0) if err != nil { + if input.Remaining > 0 { + return prewritePositiveCLIRefusal(err) + } return err } capability := e.capabilities[current.Configuration.CapabilityID] diff --git a/internal/reviewexec/cli_preflight_test.go b/internal/reviewexec/cli_preflight_test.go index f463e1b79..add25df99 100644 --- a/internal/reviewexec/cli_preflight_test.go +++ b/internal/reviewexec/cli_preflight_test.go @@ -3,6 +3,7 @@ package reviewexec import ( "context" "encoding/json" + "errors" "path/filepath" "reflect" "strings" @@ -338,3 +339,20 @@ func TestCLIAllowanceScopeRevisionAndUpperBounds(t *testing.T) { t.Fatal("valid upper bounds rejected", err) } } + +func TestPositiveCLIAllowanceHandoffNeedsTypedRefusalAndPermitRetirement(t *testing.T) { + local := newStoredUnavailable(storedPolicyHistory, "Retained policy history unavailable") + typed := prewritePositiveCLIRefusal(local) + checked := 0 + retire := func() bool { checked++; return true } + var handoff *CLIPreparationHandoff + if err := CLIPreflightUnusedHandoff(local, retire, nil); err != local || checked != 0 { + t.Fatal("untyped refusal called permit retirement") + } + if err := CLIPreflightUnusedHandoff(typed, func() bool { return false }, nil); err != typed { + t.Fatal("could not retire the permit but handed off settlement") + } + if err := CLIPreflightUnusedHandoff(typed, retire, nil); !errors.As(err, &handoff) || handoff.source != nil || checked != 1 { + t.Fatal("missing exact source-less handoff") + } +} diff --git a/internal/reviewprocess/process.go b/internal/reviewprocess/process.go index b879f0dd4..676042f60 100644 --- a/internal/reviewprocess/process.go +++ b/internal/reviewprocess/process.go @@ -175,6 +175,18 @@ func (r *Runner) Usage(ctx context.Context, workspace reviewworkspace.Workspace, return usage, nil } +// RetireUsagePermit proves the exact permit still existed and was never +// consumed by Review. A different or absent permit is left untouched. +func (r *Runner) RetireUsagePermit(workspace reviewworkspace.Workspace) bool { + r.mu.Lock() + defer r.mu.Unlock() + if r.permit == nil || r.permit.workspace != keyFor(workspace) { + return false + } + r.permit = nil + return true +} + // Review consumes the exact fresh usage permit before starting one process. // A returned capture is raw evidence for a caller-owned private journal; this // package does not classify success from exit status or inspect provider data. diff --git a/internal/reviewprocess/process_test.go b/internal/reviewprocess/process_test.go index 66dda5d80..20d32285f 100644 --- a/internal/reviewprocess/process_test.go +++ b/internal/reviewprocess/process_test.go @@ -709,3 +709,16 @@ func TestZeroUsageRejectsWorkspaceChangedByCommand(t *testing.T) { t.Fatalf("changed workspace authorized review: %v", err) } } + +func TestRetireUsagePermitOnlyRemovesExactWorkspace(t *testing.T) { + want := reviewworkspace.Workspace{Directory: "owned-attempt", ComparisonRef: "pinned"} + other := want + other.Directory = "different-attempt" + r := &Runner{permit: &usagePermit{workspace: keyFor(want)}} + if r.RetireUsagePermit(other) || r.permit == nil { + t.Fatal("wrong workspace retired the permit") + } + if !r.RetireUsagePermit(want) || r.permit != nil || r.RetireUsagePermit(want) { + t.Fatal("matching permit was not retired exactly once") + } +} diff --git a/internal/reviewruntime/cli_driver.go b/internal/reviewruntime/cli_driver.go index a548669cb..c50cd2c27 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -27,6 +27,7 @@ type CLIDriver struct { reader reviewexec.TargetReader fetch func(context.Context, int64, string, string, string, string) error verify func(context.Context, reviewworkspace.Workspace) error + retireUsage func(reviewworkspace.Workspace) bool usage func(context.Context, reviewworkspace.Workspace, string, string) (reviewprocess.Usage, error) review func(context.Context, reviewworkspace.Workspace) (reviewprocess.Capture, error) mu sync.Mutex @@ -79,7 +80,7 @@ func NewCLIDriver(store *core.Store, engine *reviewexec.Engine, capability Opera if err != nil { return nil, err } - return &CLIDriver{store: store, engine: engine, capability: capability, manager: manager, captures: captures, exhaustions: exhaustions, reader: reader, fetch: manager.Fetch, verify: manager.Verify, usage: runner.Usage, review: runner.Review, prepared: map[string]*cliPrepared{}, settling: map[string]struct{}{}}, nil + return &CLIDriver{store: store, engine: engine, capability: capability, manager: manager, captures: captures, exhaustions: exhaustions, reader: reader, fetch: manager.Fetch, verify: manager.Verify, usage: runner.Usage, retireUsage: runner.RetireUsagePermit, review: runner.Review, prepared: map[string]*cliPrepared{}, settling: map[string]struct{}{}}, nil } // A successful preflight can be held by admission before Dispatch. Expire only @@ -200,7 +201,9 @@ func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, return preparation, reviewHold("allowance_unavailable") } if err := d.engine.RecordCLIAllowance(ctx, operation.ProjectID, attempt.ID, attempt.Revision, reviewexec.CLIAllowanceObservation{Anchor: anchor, ObservedAt: time.Now().UTC().Format(time.RFC3339Nano), Remaining: usage.Remaining, Limit: usage.Limit, FullCapacityInMS: usage.FullCapacityInMS, RollingWindowMS: usage.RollingWindowMS, ChangedFiles: changedFiles}); err != nil { - return preparation, err + return preparation, reviewexec.CLIPreflightUnusedHandoff(err, func() bool { + return d.retireUsage != nil && d.retireUsage(workspace) + }, releaseSettlement) } if err := publishPreparedAttempt(ctx, d.engine, operation.ProjectID, attempt.ID, plan); err != nil { if reviewexec.CLIProjectHistoryRefused(err) { From 482f34d6710a6f46b7e1e011f3d766e49808900e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 17:32:59 +1300 Subject: [PATCH 18/34] Harden review selection history and settlement readback --- docs/review-scheduling.md | 2 +- internal/reviewexec/attempts.go | 11 +++- internal/reviewexec/run_selection_worker.go | 44 +++++++++++--- .../scheduling_ancestor_memo_test.go | 9 ++- internal/reviewexec/scheduling_automatic.go | 57 +++++++++++++------ .../scheduling_historical_basis_test.go | 3 + .../scheduling_recovery_regression_test.go | 13 ++++- internal/reviewexec/scheduling_snapshot.go | 2 +- .../reviewexec/scheduling_source_retry.go | 26 +++++++-- 9 files changed, 130 insertions(+), 37 deletions(-) diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index 6e70613bb..676d897e4 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -28,4 +28,4 @@ A legacy bundle can omit a PR control when its unique latest canonical event pro A linked selection with proven custody retains its original child identifier and observed revision in a diagnostic record. Quarantine preserves the child, authorizer, retained evidence and any existing provider action. A held child cannot obtain new admission or reserve a queued turn. Ambiguous provenance holds for investigation. -The active selection custody migration is forward-only. Retain a verified version-one backup before upgrading. For binary rollback, restore the verified bundle to a separate inactive destination and use the [backup recovery procedure](backups.md). Version-two bundles require compatible readers and retain custody records pending an explicit retention policy. +The active selection custody migration is forward-only. Before upgrading, retain a verified rollback backup whose `review_selection` schema is version 1. For binary rollback, restore that bundle to a separate inactive destination and use the [backup recovery procedure](backups.md). Backups containing `review_selection` schema version 2 require compatible readers and retain custody records pending an explicit retention policy. The selection schema version is independent of the bundle manifest version. diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index a94b21866..425b0e456 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -453,8 +453,15 @@ func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operat }) // A nonzero proposal means the entire transaction callback completed; // only then can this caller have lost the acknowledgement of a commit. - if err != nil && proposed.ID != "" && e.unusedCLISettlementCommitted(ctx, original, captured, proposed) { - err = nil + if err != nil && proposed.ID != "" { + // The settlement window may have expired after commit. Give + // this exact read-only acknowledgement check its own short window. + readCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + committed := e.unusedCLISettlementCommitted(readCtx, original, captured, proposed) + cancel() + if committed { + err = nil + } } if err == nil { e.notifyOperation(captured.OperationID) diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 12df85d4b..30c35e6c0 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -174,6 +174,7 @@ type runChoice struct { automaticBasisRevision int64 automaticPullScheduling []int64 automaticGrantRevisions []int64 + automaticRouteSequence int64 } // retryRunSelectionLocal retains completed source reads while only retrying @@ -263,6 +264,16 @@ func readAutomaticGrantRevisions(ctx context.Context, tx *sql.Tx, project, chann return revisions, nil } +// The route writer atomically journals every route revision with its +// projection. A project-scoped watermark also covers routes on stack parents +// discovered later during source I/O; it never includes another project. +func automaticRouteSequence(ctx context.Context, tx *sql.Tx, project string) (int64, error) { + var sequence int64 + err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(sequence),0) FROM events + WHERE project_id=? AND event_type GLOB 'review.route.*'`, project).Scan(&sequence) + return sequence, err +} + func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader) (runChoice, error) { return e.chooseRunWithSourceBudget(ctx, r, repo, c, reader, e.runSourceBudget) } @@ -270,13 +281,14 @@ func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configurati func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (result runChoice, resultErr error) { var automaticQueueLimit *int - var basisRevision int64 + var basisRevision, routeSequence int64 var pullScheduling, grantRevisions []int64 defer func() { result.automaticQueueLimit = automaticQueueLimit result.automaticBasisRevision = basisRevision result.automaticPullScheduling = pullScheduling result.automaticGrantRevisions = grantRevisions + result.automaticRouteSequence = routeSequence }() // Bound source work before metadata lookahead. Local suppression still // rechecks the live prefix at admission if queued work changes afterward. @@ -285,6 +297,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 // An expired snapshot must not shorten a later retry's input. limit, automatic, basisRevision = len(c.Queue), false, 0 pullScheduling, grantRevisions = nil, nil + routeSequence = 0 return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { attribution, err := automaticSelectionBinding(ctx, tx, r) if err != nil { @@ -310,6 +323,10 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 return err } grantRevisions, err = readAutomaticGrantRevisions(ctx, tx, r.ProjectID, r.Channel, c.Queue[:limit]) + if err != nil { + return err + } + routeSequence, err = automaticRouteSequence(ctx, tx, r.ProjectID) return err }) }) @@ -603,10 +620,13 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target project, projectOK = nativeProject.(string) id, idOK = nativeID.(string) if !projectOK || !idOK { - err = e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { - var err error - quarantined, err = quarantineNativeSelection(ctx, tx, nativeProject, nativeID, "queued", expected) - return err + err = retryRunSelectionLocal(ctx, func() error { + quarantined = false + return e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + var err error + quarantined, err = quarantineNativeSelection(ctx, tx, nativeProject, nativeID, "queued", expected) + return err + }) }) return quarantined, err } @@ -758,13 +778,20 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat resultErr = err return } - settle := !zeroPrefixHold && state != "queued" && reason != "selection_changed" + // An incomplete local front read never evaluated this + // basis, even if grant identity matches. Do not mark it served. + settle := !zeroPrefixHold && state != "queued" && reason != "selection_changed" && reason != "local_read_unavailable" if settle && choice.automaticQueueLimit != nil && choice.automaticBasisRevision != 0 { var currentBasis int64 currentBasis, resultErr = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) // Retain an older result and any selected child as history. // It must not mark a newly rearmed lane basis served. settle = resultErr == nil && currentBasis == choice.automaticBasisRevision + if settle { + var routeSequence int64 + routeSequence, resultErr = automaticRouteSequence(ctx, tx, r.ProjectID) + settle = resultErr == nil && routeSequence == choice.automaticRouteSequence + } if settle && pull == 0 { var revisions []int64 // A newly unreadable row must roll back the provisional @@ -831,8 +858,11 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat if err = publishSourcePlans(ctx, tx, core.Scope{ProjectID: current.ProjectID, PrincipalID: current.ActorID, WorkerID: current.WorkerID}, repo, metadataPins, choice.prefix); err != nil { return err } - zeroPrefixHold = choice.state == "held" && choice.automaticQueueLimit != nil && + zeroPrefixHold = choice.automaticQueueLimit != nil && *choice.automaticQueueLimit == 0 && len(c.Queue) > 0 && len(choice.prefix) == 0 + if zeroPrefixHold && choice.state == "empty" && choice.reason == "queue_complete" { + return updateRun(ctx, tx, current, "empty", "queue_complete", "") + } if !zeroPrefixHold { if err = writeFrontFrame(ctx, tx, current, repo, c, choice); err != nil { return err diff --git a/internal/reviewexec/scheduling_ancestor_memo_test.go b/internal/reviewexec/scheduling_ancestor_memo_test.go index f5a162f23..02d58f01d 100644 --- a/internal/reviewexec/scheduling_ancestor_memo_test.go +++ b/internal/reviewexec/scheduling_ancestor_memo_test.go @@ -20,12 +20,16 @@ func TestAutomaticDependenciesReuseSharedAncestorWithinSnapshot(t *testing.T) { 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 := automaticDependenciesWithFrame(ctx, tx, attemptProject, pull, "hosted", frame, true, index, memo) + 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 } @@ -33,6 +37,9 @@ func TestAutomaticDependenciesReuseSharedAncestorWithinSnapshot(t *testing.T) { 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)) } diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index c7f95529d..babde93a4 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -377,6 +377,12 @@ func frontPullIndex(frame frontFrame) map[int64]frontPull { } func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, frame frontFrame, found bool, byNumber map[int64]frontPull, parentFacts map[int64][]any) ([]any, error) { + return automaticDependenciesWithAncestorRead(pull, frame, found, byNumber, parentFacts, func(p frontPull) ([]any, error) { + return readAutomaticAncestorFacts(ctx, tx, project, channel, frame.repository, p) + }) +} + +func automaticDependenciesWithAncestorRead(pull int64, frame frontFrame, found bool, byNumber map[int64]frontPull, parentFacts map[int64][]any, read func(frontPull) ([]any, error)) ([]any, error) { out := []any{} if !found { return out, nil @@ -406,27 +412,10 @@ func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project str parent = p.ParentPullNumber continue } - progress, err := channelProgress(ctx, tx, project, frame.repository, parent, channel) - if err != nil { - return nil, err - } - control, err := readRoundRecord(ctx, tx, project, parent, channel) + facts, err := read(p) if err != nil { return nil, err } - obligations, err := sourceObligationCount(ctx, tx, project, parent) - if err != nil { - return nil, err - } - routes, err := pendingIncomingRoutes(ctx, tx, project, parent) - if err != nil { - return nil, err - } - var completed int64 - if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM review_comparison_proofs WHERE project_id=? AND pull_number=? AND channel='`+channel+`' AND state='ready'`, project, parent).Scan(&completed); err != nil { - return nil, err - } - facts := []any{parent, p.HeadSHA, p.ParentPullNumber, p.ParentSHA, progress, control.Configured, control.Epoch, control.grantRevision, control.Closed, control.Used, control.Dry, control.Tapered, completed, obligations, routes} if parentFacts != nil { parentFacts[parent] = facts } @@ -436,6 +425,31 @@ func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project str return out, nil } +func readAutomaticAncestorFacts(ctx context.Context, tx *sql.Tx, project, channel string, repository int64, p frontPull) ([]any, error) { + parent := p.Number + progress, err := channelProgress(ctx, tx, project, repository, parent, channel) + if err != nil { + return nil, err + } + control, err := readRoundRecord(ctx, tx, project, parent, channel) + if err != nil { + return nil, err + } + obligations, err := sourceObligationCount(ctx, tx, project, parent) + if err != nil { + return nil, err + } + routes, err := pendingIncomingRoutes(ctx, tx, project, parent) + if err != nil { + return nil, err + } + var completed int64 + if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM review_comparison_proofs WHERE project_id=? AND pull_number=? AND channel='`+channel+`' AND state='ready'`, project, parent).Scan(&completed); err != nil { + return nil, err + } + return []any{parent, p.HeadSHA, p.ParentPullNumber, p.ParentSHA, progress, control.Configured, control.Epoch, control.grantRevision, control.Closed, control.Used, control.Dry, control.Tapered, completed, obligations, routes}, nil +} + // Planning can move on to a distinct unattempted PR without treating an // operation's state transition as a reason to recreate that operation. A // selected PR is suppressed by its own semantic basis, independently of peers. @@ -633,6 +647,13 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) } return 0, err } + if _, err := readPullScheduling(ctx, tx, project, pull); err != nil { + var local *pullSchedulingStateError + if errors.As(err, &local) && local.project == project && local.pull == pull { + continue + } + return 0, err + } return position, nil } if err = rows.Err(); err != nil { diff --git a/internal/reviewexec/scheduling_historical_basis_test.go b/internal/reviewexec/scheduling_historical_basis_test.go index 21a4ead5e..b6ccb2f41 100644 --- a/internal/reviewexec/scheduling_historical_basis_test.go +++ b/internal/reviewexec/scheduling_historical_basis_test.go @@ -16,6 +16,9 @@ func TestSchedulingSnapshotDiscoversDetachedNativeHoldWithoutJournalRow(t *testi 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 { diff --git a/internal/reviewexec/scheduling_recovery_regression_test.go b/internal/reviewexec/scheduling_recovery_regression_test.go index 04870c1b5..69e5112fe 100644 --- a/internal/reviewexec/scheduling_recovery_regression_test.go +++ b/internal/reviewexec/scheduling_recovery_regression_test.go @@ -197,7 +197,18 @@ func TestStartupIsolatesDamagedFrontCacheButSnapshotsRejectIt(t *testing.T) { case "json": admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json='not-json'`) case "oversized": - admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json=?`, strings.Repeat(" ", maxFrontPrefixBytes+1)) + // 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": diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 8ac695cf6..556a81c4b 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -69,7 +69,7 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { LEFT JOIN review_scheduling s ON s.project_id=e.project_id WHERE (e.event_type='review.scheduling_updated' OR (typeof(e.event_type)='blob' AND CAST(e.event_type AS TEXT)='review.scheduling_updated')) - AND (typeof(e.event_type)<>'text' OR typeof(e.resource_id)<>'text' OR e.resource_id<>e.project_id OR s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) + AND (typeof(e.event_type)<>'text' OR typeof(e.resource_id)<>'text' OR typeof(e.revision)<>'integer' OR e.resource_id<>e.project_id OR s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) if err != nil { return err } diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index ac3bcfc3f..c33db1465 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -8,7 +8,8 @@ import ( // Recheck recovery fences during every admission snapshot, including after // source I/O. Interrupted initial reads retain ordinary authorization continuity. -// Completed source holds require the exact accepted scheduling revision even +// Both recovery paths respect newer intent. Completed source holds require the +// exact accepted scheduling revision even // after further interrupted reads; incomplete transition evidence is conservative. func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (string, error) { if !validChannel(r.Channel) || r.Revision < 4 { @@ -46,9 +47,7 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin if !proved { return "selection_superseded", nil } - return "", nil - } - if accepted != current.Revision { + } else if accepted != current.Revision { return "automation_authorization_changed", nil } superseded, err := automaticSourceSuperseded(ctx, tx, r) @@ -85,7 +84,7 @@ func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, e var count, distinct, first, last, invalid int64 err = tx.QueryRowContext(ctx, `WITH transitions AS ( SELECT revision,sequence,payload_json,lag(sequence) OVER (ORDER BY revision,sequence) AS previous_sequence - FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' AND revision BETWEEN 2 AND ? + FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' ) SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( CASE WHEN typeof(revision)='integer' AND typeof(sequence)='integer' AND sequence>? AND @@ -93,7 +92,7 @@ func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, e CASE WHEN json_extract(payload_json,'$.state')=CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END AND json_extract(payload_json,'$.reason')='' AND (revision<>? OR json_extract(payload_json,'$.state')=?) THEN 0 ELSE 1 END ELSE 1 END),0) - FROM transitions`, r.ProjectID, r.ID, r.Revision, acceptance.sequence, r.Revision, r.State).Scan(&count, &distinct, &first, &last, &invalid) + FROM transitions`, r.ProjectID, r.ID, acceptance.sequence, r.Revision, r.State).Scan(&count, &distinct, &first, &last, &invalid) if err != nil { return false, err } @@ -104,6 +103,8 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er // Any later or simultaneous same-channel intent supersedes this recovery, even if // that intent was cancelled, denied, held or completed. A directly submitted // operation is also a fence; never recover behind its cancellation/uncertainty. + // A positively bound selection child uses its parent's acceptance order, + // not the later operation creation event. Missing custody remains a fence. // Compare parsed times, not RFC3339 text with variable fractional precision. // For rows with no acceptance event, millisecond ties conservatively fence. // Event sequence is the durable acceptance order even if the wall clock @@ -130,6 +131,19 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er ) OR EXISTS( SELECT 1 FROM events e JOIN review_operations o ON o.project_id=e.project_id AND o.id=e.resource_id WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.requested' AND e.revision=1 AND o.channel=? + AND NOT EXISTS( + SELECT 1 FROM review_selections parent + JOIN events accept ON accept.project_id=parent.project_id AND accept.resource_id=parent.id + AND accept.event_type='review.selection_requested' AND accept.revision=1 + WHERE parent.project_id=o.project_id AND parent.operation_id=o.id AND parent.state='selected' + AND parent.actor_id=o.actor_id AND parent.worker_id=o.worker_id AND parent.channel=o.channel + AND parent.configuration_revision=o.configuration_revision AND parent.policy_revision=o.policy_revision + AND parent.capability_fingerprint=o.capability_fingerprint + AND parent.expected_pull_number IN (0,o.pull_number) + AND accept.actor_id=parent.actor_id AND accept.sequence Date: Sun, 29 Nov 2026 18:24:50 +1300 Subject: [PATCH 19/34] Harden scheduling evidence and review settlement continuity --- internal/reviewexec/attempts.go | 29 +++++++++++++- .../live_cli_preparation_settlement_test.go | 13 +++++++ internal/reviewexec/run_selection_worker.go | 18 ++++++++- internal/reviewexec/scheduling_automatic.go | 7 +++- .../scheduling_paused_grant_basis_test.go | 31 +++++++++++++++ internal/reviewexec/scheduling_snapshot.go | 16 +++++--- ...cheduling_snapshot_event_integrity_test.go | 38 +++++++++++++++++++ ...scheduling_source_custody_positive_test.go | 30 +++++++++++++++ .../scheduling_source_hold_basis_test.go | 20 ++-------- .../reviewexec/scheduling_source_retry.go | 19 ++++++++-- 10 files changed, 192 insertions(+), 29 deletions(-) create mode 100644 internal/reviewexec/scheduling_paused_grant_basis_test.go create mode 100644 internal/reviewexec/scheduling_source_custody_positive_test.go diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 425b0e456..be5b1f53a 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -482,13 +482,38 @@ func (e *Engine) unusedCLISettlementCommitted(ctx context.Context, original Oper return false } o, err := readOperation(ctx, tx, captured.ProjectID, captured.OperationID) - if err != nil || o.State != "queued" || o.AttemptID != "" || o.Reason != "automatic_scheduling_unavailable" || !sameCLIWait(original.Wait, o.Wait) { + if err != nil || !sameCLIWait(original.Wait, o.Wait) { + return false + } + expectedRevision := original.Revision + 2 + switch { + case o.State == "queued" && o.AttemptID == "" && o.Reason == "automatic_scheduling_unavailable": + // The original settlement is still the current operation revision. + case o.State == "preparing" && o.AttemptID != "" && o.AttemptID != a.ID && o.Reason == "": + // An ordinary immediate successor can claim after the transaction + // commits. Prove that claim without treating it as a new permit. + successor, err := readAttempt(ctx, tx, o.ProjectID, o.AttemptID) + if err != nil || successor.OperationID != o.ID || successor.State != "preparing" || + successor.Revision != 1 || successor.Anchor != nil || successor.Intent != "" || + successor.ExternalID != "" || successor.Provider != a.Provider || successor.Account != a.Account { + return false + } + var repositoryID int64 + if err := tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, o.ProjectID).Scan(&repositoryID); err != nil { + return false + } + unused, err := untouchedCLIReservation(ctx, tx, o, successor, repositoryID) + if err != nil || !unused { + return false + } + expectedRevision++ + default: return false } // Compare the same immutable claim fields as the settlement writer. claimed := o claimed.State, claimed.AttemptID = "preparing", captured.ID - if !sameCLIClaim(original, claimed, captured, original.Revision+2) { + if !sameCLIClaim(original, claimed, captured, expectedRevision) { return false } var exact bool diff --git a/internal/reviewexec/live_cli_preparation_settlement_test.go b/internal/reviewexec/live_cli_preparation_settlement_test.go index 4381f5336..29c2e565b 100644 --- a/internal/reviewexec/live_cli_preparation_settlement_test.go +++ b/internal/reviewexec/live_cli_preparation_settlement_test.go @@ -165,4 +165,17 @@ func TestUnusedCLIPreparationConfirmsExactCommittedSettlement(t *testing.T) { 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) + } + } diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 30c35e6c0..a73e52a35 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -246,8 +246,20 @@ func readAutomaticPullSchedulingRevisionsBound(ctx context.Context, tx *sql.Tx, func readAutomaticGrantRevisions(ctx context.Context, tx *sql.Tx, project, channel string, pulls []int64) ([]int64, error) { revisions := make([]int64, 0, len(pulls)) for _, pull := range pulls { + // Keep a position for a provably paused pull, without consulting + // its grant. The caller separately compares the full pause basis. + pause, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + var local *pullSchedulingStateError + if !errors.As(err, &local) || local.project != project || local.pull != pull { + return nil, err + } + } else if pause.Paused { + revisions = append(revisions, -2) + continue + } var native any - err := tx.QueryRowContext(ctx, `SELECT grant_revision FROM review_round_controls WHERE project_id=? AND channel=? AND pull_number=?`, project, channel, pull).Scan(&native) + err = tx.QueryRowContext(ctx, `SELECT grant_revision FROM review_round_controls WHERE project_id=? AND channel=? AND pull_number=?`, project, channel, pull).Scan(&native) if errors.Is(err, sql.ErrNoRows) { revisions = append(revisions, -1) continue @@ -805,7 +817,9 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } } } - if settle { + // A source hold did not evaluate the live workspace facts + // that settlement would hash. Keep its accepted basis. + if settle && !(pull == 0 && choice.sourceReason != "") { resultErr = e.settleAutomaticBasis(ctx, tx, r, pull) } } diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index babde93a4..eaec88cb3 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -627,9 +627,14 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) return position, nil } id, validID := selection.(string) - if selectionProject != project || !validID || !validRunID(id) { + if selectionProject != project { return 0, schedulingUnavailable() } + // An unreadable exact local binding cannot claim this prefix. + // Keep cross-project custody refusals and shared read errors hard. + if !validID || !validRunID(id) { + continue + } r, err := readRun(ctx, tx, project, id) if err != nil { var bindingState *operationSelectionBindingStateError 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_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 556a81c4b..d1630e01b 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -63,13 +63,19 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { return closeErr } // A genuine project scheduling event must have a projection at least - // as new. Only projects with no retained history default to revision zero. + // as new. Its revision must also increase in each project's journal + // order, independently of other projects and event families. var ahead bool - err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events e + err = tx.QueryRowContext(ctx, `WITH scheduling_journal AS ( + SELECT e.*, lag(e.revision) OVER (PARTITION BY e.project_id ORDER BY e.sequence) AS previous_revision + FROM events e + WHERE e.event_type='review.scheduling_updated' OR + (typeof(e.event_type)='blob' AND CAST(e.event_type AS TEXT)='review.scheduling_updated') + ) SELECT EXISTS(SELECT 1 FROM scheduling_journal e LEFT JOIN review_scheduling s ON s.project_id=e.project_id - WHERE (e.event_type='review.scheduling_updated' OR - (typeof(e.event_type)='blob' AND CAST(e.event_type AS TEXT)='review.scheduling_updated')) - AND (typeof(e.event_type)<>'text' OR typeof(e.resource_id)<>'text' OR typeof(e.revision)<>'integer' OR e.resource_id<>e.project_id OR s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) + WHERE typeof(e.event_type)<>'text' OR typeof(e.resource_id)<>'text' + OR typeof(e.revision)<>'integer' OR e.revision<1 OR e.resource_id<>e.project_id + OR s.project_id IS NULL OR e.revision>s.revision OR e.revision<=e.previous_revision)`).Scan(&ahead) if err != nil { return err } diff --git a/internal/reviewexec/scheduling_snapshot_event_integrity_test.go b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go index eee412f6b..8358123fa 100644 --- a/internal/reviewexec/scheduling_snapshot_event_integrity_test.go +++ b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go @@ -2,6 +2,7 @@ package reviewexec import ( "database/sql" + "strings" "testing" ) @@ -174,3 +175,40 @@ func TestOrphanResumeRejectsBlobResourceInSnapshotAndRestore(t *testing.T) { t.Fatalf("invalid resource produced a projection: %d %v", rows, err) } } + +// Independent ordinary project journals can be interleaved in global event order. +func TestSchedulingSnapshotProjectJournalOrderIsPerProject(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + for _, statement := range []string{ + `INSERT INTO review_scheduling VALUES ('test-project',2,0,0,'test-actor','','',?),('other-project',1,0,0,'other-actor','','',?)`, + `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json,created_at) VALUES + ('test-project','test-project','review.scheduling_updated',1,'test-actor','{"automatic_hosted":false}',?), + ('other-project','other-project','review.scheduling_updated',1,'other-actor','{"automatic_hosted":false}',?), + ('test-project','test-project','review.scheduling_updated',2,'test-actor','{"automatic_hosted":false}',?)`, + } { + args := make([]any, strings.Count(statement, "?")) + for i := range args { + args[i] = stamp() + } + if _, err := tx.ExecContext(t.Context(), statement, args...); err != nil { + t.Fatal(err) + } + } + if err := ValidateSchedulingSnapshot(t.Context(), tx); err != nil { + t.Fatal(err) + } +} + +// An ordinary isolated affinity sample never creates a scheduling event. +func TestOrphanResumeReadsRevisionWithSQLiteIntegerAffinity(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + if _, err := tx.ExecContext(t.Context(), `CREATE TABLE revision_sample(rev INTEGER NOT NULL); + INSERT INTO revision_sample VALUES (2.0), (2.5)`); err != nil { + t.Fatal(err) + } + query := `SELECT 'test-project', '2', rev, '{"pull_number":2,"paused":false}', 1, 'test-actor', ? FROM revision_sample WHERE rowid=?` + if err := validateOrphanPullSchedulingEvent(tx.QueryRowContext(t.Context(), query, stamp(), 1)); err != nil { + t.Fatal(err) + } + attemptCode(t, validateOrphanPullSchedulingEvent(tx.QueryRowContext(t.Context(), query, stamp(), 2)), "storage_unavailable") +} diff --git a/internal/reviewexec/scheduling_source_custody_positive_test.go b/internal/reviewexec/scheduling_source_custody_positive_test.go new file mode 100644 index 000000000..d7e1af8e4 --- /dev/null +++ b/internal/reviewexec/scheduling_source_custody_positive_test.go @@ -0,0 +1,30 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" +) + +func TestSourceRecoveryIgnoresEarlierOrdinarySelectedChild(t *testing.T) { + f := selectionFixture(t) + parent, _ := selectionEnqueue(t, f, "earlier-canonical-parent", "hosted", nil) + selectionNext(t, f, &refreshTestReader{}) + + selected := selectionRead(t, f, parent.ID) + if selected.State != "selected" || selected.OperationID == "" { + t.Fatalf("earlier canonical parent did not select a child: %+v", selected) + } + target, _ := selectionEnqueue(t, f, "later-source-recovery-target", "hosted", nil) + run := selectionRead(t, f, target.ID) + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + superseded, err := automaticSourceSuperseded(ctx, tx, run) + if superseded || err != nil { + t.Fatalf("earlier canonical parent child superseded later selection: %v (%v)", superseded, 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 index 79c217379..7ed1d2289 100644 --- a/internal/reviewexec/scheduling_source_hold_basis_test.go +++ b/internal/reviewexec/scheduling_source_hold_basis_test.go @@ -42,18 +42,6 @@ func TestAutomaticSourceHoldRetainsOnlyItsBoundPullSchedulingBasis(t *testing.T) if err != nil { t.Fatal(err) } - var expected string - err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - config, _, err := readConfiguration(ctx, tx, scope.ProjectID) - if err != nil { - return err - } - expected, _, err = f.e.automaticPlanningBasisChannel(ctx, tx, scope.ProjectID, config, receipt.ID, "hosted") - return err - }) - if err != nil || !hash.MatchString(expected) { - t.Fatalf("compute fixture's bound basis: %q (%v)", expected, err) - } reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { if edited { schedulingPause(t, f, 2, 0, true) @@ -66,12 +54,12 @@ func TestAutomaticSourceHoldRetainsOnlyItsBoundPullSchedulingBasis(t *testing.T) 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 settled string - if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, receipt.ID).Scan(&settled); err != nil { + var accepted, settled string + if err := f.store.DB().QueryRow(`SELECT basis_sha256,settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, receipt.ID).Scan(&accepted, &settled); err != nil { t.Fatal(err) } - if edited && settled != "" || !edited && settled != expected { - t.Fatalf("unexpected settled basis after lawful source hold: edited=%v basis=%q", edited, settled) + if accepted != strings.Repeat("a", 64) || settled != "" { + t.Fatalf("unverified source hold did not retain only accepted basis: edited=%v accepted=%q settled=%q", edited, accepted, settled) } }) } diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index c33db1465..34ad6c4c5 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -83,16 +83,17 @@ func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, e } var count, distinct, first, last, invalid int64 err = tx.QueryRowContext(ctx, `WITH transitions AS ( - SELECT revision,sequence,payload_json,lag(sequence) OVER (ORDER BY revision,sequence) AS previous_sequence + SELECT revision,sequence,actor_id,payload_json,lag(sequence) OVER (ORDER BY revision,sequence) AS previous_sequence FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' ) SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( CASE WHEN typeof(revision)='integer' AND typeof(sequence)='integer' AND sequence>? AND + typeof(actor_id)='text' AND actor_id=? AND (previous_sequence IS NULL OR sequence>previous_sequence) AND json_valid(payload_json) THEN CASE WHEN json_extract(payload_json,'$.state')=CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END AND json_extract(payload_json,'$.reason')='' AND (revision<>? OR json_extract(payload_json,'$.state')=?) THEN 0 ELSE 1 END ELSE 1 END),0) - FROM transitions`, r.ProjectID, r.ID, acceptance.sequence, r.Revision, r.State).Scan(&count, &distinct, &first, &last, &invalid) + FROM transitions`, r.ProjectID, r.ID, acceptance.sequence, r.ActorID, r.Revision, r.State).Scan(&count, &distinct, &first, &last, &invalid) if err != nil { return false, err } @@ -105,6 +106,9 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er // operation is also a fence; never recover behind its cancellation/uncertainty. // A positively bound selection child uses its parent's acceptance order, // not the later operation creation event. Missing custody remains a fence. + // Match the closed canonical acceptance shapes without parsing untrusted + // payloads. Channel and worker are restricted to JSON-safe native IDs, + // so SQLite json_object emits the same bytes as selectionRequestedEvent. // Compare parsed times, not RFC3339 text with variable fractional precision. // For rows with no acceptance event, millisecond ties conservatively fence. // Event sequence is the durable acceptance order even if the wall clock @@ -140,7 +144,16 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er AND parent.configuration_revision=o.configuration_revision AND parent.policy_revision=o.policy_revision AND parent.capability_fingerprint=o.capability_fingerprint AND parent.expected_pull_number IN (0,o.pull_number) - AND accept.actor_id=parent.actor_id AND accept.sequence0 AND accept.sequence Date: Sun, 29 Nov 2026 19:32:24 +1300 Subject: [PATCH 20/34] Guard FireController review recovery and local scheduling holds --- internal/reviewexec/cli_preflight.go | 16 +++++++++++-- internal/reviewexec/cli_wait_test.go | 20 ++++++++++++++++ .../reviewexec/finish_front_local_test.go | 23 ++++++++++++++++++ internal/reviewexec/run_selection.go | 10 ++++++-- internal/reviewexec/run_selection_worker.go | 24 ++++++++++++++++--- internal/reviewexec/scheduling_automatic.go | 3 ++- .../reviewexec/scheduling_source_retry.go | 6 ++--- 7 files changed, 91 insertions(+), 11 deletions(-) create mode 100644 internal/reviewexec/finish_front_local_test.go diff --git a/internal/reviewexec/cli_preflight.go b/internal/reviewexec/cli_preflight.go index 6de948c46..c8131fd50 100644 --- a/internal/reviewexec/cli_preflight.go +++ b/internal/reviewexec/cli_preflight.go @@ -261,10 +261,22 @@ func (e *Engine) replayCLIExhaustion(ctx context.Context, r CLIExhaustionRecover if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM review_execution_reservations WHERE attempt_id=?`, a.ID).Scan(&reservations); err != nil { return err } - if o.Wait.BaselineAttemptID != baseline || o.Revision != original.Revision+1 || reservations != 0 { + if o.Wait.BaselineAttemptID != baseline || o.Revision != original.Revision+1 || reservations != 0 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { return invalid() } - return nil + if live && (o.AllowOutOfOrder != original.AllowOutOfOrder || o.OverrideFileLimit != original.OverrideFileLimit || + o.Wait.Paused != (original.Wait != nil && original.Wait.Paused)) { + return invalid() + } + // readOperation validates the projected deadline, but its baseline + // may belong to an earlier attempt. Require this attempt's own + // retained cooldown transition before acknowledging the replay. + var recorded int + err := tx.QueryRowContext(ctx, `SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=? AND state='held' AND reason='allowance_exhausted'`, a.ID, a.Revision).Scan(&recorded) + if errors.Is(err, sql.ErrNoRows) { + return invalid() + } + return err } if a.State != "preparing" || a.Revision != 1 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" || o.State != "preparing" || o.AttemptID != a.ID || o.Revision != original.Revision { return invalid() diff --git a/internal/reviewexec/cli_wait_test.go b/internal/reviewexec/cli_wait_test.go index f1a98f69c..4debf760f 100644 --- a/internal/reviewexec/cli_wait_test.go +++ b/internal/reviewexec/cli_wait_test.go @@ -350,6 +350,26 @@ func TestCLIWaitRecoveryRequiresProvenUnusedExhaustion(t *testing.T) { } } +func TestCLIExhaustionReplayAcknowledgesExactCooldown(t *testing.T) { + f, a, observation, _ := cliWaitFixture(t) + original := cliWaitRead(t, f, a.OperationID) + recovery := CLIExhaustionRecovery{Operation: original, Attempt: a, Observation: observation} + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + queued := cliWaitRead(t, f, a.OperationID) + cliWaitDue(t, queued) + for _, live := range []bool{false, true} { + if err := f.e.replayCLIExhaustion(t.Context(), recovery, live); err != nil { + t.Fatalf("exact settled replay (live=%v): %v", live, err) + } + } + if after := cliWaitRead(t, f, a.OperationID); after.Revision != queued.Revision || !sameCLIWait(after.Wait, queued.Wait) { + t.Fatal("settled replay changed the existing wait", after) + } + assertCLIWaitNoCredit(t, f) +} + func TestCLIWaitDoesNotReopenTerminalQuotaHold(t *testing.T) { f, a, _, _ := cliWaitFixture(t) if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "allowance_exhausted", ""); err != nil { 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/run_selection.go b/internal/reviewexec/run_selection.go index df13d7ff6..5fb3e2643 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -61,6 +61,12 @@ func validRun(r Run) bool { } return false } + +// A retained selection decode refusal is local to the positively scoped row. +type retainedSelectionStateError struct{ error } + +func (e *retainedSelectionStateError) Unwrap() error { return e.error } + func readRun(ctx context.Context, q EvidenceQuery, project, id string) (Run, error) { var r Run err := scanRoundValues(q.QueryRowContext(ctx, `SELECT `+runColumns+` FROM review_selections WHERE project_id=? AND id=?`, project, id), &r.ID, &r.ProjectID, &r.ActorID, &r.WorkerID, &r.Channel, &r.ConfigurationRevision, &r.PolicyRevision, &r.CapabilityFingerprint, &r.ExpectedPullNumber, &r.State, &r.Reason, &r.Revision, &r.OperationID, &r.CreatedAt, &r.UpdatedAt) @@ -68,13 +74,13 @@ func readRun(ctx context.Context, q EvidenceQuery, project, id string) (Run, err return r, core.Fail("not_found", "The review selection is unavailable in this project.", 404) } if automaticProjectRefused(err) { - return Run{}, runUnavailable() + return Run{}, &retainedSelectionStateError{runUnavailable()} } if err != nil { return r, err } if !validRun(r) { - return Run{}, runUnavailable() + return Run{}, &retainedSelectionStateError{runUnavailable()} } if r.State == "selected" { child, err := readOperation(ctx, q, r.ProjectID, r.OperationID) diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index a73e52a35..9f85310b1 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -254,6 +254,9 @@ func readAutomaticGrantRevisions(ctx context.Context, tx *sql.Tx, project, chann if !errors.As(err, &local) || local.project != project || local.pull != pull { return nil, err } + // Unreadable local pause state is not an unpaused grant input. + revisions = append(revisions, -3) + continue } else if pause.Paused { revisions = append(revisions, -2) continue @@ -719,7 +722,8 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target } choice.claimAutomaticQueueLimit = claimAutomaticQueueLimit worked, err := e.finishRunChoice(ctx, r, repo, metadataPins, choice) - if automaticProjectRefused(err) { + var localFront *finishFrontLocalRefusal + if automaticProjectRefused(err) || errors.As(err, &localFront) { return e.holdRunLocalRefusal(ctx, r) } return worked, err @@ -766,6 +770,20 @@ func (e *Engine) holdRunLocalRefusal(ctx context.Context, expected Run) (bool, e } // finishRunChoice validates and records a source selection in one local write. +// A local refusal at the last front recheck must first roll back the +// provisional frame. The selection worker can then persist only a guarded hold. +type finishFrontLocalRefusal struct{ error } + +func finishFrontReadError(r Run, err error) error { + var pause *pullSchedulingStateError + var failure *core.Error + if (errors.As(err, &pause) && pause.project == r.ProjectID && pause.pull > 0) || + (errors.As(err, &failure) && failure.Code == "local_read_unavailable") { + return &finishFrontLocalRefusal{err} + } + return err +} + func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadataPins map[int64]reviews.SourceMetadataPin, choice runChoice) (bool, error) { err := retryRunSelectionLocal(ctx, func() error { return e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) (resultErr error) { @@ -891,7 +909,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat // facts rather than dispatch directly from this recheck. _, reason, err := e.runFront(ctx, tx, current, repo, choice.prefix, true) if err != nil { - return err + return finishFrontReadError(current, err) } if reason != choice.reason { return updateRun(ctx, tx, current, "held", "selection_changed", "") @@ -901,7 +919,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } front, reason, err := e.runFront(ctx, tx, current, repo, choice.prefix, true) if err != nil { - return err + return finishFrontReadError(current, err) } if reason != "" { return updateRun(ctx, tx, current, "held", reason, "") diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index eaec88cb3..432cc83c2 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -638,7 +638,8 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) r, err := readRun(ctx, tx, project, id) if err != nil { var bindingState *operationSelectionBindingStateError - if errors.As(err, &bindingState) { + var selectionState *retainedSelectionStateError + if errors.As(err, &bindingState) || errors.As(err, &selectionState) { continue } return 0, err diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index 34ad6c4c5..945a51180 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -89,9 +89,9 @@ func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, e SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( CASE WHEN typeof(revision)='integer' AND typeof(sequence)='integer' AND sequence>? AND typeof(actor_id)='text' AND actor_id=? AND - (previous_sequence IS NULL OR sequence>previous_sequence) AND json_valid(payload_json) THEN - CASE WHEN json_extract(payload_json,'$.state')=CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END - AND json_extract(payload_json,'$.reason')='' AND (revision<>? OR json_extract(payload_json,'$.state')=?) THEN 0 ELSE 1 END + (previous_sequence IS NULL OR sequence>previous_sequence) AND typeof(payload_json)='text' THEN + CASE WHEN payload_json=json_object('reason','','state',CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END) + AND (revision<>? OR payload_json=json_object('reason','','state',?)) THEN 0 ELSE 1 END ELSE 1 END),0) FROM transitions`, r.ProjectID, r.ID, acceptance.sequence, r.ActorID, r.Revision, r.State).Scan(&count, &distinct, &first, &last, &invalid) if err != nil { From 9d34690d3833c59fb13e7652dafbc66972ece32c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 20:56:17 +1300 Subject: [PATCH 21/34] Use bounded supervisor readiness assertion --- internal/reviewexec/supervisor_test.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/internal/reviewexec/supervisor_test.go b/internal/reviewexec/supervisor_test.go index 85728d9e3..5e30102ec 100644 --- a/internal/reviewexec/supervisor_test.go +++ b/internal/reviewexec/supervisor_test.go @@ -214,11 +214,9 @@ func TestSupervisorBusyQueueDoesNotEnterWriterAndCoordinationStaysUsable(t *test if _, err := f.e.Advance(context.Background(), attemptProject, busy.ID, busy.Revision+2, "cancelled", "synthetic_release", ""); err != nil { t.Fatal(err) } - select { - case <-ready: - case <-time.After(2 * time.Second): - t.Fatal("supervisor did not resume queued work after reservation release") - } + waitSupervisor(t, "supervisor resumes queued work after reservation release", func() bool { + return len(ready) != 0 + }) stop() } From a8b2e8eff3c92ce2166964024187aa9f65043be1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 21:33:17 +1300 Subject: [PATCH 22/34] Preserve verified review recovery and validate retained scheduling history --- internal/backup/inventory.go | 4 +- internal/backup/scheduling_test.go | 7 +- internal/reviewexec/cli_coverage.go | 8 +- .../operation_direct_receipt_test.go | 40 ++++++ internal/reviewexec/run_selection.go | 3 + internal/reviewexec/scheduling.go | 4 +- internal/reviewexec/scheduling_authority.go | 116 ++++++++++++++++++ .../scheduling_authorization_continuity.go | 8 +- .../scheduling_selected_basis_guard_test.go | 8 +- internal/reviewexec/scheduling_snapshot.go | 64 +++++++--- .../reviewexec/scheduling_source_retry.go | 15 ++- internal/reviewexec/supervisor.go | 7 ++ internal/reviewexec/supervisor_test.go | 16 +++ 13 files changed, 275 insertions(+), 25 deletions(-) create mode 100644 internal/reviewexec/scheduling_authority.go diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index 3fe764f7c..6e47d067b 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -1097,8 +1097,8 @@ func validateSnapshotContent(ctx context.Context, dataDir string, m Manifest, al // An optional predecessor domain may be absent only before it has // produced durable controls. Dropping tables cannot erase that history. var used bool - if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events WHERE event_type IN ('review.scheduling_updated','review.pull_scheduling_updated') - OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT) IN ('review.scheduling_updated','review.pull_scheduling_updated')))`).Scan(&used); err != nil { + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events WHERE event_type IN ('review.scheduling_updated','review.pull_scheduling_updated','review.scheduling_authority_bound') + OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT) IN ('review.scheduling_updated','review.pull_scheduling_updated','review.scheduling_authority_bound')))`).Scan(&used); err != nil { return unavailable() } if used { diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index e64a35ee2..2a0817eab 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -29,12 +29,17 @@ func TestSchedulingBackupRetainsCanonicalProjectRow(t *testing.T) { } _, err := tx.ExecContext(ctx, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) VALUES(?,'review.scheduling_updated',?,1,?,'{"automatic_hosted":true,"automatic_cli":false,"hosted_basis_revision":1,"cli_basis_revision":1}',?)`, f.project, f.project, f.principal, at) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) + VALUES(?,'review.scheduling_authority_bound',?,1,?,'{"generation":1}',?)`, f.project, f.project, f.principal, at) return err }); err != nil { t.Fatal(err) } const controls = `SELECT * FROM review_scheduling` - const journal = `SELECT * FROM events WHERE event_type='review.scheduling_updated' ORDER BY sequence` + const journal = `SELECT * FROM events WHERE event_type IN ('review.scheduling_updated','review.scheduling_authority_bound') ORDER BY sequence` wantControls, wantJournal := restoreRows(t, f.store.DB(), controls), restoreRows(t, f.store.DB(), journal) bundle := restoreBundle(t, f) immutable := restoreTree(t, bundle.Path) diff --git a/internal/reviewexec/cli_coverage.go b/internal/reviewexec/cli_coverage.go index 76786551b..b5186eaee 100644 --- a/internal/reviewexec/cli_coverage.go +++ b/internal/reviewexec/cli_coverage.go @@ -7,6 +7,12 @@ import ( "time" ) +// Dirty comparison proof is a typed pre-dispatch refusal, distinct from +// a query or storage failure whose outcome cannot be classified. +type dirtyComparisonProofError struct{ error } + +func (e *dirtyComparisonProofError) Unwrap() error { return e.error } + func validCoverageSource(current SourcePlan) bool { observed, err := time.Parse(time.RFC3339Nano, current.ObservedAt) return err == nil && !observed.IsZero() && current.SourceReason == "" && current.Repository.ID > 0 && repository.MatchString(current.Repository.FullName) && current.Repository.DefaultBranch != "" && safeText(current.Repository.DefaultBranch, 256) && @@ -83,7 +89,7 @@ func channelProgress(ctx context.Context, tx *sql.Tx, project string, repository return ComparisonState{}, err } if dirty { - return ComparisonState{}, &automaticProjectStateError{adjudicationStorageError()} + return ComparisonState{}, &dirtyComparisonProofError{&automaticProjectStateError{adjudicationStorageError()}} } c, err := readRoundControl(ctx, tx, project, number, channel) if err != nil { diff --git a/internal/reviewexec/operation_direct_receipt_test.go b/internal/reviewexec/operation_direct_receipt_test.go index 9a159655d..aae444b82 100644 --- a/internal/reviewexec/operation_direct_receipt_test.go +++ b/internal/reviewexec/operation_direct_receipt_test.go @@ -70,3 +70,43 @@ func seedDirectOperationReceipt(t *testing.T, f *attemptFixture, project, id str admissionSQL(t, f, `INSERT INTO receipts(instance_id,principal_id,project_id,operation,target,key,fingerprint,response_json) VALUES(?,?,?,'reviews.request','requests',?,?,?)`, f.store.InstanceID(), o.ActorID, project, core.NewID("fixture-key"), fp, encoded(Receipt{ID: id, State: "queued", Revision: 1})) } + +func TestDirectOperationEnqueueRollsBackOnReceiptStorageFailure(t *testing.T) { + f := schedulingFixture(t) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + request := Request{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: "hosted", HeadSHA: strings.Repeat("a", 40)} + const key = "direct-receipt-storage-failure" + counts := func() [3]int { + return [3]int{ + attemptCount(t, f.store, `SELECT count(*) FROM review_operations WHERE project_id=? AND pull_number=2 AND channel='hosted'`, attemptProject), + attemptCount(t, f.store, `SELECT count(*) FROM events WHERE project_id=? AND event_type='review.requested'`, attemptProject), + attemptCount(t, f.store, `SELECT count(*) FROM receipts WHERE project_id=? AND operation='reviews.request' AND key=?`, attemptProject, key), + } + } + before := counts() + admissionSQL(t, f, `CREATE TRIGGER synthetic_receipt_storage_failure BEFORE INSERT ON receipts + WHEN NEW.key='direct-receipt-storage-failure' AND NEW.operation='reviews.request' + AND EXISTS(SELECT 1 FROM review_operations WHERE project_id=NEW.project_id AND pull_number=2 AND channel='hosted' AND state='queued') + BEGIN SELECT RAISE(ABORT,'synthetic receipt write failure'); END`) + if _, err := f.e.Enqueue(t.Context(), scope, key, request); err == nil { + t.Fatal("request committed despite its receipt write failing") + } + if got := counts(); got != before { + t.Fatal("partial enqueue", got, before) + } + admissionSQL(t, f, `DROP TRIGGER synthetic_receipt_storage_failure`) + reply, err := f.e.Enqueue(t.Context(), scope, key, request) + if err != nil { + t.Fatal(err) + } + replay, err := f.e.Enqueue(t.Context(), scope, key, request) + if err != nil || string(reply) != string(replay) { + t.Fatal("receipt retry differed", err) + } + after := counts() + for i, n := range before { + if after[i] != n+1 { + t.Fatal("retry did not commit one atomic receipt", before, after) + } + } +} diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 5fb3e2643..9037dc76e 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -587,6 +587,9 @@ func quarantineNativeSelection(ctx context.Context, tx *sql.Tx, project, id any, if err != nil { return false, err } + if retained, ok := originalRevision.(int64); originalLink == nil && ok && retained < 1 { + return false, &unprovedSelectionCustodyError{runUnavailable()} + } linkGuard := ` AND operation_id IS NULL` holdReason := "local_read_unavailable" args := []any{project, id, state, revision} diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index afa8ff24e..64fbf0df1 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -267,7 +267,7 @@ func (e *Engine) ReadPullScheduling(ctx context.Context, scope core.Scope, pull var out PullScheduling err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { var err error - out, err = readPullScheduling(ctx, tx, scope.ProjectID, pull) + out, err = editablePullScheduling(ctx, tx, scope.ProjectID, pull) return err }) return out, err @@ -277,7 +277,7 @@ func (e *Engine) ConfigurePullScheduling(ctx context.Context, scope core.Scope, return nil, invalid() } out, err := e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.pull_scheduling", Target: strconv.FormatInt(pull, 10), Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { - old, err := readPullScheduling(ctx, tx, scope.ProjectID, pull) + old, err := editablePullScheduling(ctx, tx, scope.ProjectID, pull) if err != nil { return nil, err } diff --git a/internal/reviewexec/scheduling_authority.go b/internal/reviewexec/scheduling_authority.go new file mode 100644 index 000000000..431541166 --- /dev/null +++ b/internal/reviewexec/scheduling_authority.go @@ -0,0 +1,116 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" +) + +const schedulingAuthorityBoundEvent = "review.scheduling_authority_bound" + +type schedulingAuthorityPayload struct { + Generation int64 `json:"generation"` +} + +func decodeSchedulingAuthorityGeneration(payload sql.NullString, revision int64) (int64, bool) { + var proof schedulingAuthorityPayload + if !payload.Valid || len(payload.String) > 4096 || json.Unmarshal([]byte(payload.String), &proof) != nil || + proof.Generation < 1 || proof.Generation > revision || encoded(proof) != payload.String { + return 0, false + } + return proof.Generation, true +} + +// This journal proves the settings writer retained the same authority tuple. +// It is not a history of credential activation or grant state. Callers still +// verify the original tuple against current live authority. +func schedulingAuthorityContinuity(ctx context.Context, tx *sql.Tx, project, actor string, first, last int64, stableHostedBasis bool) (int64, error) { + if first < 1 || last < first || last-first > 10000 { + return 0, nil + } + rows, err := tx.QueryContext(ctx, `WITH settings AS ( + SELECT resource_id,revision,count(*) AS copies,max(actor_id) AS actor_id,max(sequence) AS sequence, + max(CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END) AS body + FROM events WHERE project_id=? AND resource_id=? AND event_type='review.scheduling_updated' AND revision BETWEEN ? AND ? + GROUP BY resource_id,revision + ) + SELECT w.resource_id,w.actor_id,w.revision,w.sequence, + CASE WHEN typeof(w.payload_json)='text' AND length(CAST(w.payload_json AS BLOB))<=4096 THEN w.payload_json END, + u.body + FROM events w JOIN settings u ON u.resource_id=w.resource_id AND u.revision=w.revision + AND u.copies=1 AND typeof(u.actor_id)='text' AND u.actor_id=w.actor_id AND u.sequence last-first || rev != first+seen { + return 0, nil + } + value, valid := decodeSchedulingAuthorityGeneration(witness, rev) + settings, basis, _, validSettings := readSchedulingEventPayload(settingsBody, rev) + if !valid || !validSettings || seen > 0 && value != generation { + return 0, nil + } + if stableHostedBasis { + if len(settings.HostedBasis) == 0 || settings.Hosted == nil || !*settings.Hosted || seen > 0 && hostedBasis != basis { + return 0, nil + } + hostedBasis = basis + } + generation = value + previousSequence = ord + seen++ + } + if err = rows.Err(); err != nil { + return 0, err + } + if seen != last-first+1 { + return 0, nil + } + return generation, nil +} + +// Backups preserve evidence immutably. A legacy settings event may have no +// witness, but a present witness must pair uniquely with its original event. +func validateSchedulingAuthoritySnapshot(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, `WITH witnesses AS ( + SELECT e.*, count(*) OVER (PARTITION BY project_id,resource_id,revision) AS copies + FROM events e WHERE event_type=? OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)=?) + ) SELECT w.project_id,w.actor_id,w.revision, CASE WHEN + typeof(w.event_type)='text' AND typeof(w.project_id)='text' AND typeof(w.resource_id)='text' + AND w.resource_id=w.project_id AND typeof(w.actor_id)='text' + AND typeof(w.sequence)='integer' AND w.sequence>0 AND typeof(w.revision)='integer' AND w.revision>0 AND w.copies=1 + AND typeof(w.payload_json)='text' AND length(CAST(w.payload_json AS BLOB))<=4096 + AND (SELECT count(*) FROM events u WHERE u.project_id=w.project_id AND u.resource_id=w.resource_id + AND u.event_type='review.scheduling_updated' AND u.revision=w.revision)=1 + AND EXISTS(SELECT 1 FROM events u WHERE u.project_id=w.project_id AND u.resource_id=w.resource_id + AND u.event_type='review.scheduling_updated' AND u.revision=w.revision AND u.actor_id=w.actor_id AND u.sequence 10 { - return schedulingUnavailable() + return PullScheduling{}, schedulingUnavailable() } nativeRevision, revisionOK := revision.(int64) pull, err := strconv.ParseInt(resource, 10, 32) if err != nil || pull < 1 || strconv.FormatInt(pull, 10) != resource || !revisionOK || nativeRevision < 1 || matches != 1 || !validPullSchedulingPayload(payload, pull, false) || !project.Valid || !identifier.MatchString(project.String) || !actor.Valid || !identifier.MatchString(actor.String) || !createdAt.Valid || !roundTime(createdAt.String) { - return schedulingUnavailable() + return PullScheduling{}, schedulingUnavailable() } - return nil + return PullScheduling{ProjectID: project.String, PullNumber: pull, Revision: nativeRevision, ActorID: actor.String, UpdatedAt: createdAt.String}, nil +} + +// Read/mutate controls must honor the retained CAS position even where an +// older runtime discarded an unpaused projection. Ordinary admission reads +// the current pause bit only and need not re-scan historical events. +func editablePullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) (PullScheduling, error) { + current, err := readPullScheduling(ctx, tx, project, pull) + if err != nil || current.Revision != 0 { + return current, err + } + orphan, err := scanOrphanPullResume(tx.QueryRowContext(ctx, orphanPullSchedulingSQL+` + AND e.project_id=? AND (e.resource_id=? OR (typeof(e.resource_id)='blob' AND CAST(e.resource_id AS TEXT)=?))`+ + orphanPullSchedulingRankSQL+orphanPullSchedulingSelectSQL, project, strconv.FormatInt(pull, 10), strconv.FormatInt(pull, 10))) + if errors.Is(err, sql.ErrNoRows) { + return current, nil + } + if err != nil { + return current, err + } + if orphan.ProjectID != project || orphan.PullNumber != pull { + return current, schedulingUnavailable() + } + return orphan, nil } // RestoreHistoricalPullResumes preserves the CAS revision of valid legacy @@ -307,7 +342,7 @@ func RestoreHistoricalPullResumes(ctx context.Context, tx *sql.Tx) error { } // Both reads are in the same transaction, and no projection was inserted // until the complete set was validated. Keep the source event sequence. - _, err = tx.ExecContext(ctx, orphanPullSchedulingSQL+` + _, err = tx.ExecContext(ctx, orphanPullSchedulingSQL+orphanPullSchedulingRankSQL+` INSERT INTO review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at) SELECT o.project_id,CAST(o.resource_id AS INTEGER),o.revision,0,'',e.actor_id,e.created_at`+latestOrphanPullResumesSQL) return err @@ -329,6 +364,7 @@ func validPullSchedulingPayload(payload sql.NullString, pull int64, paused bool) const pullSchedulingSnapshotEventsSQL = `WITH represented_history AS ( SELECT s.project_id,s.pull_number,s.revision AS control_revision,s.paused,s.actor_id AS control_actor, e.revision,e.actor_id,e.event_type, + CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END AS created_at, CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END AS payload, LAG(e.revision) OVER (PARTITION BY s.project_id,s.pull_number ORDER BY e.sequence) AS prev_revision FROM events e CROSS JOIN review_pull_scheduling s @@ -336,12 +372,12 @@ const pullSchedulingSnapshotEventsSQL = `WITH represented_history AS ( (typeof(e.event_type)='blob' AND CAST(e.event_type AS TEXT)='review.pull_scheduling_updated')) AND s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id ), relevant AS ( - SELECT *, (typeof(event_type)<>'text' OR typeof(revision)<>'integer' OR revision<1 OR + SELECT *, (typeof(event_type)<>'text' OR typeof(revision)<>'integer' OR revision<1 OR created_at IS NULL OR julianday(created_at) IS NULL OR (prev_revision IS NOT NULL AND revision<=prev_revision)) AS invalid_event FROM represented_history ) SELECT project_id,pull_number,control_revision,paused,control_actor, - CASE WHEN NOT invalid_event THEN revision END,actor_id,payload + CASE WHEN NOT invalid_event THEN revision END,actor_id,payload,created_at FROM relevant WHERE invalid_event OR revision>=control_revision ORDER BY project_id,pull_number` @@ -361,13 +397,13 @@ func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) var project, actor string var pull, controlRevision, paused int64 var nativeRevision, nativeEventActor any - var payload sql.NullString - if err := rows.Scan(&project, &pull, &controlRevision, &paused, &actor, &nativeRevision, &nativeEventActor, &payload); err != nil { + var payload, createdAt sql.NullString + if err := rows.Scan(&project, &pull, &controlRevision, &paused, &actor, &nativeRevision, &nativeEventActor, &payload, &createdAt); err != nil { return err } revision, integer := nativeRevision.(int64) eventActor, textActor := nativeEventActor.(string) - if (project == lastProject && pull == lastPull) || !integer || !textActor || revision != controlRevision || eventActor != actor || !validPullSchedulingPayload(payload, pull, paused == 1) { + if (project == lastProject && pull == lastPull) || !integer || !textActor || revision != controlRevision || eventActor != actor || !createdAt.Valid || !roundTime(createdAt.String) || !validPullSchedulingPayload(payload, pull, paused == 1) { return schedulingUnavailable() } count++ diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index 945a51180..1f8cb888e 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -9,8 +9,8 @@ import ( // Recheck recovery fences during every admission snapshot, including after // source I/O. Interrupted initial reads retain ordinary authorization continuity. // Both recovery paths respect newer intent. Completed source holds require the -// exact accepted scheduling revision even -// after further interrupted reads; incomplete transition evidence is conservative. +// exact accepted revision unless a pending Hosted retry proves unchanged +// persisted authority and lane basis. Incomplete evidence remains conservative. func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (string, error) { if !validChannel(r.Channel) || r.Revision < 4 { return "", nil @@ -48,7 +48,16 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin return "selection_superseded", nil } } else if accepted != current.Revision { - return "automation_authorization_changed", nil + if r.Channel != "hosted" || r.State == "selected" || r.OperationID != "" || accepted >= current.Revision { + return "automation_authorization_changed", nil + } + generation, err := schedulingAuthorityContinuity(ctx, tx, r.ProjectID, r.ActorID, accepted, current.Revision, true) + if err != nil { + return "", err + } + if generation == 0 { + return "automation_authorization_changed", nil + } } superseded, err := automaticSourceSuperseded(ctx, tx, r) if err != nil { diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 1d2af10ce..91ab7a6d8 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -872,6 +872,13 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri return err } if ctx.Err() == nil { + var dirtyComparison *dirtyComparisonProofError + if o.Channel == "hosted" && errors.As(err, &dirtyComparison) { + if err := e.finishPreparation(a, "held", "preparation_failed"); err != nil { + return err + } + continue + } if o.Channel == "hosted" && isSourceObligationProjectStateError(err) { if err := e.finishPreparation(a, "held", "automatic_scheduling_unavailable"); err != nil { return err diff --git a/internal/reviewexec/supervisor_test.go b/internal/reviewexec/supervisor_test.go index 5e30102ec..c8baf8dba 100644 --- a/internal/reviewexec/supervisor_test.go +++ b/internal/reviewexec/supervisor_test.go @@ -1522,3 +1522,19 @@ func TestSupervisorCLICooldownDatabaseFailureRemainsFatal(t *testing.T) { t.Fatal("database failure became a hold or lost guarded preparation") } } + +func TestHostedPreparationSettlesTypedComparisonRefusal(t *testing.T) { + f := supervisorFixture(t) + driver := &controlledDriver{prepare: func(context.Context, Operation, Configuration, Attempt) (Preparation, error) { + return Preparation{}, &dirtyComparisonProofError{&automaticProjectStateError{adjudicationStorageError()}} + }} + r := f.enqueue(t, attemptProject, "hosted-local-proof-refusal", "hosted", 2, 1) + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal(err) + } + got := cliWaitRead(t, f, r.ID) + if got.State != "held" || got.Reason != "preparation_failed" || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || + attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal(got) + } +} From 4dd406e88f2505b90768787c84b681db7dd8a75f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 22:20:51 +1300 Subject: [PATCH 23/34] Preserve review scheduling through guarded retries and pauses --- docs/review-scheduling.md | 2 + internal/reviewexec/attempts.go | 72 +++++- internal/reviewexec/cli_draft_wait.go | 3 + internal/reviewexec/cli_pause_no_start.go | 222 ++++++++++++++++++ internal/reviewexec/hosted_priority.go | 7 + internal/reviewexec/hosted_wait_validation.go | 9 +- .../live_cli_preparation_settlement_test.go | 23 +- internal/reviewexec/run_selection.go | 19 +- internal/reviewexec/run_selection_schema.go | 26 +- internal/reviewexec/run_selection_worker.go | 98 +++++--- internal/reviewexec/scheduling_authority.go | 5 +- internal/reviewexec/scheduling_automatic.go | 53 +++++ .../scheduling_boundary_compatibility_test.go | 29 ++- .../scheduling_selected_basis_guard_test.go | 57 ++++- internal/reviewexec/scheduling_snapshot.go | 38 ++- ...cheduling_snapshot_event_integrity_test.go | 50 +++- .../reviewexec/scheduling_source_retry.go | 7 +- internal/reviewexec/supervisor.go | 7 + internal/reviewexec/wait_deadline.go | 5 + internal/reviewprocess/process.go | 6 +- internal/reviewprocess/process_test.go | 22 +- internal/reviewruntime/cli_driver.go | 10 +- internal/reviewruntime/cli_driver_test.go | 99 ++++++++ 23 files changed, 785 insertions(+), 84 deletions(-) create mode 100644 internal/reviewexec/cli_pause_no_start.go diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index 676d897e4..0482ea3e8 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -4,6 +4,8 @@ A project writer can pause new reviews for a PR before its first review intent or while it has queued work. The pause covers undispatched Hosted and CLI work. It preserves accepted operation identities and their cooldown deadlines, and collection of an already issued review can continue. An optional reason explains the pause. Resuming clears that reason. +When the owned CLI driver observes a pause at its final local check before starting the review process, it can retain the original request using an attempt-bound no-start receipt. It releases the exact unused reservation and keeps the prior attempt as history. Resume takes the ordinary admission path with a new attempt; an issued action or uncertain outcome never uses this automatic path. + Draft eligibility, [round settings](review-round-controls.md), earned taper, channel closure and operation controls remain separate. To resume an individually paused operation, use its [operation control](retained-review-quota-controls.md). Use `GET` and `POST /api/v1/projects/{project_id}/reviews/pulls/{number}/scheduling` to read or update the pause. A write supplies `expected_revision`, `paused` and an optional `reason`, with the normal explicit idempotency key. An unconfigured PR reads as revision zero and unpaused. Keep the original request and key when a mutation result is uncertain. diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index be5b1f53a..b51d69593 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -416,10 +416,18 @@ func untouchedCLIReservation(ctx context.Context, tx *sql.Tx, o Operation, a Att return unused, err } +const unusedCLISettlementEvent = "review.cli_unused_settlement" + +type unusedCLISettlementRecord struct { + OperationID string `json:"operation_id"` + ClaimRevision int64 `json:"claim_revision"` +} + // The driver has finished its exclusively owned preparation without authorizing review. // Release only the original revision-1 reservation and retain the queued request. func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operation, captured Attempt) error { var proposed Attempt + var receiptSequence int64 err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { a, err := readAttempt(ctx, tx, captured.ProjectID, captured.ID) if err != nil { @@ -448,8 +456,23 @@ func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operat if !errors.Is(err, errAllowanceObservationAbsent) { return err } - proposed, err = e.advanceAttempt(ctx, tx, o, a, "held", "automatic_scheduling_unavailable", "") - return err + candidate, err := e.advanceAttempt(ctx, tx, o, a, "held", "automatic_scheduling_unavailable", "") + if err != nil { + return err + } + record := unusedCLISettlementRecord{OperationID: o.ID, ClaimRevision: o.Revision} + if err := core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, + unusedCLISettlementEvent, a.ID, candidate.Revision, record); err != nil { + return err + } + if err := tx.QueryRowContext(ctx, `SELECT last_insert_rowid()`).Scan(&receiptSequence); err != nil { + return err + } + if receiptSequence <= 0 { + return conflict() + } + proposed = candidate + return nil }) // A nonzero proposal means the entire transaction callback completed; // only then can this caller have lost the acknowledgement of a commit. @@ -457,7 +480,7 @@ func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operat // The settlement window may have expired after commit. Give // this exact read-only acknowledgement check its own short window. readCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) - committed := e.unusedCLISettlementCommitted(readCtx, original, captured, proposed) + committed := e.readUnusedCLISettlementReceipt(readCtx, original, captured, proposed, receiptSequence) cancel() if committed { err = nil @@ -469,6 +492,42 @@ func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operat return err } +// Reconcile the exact attempt-local settlement receipt without consulting the +// successor. This is acknowledgement only; it cannot grant new work. +func (e *Engine) readUnusedCLISettlementReceipt(ctx context.Context, original Operation, captured, proposed Attempt, sequence int64) bool { + if sequence <= 0 || original.ProjectID != captured.ProjectID || original.ID != captured.OperationID || original.Channel != "cli" || + captured.State != "preparing" || captured.Revision != 1 || captured.Anchor != nil || captured.Intent != "" || captured.ExternalID != "" { + return false + } + tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return false + } + defer tx.Rollback() + a, err := readAttempt(ctx, tx, captured.ProjectID, captured.ID) + if err != nil || a != proposed || a.State != "held" || a.Revision != 2 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { + return false + } + record := unusedCLISettlementRecord{OperationID: original.ID, ClaimRevision: original.Revision + 1} + var at any + err = tx.QueryRowContext(ctx, `SELECT created_at FROM events WHERE sequence=? AND project_id=? AND event_type=? AND + resource_id=? AND typeof(revision)='integer' AND revision=? AND actor_id=? AND payload_json=?`, + sequence, captured.ProjectID, unusedCLISettlementEvent, captured.ID, a.Revision, original.ActorID, encoded(record)).Scan(&at) + stamp, native := at.(string) + if err != nil || !native || !roundTime(stamp) { + return false + } + var exact bool + err = tx.QueryRowContext(ctx, `SELECT + (SELECT count(*) FROM review_execution_transitions WHERE attempt_id=?)=2 + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=1 AND state='preparing' AND reason='preparing' AND external_id='') + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=2 AND state='held' AND reason='automatic_scheduling_unavailable' AND external_id='') + AND NOT EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=?) + AND NOT EXISTS(SELECT 1 FROM review_cli_preflight WHERE attempt_id=?) + AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, a.ID, a.ID, a.ID, a.ID, a.ID, a.ID).Scan(&exact) + return err == nil && exact +} + // Reconcile only the exact guarded transaction whose acknowledgement was // uncertain. The observations come from one snapshot and cannot grant work. func (e *Engine) unusedCLISettlementCommitted(ctx context.Context, original Operation, captured, proposed Attempt) bool { @@ -600,6 +659,10 @@ func (e *Engine) Advance(ctx context.Context, project, id string, expectedRevisi // advanceAttempt records a transition for the attempt and operation already // checked in this write transaction. func (e *Engine) advanceAttempt(ctx context.Context, tx *sql.Tx, o Operation, a Attempt, state, reason, externalID string) (Attempt, error) { + return e.advanceAttemptWithCLIPause(ctx, tx, o, a, state, reason, externalID, false) +} + +func (e *Engine) advanceAttemptWithCLIPause(ctx context.Context, tx *sql.Tx, o Operation, a Attempt, state, reason, externalID string, cliBeforeStart bool) (Attempt, error) { at, err := attemptRecordingStamp(ctx, tx, o, &a, e.sampleAttemptTime()) if err != nil { return Attempt{}, err @@ -616,6 +679,9 @@ func (e *Engine) advanceAttempt(ctx context.Context, tx *sql.Tx, o Operation, a return Attempt{}, err } operationState, operationAttempt := state, o.AttemptID + if cliBeforeStart { + operationState, operationAttempt = "queued", "" + } // Only an unused preparation may detach and retain the same queued intent. retainQueued := o.Channel == "cli" && reason == cliDraftWait || reason == "pull_scheduling_paused" || reason == "automation_authorization_changed" || reason == "automatic_scheduling_unavailable" if retainQueued && state == "held" && o.State == "preparing" && o.AttemptID == a.ID && a.Anchor == nil && a.Intent == "" && a.ExternalID == "" { diff --git a/internal/reviewexec/cli_draft_wait.go b/internal/reviewexec/cli_draft_wait.go index fbe1a795a..3eb01dcc9 100644 --- a/internal/reviewexec/cli_draft_wait.go +++ b/internal/reviewexec/cli_draft_wait.go @@ -231,6 +231,9 @@ func historicalUnusedPreparationOperation(ctx context.Context, q EvidenceQuery, if matching != 1 { return Operation{}, false, waitUnavailable() } + if scheduling && reason == cliPauseNoStartReason { + return historicalCLIPauseBeforeStart(ctx, q, o, a) + } draft := reason == cliDraftWait if !draft && !(scheduling && (reason == "pull_scheduling_paused" || reason == "automation_authorization_changed" || reason == "automatic_scheduling_unavailable")) { return Operation{}, false, nil diff --git a/internal/reviewexec/cli_pause_no_start.go b/internal/reviewexec/cli_pause_no_start.go new file mode 100644 index 000000000..b61ae0d59 --- /dev/null +++ b/internal/reviewexec/cli_pause_no_start.go @@ -0,0 +1,222 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "sync/atomic" + "time" + + "github.com/benhook1013/FireController/internal/core" +) + +const cliPauseNoStartReason = "pull_scheduling_paused_before_cli_start" +const cliPauseNoStartEvent = "review.cli_pause_before_start" + +type cliPauseNoStart struct { + engine *Engine + attempt Attempt + operation Operation + pauseRevision int64 + consumed atomic.Bool +} + +type cliPauseNoStartRecord struct { + OperationID string `json:"operation_id"` + PauseRevision int64 `json:"pause_revision"` +} + +func (r Result) HasCLIStartRefusal() bool { return r.cliPause != nil } + +// VerifyCLIAction is the owned runtime's final local guard before starting a +// review. A normal scoped pause may prove that this runner never started it. +func (e *Engine) VerifyCLIAction(ctx context.Context, project, id string, rev int64, predecessors ...SourcePlan) (Result, error) { + if ctx == nil || e == nil || e.store == nil || !identifier.MatchString(project) || !identifier.MatchString(id) || rev != 2 { + return Result{}, invalid() + } + var result Result + err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + err := e.verifyAction(ctx, tx, project, id, rev, predecessors) + var refusal *core.Error + if !errors.As(err, &refusal) || refusal.Code != "pull_scheduling_paused" { + return err + } + a, o, err := readCLIPauseNoStart(ctx, tx, project, id) + if err != nil { + return err + } + pause, err := readPullScheduling(ctx, tx, project, o.PullNumber) + if err != nil { + return err + } + if !pause.Paused || pause.Revision < 1 { + return conflict() + } + result.cliPause = &cliPauseNoStart{engine: e, attempt: a, operation: o, pauseRevision: pause.Revision} + return nil + }) + if err != nil { + return Result{}, err + } + return result, nil +} + +func readCLIPauseNoStart(ctx context.Context, tx *sql.Tx, project, id string) (Attempt, Operation, error) { + a, err := readAttempt(ctx, tx, project, id) + if err != nil { + return Attempt{}, Operation{}, err + } + o, err := readOperation(ctx, tx, project, a.OperationID) + if err != nil { + return Attempt{}, Operation{}, err + } + if a.State != "active" || a.Revision != 2 || a.Intent != "" || a.ExternalID != "" || a.Anchor == nil || !validEvidenceAnchor(*a.Anchor) || + o.Channel != "cli" || o.State != "active" || o.AttemptID != a.ID || o.PullNumber != a.Anchor.PullNumber || o.HeadSHA != a.Anchor.CandidateSHA { + return Attempt{}, Operation{}, conflict() + } + record, err := readCLIAllowanceRecord(ctx, tx, o, a) + if err != nil { + return Attempt{}, Operation{}, err + } + if record.Observation.Remaining <= 0 || record.Observation.Anchor != *a.Anchor { + return Attempt{}, Operation{}, conflict() + } + var owned bool + err = tx.QueryRowContext(ctx, `SELECT (SELECT count(*) FROM review_execution_reservations WHERE attempt_id=?)=1 + AND EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=? AND provider=? AND account=? AND repository_id=? AND pull_number=? AND action_class='cli') + AND (SELECT count(*) FROM review_execution_transitions WHERE attempt_id=?)=2 + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=1 AND state='preparing' AND reason='preparing' AND external_id='') + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=2 AND state='active' AND reason='admitted' AND external_id='') + AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, + a.ID, a.ID, a.Provider, a.Account, a.Anchor.RepositoryID, o.PullNumber, a.ID, a.ID, a.ID, a.ID).Scan(&owned) + if err != nil { + return Attempt{}, Operation{}, err + } + if !owned { + return Attempt{}, Operation{}, conflict() + } + return a, o, nil +} + +func sameCLIPauseAttempt(a, b Attempt) bool { + if a.Anchor == nil || b.Anchor == nil || *a.Anchor != *b.Anchor { + return false + } + a.Anchor, b.Anchor = nil, nil + return a == b +} + +func (e *Engine) settleCLIPauseNoStart(ctx context.Context, original Operation, admitted Attempt, w *cliPauseNoStart) error { + if w.engine != e || !sameCLIPauseAttempt(admitted, w.attempt) || !w.consumed.CompareAndSwap(false, true) { + return conflict() + } + local, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + defer cancel() + err := e.store.BackgroundWrite(local, func(ctx context.Context, tx *sql.Tx) error { + a, o, err := readCLIPauseNoStart(ctx, tx, admitted.ProjectID, admitted.ID) + if err != nil { + return err + } + claim := o + claim.State = "preparing" + if !sameCLIPauseAttempt(a, w.attempt) || !sameCLIClaim(original, claim, a, original.Revision+2) || + !sameCLIClaim(w.operation, claim, a, w.operation.Revision) || !sameCLIWait(original.Wait, o.Wait) || !sameCLIWait(w.operation.Wait, o.Wait) { + return conflict() + } + if err = core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, cliPauseNoStartEvent, a.ID, a.Revision+1, cliPauseNoStartRecord{OperationID: o.ID, PauseRevision: w.pauseRevision}); err != nil { + return err + } + _, err = e.advanceAttemptWithCLIPause(ctx, tx, o, a, "failed", cliPauseNoStartReason, "", true) + return err + }) + if err == nil { + e.notifyOperation(admitted.OperationID) + } + return err +} + +func validateCLIPauseNoStartRecord(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) error { + var body sql.NullString + var actor, revision, eventType any + var count int64 + err := q.QueryRowContext(ctx, `SELECT CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END, + actor_id,revision,event_type,count(*) OVER() FROM events WHERE project_id=? AND resource_id=? AND + (event_type=? OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)=?))`, o.ProjectID, a.ID, cliPauseNoStartEvent, cliPauseNoStartEvent).Scan(&body, &actor, &revision, &eventType, &count) + if errors.Is(err, sql.ErrNoRows) { + return waitUnavailable() + } + if err != nil { + return err + } + var proof cliPauseNoStartRecord + if count != 1 || actor != o.ActorID || revision != a.Revision || eventType != cliPauseNoStartEvent || !body.Valid || + json.Unmarshal([]byte(body.String), &proof) != nil || encoded(proof) != body.String || + proof.OperationID != o.ID || proof.PauseRevision < 1 { + return waitUnavailable() + } + return nil +} + +func historicalCLIPauseBeforeStart(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (Operation, bool, error) { + if o.Channel != "cli" || a.ProjectID != o.ProjectID || a.OperationID != o.ID || a.ID == o.AttemptID || + a.State != "failed" || a.Revision != 3 || a.Anchor == nil || !validEvidenceAnchor(*a.Anchor) || + a.Anchor.PullNumber != o.PullNumber || a.Anchor.CandidateSHA != o.HeadSHA || a.Intent != "" || a.ExternalID != "" { + return Operation{}, false, waitUnavailable() + } + if err := validateCLIPauseNoStartRecord(ctx, q, o, a); err != nil { + return Operation{}, false, err + } + var occupied bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=?) + OR EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, a.ID, a.ID).Scan(&occupied); err != nil { + return Operation{}, false, err + } + if occupied { + return Operation{}, false, waitUnavailable() + } + rows, err := q.QueryContext(ctx, `SELECT revision,state,reason,external_id,created_at FROM review_execution_transitions WHERE attempt_id=? ORDER BY revision LIMIT 4`, a.ID) + if err != nil { + return Operation{}, false, err + } + defer rows.Close() + states := [...]string{"preparing", "active", "failed"} + reasons := [...]string{"preparing", "admitted", cliPauseNoStartReason} + var seen int + var previous time.Time + for rows.Next() { + var revision, state, reason, external, stamp any + if err := rows.Scan(&revision, &state, &reason, &external, &stamp); err != nil { + return Operation{}, false, err + } + text, ok := stamp.(string) + at, valid := attemptRecordedTime(text) + if seen >= len(states) || revision != int64(seen+1) || state != states[seen] || reason != reasons[seen] || + external != "" || !ok || !valid || at.Before(previous) { + return Operation{}, false, waitUnavailable() + } + seen++ + previous = at + } + if err := rows.Err(); err != nil { + return Operation{}, false, err + } + if err := rows.Close(); err != nil { + return Operation{}, false, err + } + if seen != len(states) { + return Operation{}, false, waitUnavailable() + } + o.AttemptID, o.State, o.Reason, o.Wait = a.ID, "failed", cliPauseNoStartReason, nil + allowance, err := readCLIAllowanceRecord(ctx, q, o, a) + if errors.Is(err, errAllowanceObservationAbsent) || storedAllowanceUnavailable(err) { + return Operation{}, false, waitUnavailable() + } + if err != nil { + return Operation{}, false, err + } + if allowance.Observation.Remaining <= 0 || allowance.Observation.Anchor != *a.Anchor { + return Operation{}, false, waitUnavailable() + } + return o, true, nil +} diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 5edd9bbec..e12d2c121 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -82,6 +82,13 @@ ORDER BY q.key,o.created_at,o.id`, string(queue), position, o.ProjectID, o.Chann } valid, err := e.hostedPriorityBinding(ctx, tx, earlier) if err != nil { + // A proved conflict affects this earlier queued Hosted intent only. + // Independent admission and dependency checks still run normally. + var conflict *localSelectionCustodyConflict + if o.Channel == "hosted" && errors.As(err, &conflict) && + conflict.project == earlier.ProjectID && conflict.operation == earlier.ID { + continue + } return nil, err } if valid { diff --git a/internal/reviewexec/hosted_wait_validation.go b/internal/reviewexec/hosted_wait_validation.go index 53b67effb..ec9cb5434 100644 --- a/internal/reviewexec/hosted_wait_validation.go +++ b/internal/reviewexec/hosted_wait_validation.go @@ -26,7 +26,14 @@ func ValidateOperationWaitsSnapshot(ctx context.Context, tx *sql.Tx) error { EXISTS(SELECT 1 FROM review_execution_transitions t WHERE t.attempt_id=a.id AND t.reason IN ('pull_scheduling_paused','automation_authorization_changed','automatic_scheduling_unavailable')) OR (a.state='held' AND a.revision=2 AND a.anchor_json='null' AND a.intent='' AND a.external_id='') ) - ORDER BY 2`, cliDraftWait, cliDraftWait) + UNION SELECT m.project_id,coalesce(a.operation_id,'') FROM events m + LEFT JOIN review_execution_attempts a ON a.project_id=m.project_id AND a.id=m.resource_id + WHERE m.event_type=? OR (typeof(m.event_type)='blob' AND CAST(m.event_type AS TEXT)=?) + UNION SELECT a.project_id,a.operation_id FROM review_execution_attempts a + LEFT JOIN review_operations o ON o.id=a.operation_id + JOIN review_execution_transitions t ON t.attempt_id=a.id AND t.revision=a.revision + WHERE o.attempt_id IS NOT a.id AND t.reason=? + ORDER BY 2`, cliDraftWait, cliDraftWait, cliPauseNoStartEvent, cliPauseNoStartEvent, cliPauseNoStartReason) if err != nil { return err } diff --git a/internal/reviewexec/live_cli_preparation_settlement_test.go b/internal/reviewexec/live_cli_preparation_settlement_test.go index 29c2e565b..e7a38ca31 100644 --- a/internal/reviewexec/live_cli_preparation_settlement_test.go +++ b/internal/reviewexec/live_cli_preparation_settlement_test.go @@ -177,5 +177,26 @@ func TestUnusedCLIPreparationConfirmsExactCommittedSettlement(t *testing.T) { 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") + } + 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/run_selection.go b/internal/reviewexec/run_selection.go index 9037dc76e..e78df5929 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -247,15 +247,17 @@ func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configurati WHERE p.project_id=o.project_id AND p.pull_number=o.pull_number AND typeof(p.paused)='integer' AND p.paused=1)))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { return c, 0, "", err } - if !busy && r.Channel == "hosted" { + var unprovedPause bool + if r.Channel == "hosted" { // The SQL predicate is only a shortlist. A queued operation // may yield its turn only on a fully validated pull pause. - busy, err = unprovedQueuedHostedPause(ctx, tx, r.ProjectID) + unprovedPause, err = unprovedQueuedHostedPause(ctx, tx, r.ProjectID) if err != nil { return c, 0, "", err } + busy = busy || unprovedPause } - if busy { + if busy && !unprovedPause { var automatic bool if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id=?)`, r.ProjectID, r.ID).Scan(&automatic); err != nil { return c, 0, "", err @@ -629,6 +631,17 @@ func quarantineNativeSelection(ctx context.Context, tx *sql.Tx, project, id any, if inconsistent { return false, &unprovedSelectionCustodyError{runUnavailable()} } + // A conflicting retained diagnostic cannot prove this row's custody. + // Detect only these known keys before writing, so recovery can isolate + // this row without treating a database failure as a local refusal. + var conflict bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selection_quarantine + WHERE selection_id=? OR (project_id=? AND original_operation_id=?))`, sid, pid, op).Scan(&conflict); err != nil { + return false, err + } + if conflict { + return false, &unprovedSelectionCustodyError{runUnavailable()} + } // Preserve the observed exact link without copying child or credential // state. The outer transaction rolls this back if the hold fails. if _, err := tx.ExecContext(ctx, `INSERT INTO review_selection_quarantine diff --git a/internal/reviewexec/run_selection_schema.go b/internal/reviewexec/run_selection_schema.go index d5862c42f..4dfaa4eaa 100644 --- a/internal/reviewexec/run_selection_schema.go +++ b/internal/reviewexec/run_selection_schema.go @@ -38,10 +38,19 @@ const selectionQuarantineTableSQL = `CREATE TABLE review_selection_quarantine( const linkedSelectionCustodyHeld = "selection_custody_quarantined" +// localSelectionCustodyConflict classifies only a proved, same-project +// conflict. Its wrapped refusal remains unchanged for operation admission. +type localSelectionCustodyConflict struct { + error + project, operation string +} + +func (e *localSelectionCustodyConflict) Unwrap() error { return e.error } + // requireUnquarantinedSelectionLink only denies work. The custody row cannot // replace active selection attribution or authorize a new provider action. func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, project, operation string) error { - var proved bool + var proved, hasLive, hasLocalLive bool err := q.QueryRowContext(ctx, `SELECT COALESCE(s.project_id=d.project_id AND s.state='held' AND s.reason='linked_selection_quarantined' AND s.operation_id IS NULL AND typeof(d.observed_revision)='integer' AND d.observed_revision>0 AND @@ -51,15 +60,16 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro (o.id IS NULL OR (o.project_id=s.project_id AND o.actor_id=s.actor_id AND o.worker_id=s.worker_id AND o.channel=s.channel AND o.configuration_revision=s.configuration_revision AND o.policy_revision=s.policy_revision AND o.capability_fingerprint=s.capability_fingerprint AND (s.expected_pull_number=0 OR s.expected_pull_number=o.pull_number))) - AND NOT EXISTS(SELECT 1 FROM review_selections live WHERE live.operation_id=d.original_operation_id) - AND NOT EXISTS(SELECT 1 FROM review_automatic_selections a WHERE a.selection_id=s.id AND + AND NOT EXISTS(SELECT 1 FROM review_automatic_selections a WHERE a.selection_id=s.id AND (a.project_id<>s.project_id OR a.actor_id<>s.actor_id OR a.worker_id<>s.worker_id OR typeof(a.pull_number)<>'integer' OR a.pull_number<0 OR a.pull_number>2147483647 OR (a.pull_number<>0 AND (o.id IS NULL OR o.pull_number<>a.pull_number)) OR - (a.pull_number=0 AND a.pull_basis_sha256<>''))), 0) + (a.pull_number=0 AND a.pull_basis_sha256<>''))), 0), + EXISTS(SELECT 1 FROM review_selections live WHERE live.operation_id=d.original_operation_id), + EXISTS(SELECT 1 FROM review_selections live WHERE live.operation_id=d.original_operation_id AND live.project_id=d.project_id) FROM review_selection_quarantine d LEFT JOIN review_selections s ON s.id=d.selection_id LEFT JOIN review_operations o ON o.id=d.original_operation_id - WHERE d.project_id=? AND d.original_operation_id=?`, project, operation).Scan(&proved) + WHERE d.project_id=? AND d.original_operation_id=?`, project, operation).Scan(&proved, &hasLive, &hasLocalLive) if errors.Is(err, sql.ErrNoRows) { // A detached marker without its diagnostic has lost the only // exact child link. Do not infer ordinary authority for any @@ -84,6 +94,12 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro // An unknown custody row cannot establish ordinary ineligibility. return runUnavailable() } + if hasLive { + if hasLocalLive { + return &localSelectionCustodyConflict{error: runUnavailable(), project: project, operation: operation} + } + return runUnavailable() + } return automaticProjectStateFailure(linkedSelectionCustodyHeld, "This review operation is held for selection custody recovery.", 403) } diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 9f85310b1..029f73e8e 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -242,36 +242,15 @@ func readAutomaticPullSchedulingRevisionsBound(ctx context.Context, tx *sql.Tx, return revisions, nil } -// Read the exact round grants included in a source-held choice's pull basis. +// Read the exact round grants included in a source choice's pull basis. func readAutomaticGrantRevisions(ctx context.Context, tx *sql.Tx, project, channel string, pulls []int64) ([]int64, error) { revisions := make([]int64, 0, len(pulls)) for _, pull := range pulls { - // Keep a position for a provably paused pull, without consulting - // its grant. The caller separately compares the full pause basis. - pause, err := readPullScheduling(ctx, tx, project, pull) - if err != nil { - var local *pullSchedulingStateError - if !errors.As(err, &local) || local.project != project || local.pull != pull { - return nil, err - } - // Unreadable local pause state is not an unpaused grant input. - revisions = append(revisions, -3) - continue - } else if pause.Paused { - revisions = append(revisions, -2) - continue - } - var native any - err = tx.QueryRowContext(ctx, `SELECT grant_revision FROM review_round_controls WHERE project_id=? AND channel=? AND pull_number=?`, project, channel, pull).Scan(&native) - if errors.Is(err, sql.ErrNoRows) { - revisions = append(revisions, -1) - continue - } + revision, readable, err := automaticGrantRevision(ctx, tx, project, channel, pull) if err != nil { return nil, err } - revision, ok := native.(int64) - if !ok || revision < 0 { + if !readable { return nil, schedulingUnavailable() } revisions = append(revisions, revision) @@ -279,6 +258,30 @@ func readAutomaticGrantRevisions(ctx context.Context, tx *sql.Tx, project, chann return revisions, nil } +func automaticGrantRevision(ctx context.Context, tx *sql.Tx, project, channel string, pull int64) (int64, bool, error) { + pause, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + var local *pullSchedulingStateError + if !errors.As(err, &local) || local.project != project || local.pull != pull { + return 0, false, err + } + return -3, true, nil + } + if pause.Paused { + return -2, true, nil + } + var native any + err = tx.QueryRowContext(ctx, `SELECT grant_revision FROM review_round_controls WHERE project_id=? AND channel=? AND pull_number=?`, project, channel, pull).Scan(&native) + if errors.Is(err, sql.ErrNoRows) { + return -1, true, nil + } + if err != nil { + return 0, false, err + } + revision, ok := native.(int64) + return revision, ok && revision >= 0, nil +} + // The route writer atomically journals every route revision with its // projection. A project-scoped watermark also covers routes on stack parents // discovered later during source I/O; it never includes another project. @@ -295,6 +298,7 @@ func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configurati func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (result runChoice, resultErr error) { var automaticQueueLimit *int + var grantBlocked bool var basisRevision, routeSequence int64 var pullScheduling, grantRevisions []int64 @@ -304,6 +308,10 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 result.automaticPullScheduling = pullScheduling result.automaticGrantRevisions = grantRevisions result.automaticRouteSequence = routeSequence + if grantBlocked && resultErr == nil && result.state == "empty" { + result.state = "held" + result.reason, result.sourceReason = "automatic_scheduling_unavailable", "automatic_scheduling_unavailable" + } }() // Bound source work before metadata lookahead. Local suppression still // rechecks the live prefix at admission if queued work changes afterward. @@ -311,6 +319,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 err := retryRunSelectionRead(ctx, func() error { // An expired snapshot must not shorten a later retry's input. limit, automatic, basisRevision = len(c.Queue), false, 0 + grantBlocked = false pullScheduling, grantRevisions = nil, nil routeSequence = 0 return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { @@ -322,7 +331,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 if !automatic { return nil } - limit, err = e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + limit, grantBlocked, err = e.automaticQueuedPrefixBounds(ctx, tx, r.ProjectID, c, r.Channel) if err != nil { return err } @@ -822,19 +831,39 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat routeSequence, resultErr = automaticRouteSequence(ctx, tx, r.ProjectID) settle = resultErr == nil && routeSequence == choice.automaticRouteSequence } - if settle && pull == 0 { + if settle { var revisions []int64 // A newly unreadable row must roll back the provisional // front frame; it is not equivalent to an ordinary revision change. revisions, resultErr = readAutomaticPullSchedulingRevisionsBound(ctx, tx, r.ProjectID, boundPrefix, true, choice.automaticPullScheduling) settle = resultErr == nil && slices.Equal(revisions, choice.automaticPullScheduling) - if settle && choice.sourceReason != "" { + if settle && (pull > 0 || choice.sourceReason != "") { grants, err := readAutomaticGrantRevisions(ctx, tx, r.ProjectID, r.Channel, boundPrefix) resultErr = err settle = err == nil && slices.Equal(grants, choice.automaticGrantRevisions) } } } + if settle && pull > 0 { + index := slices.IndexFunc(choice.prefix, func(plan SourcePlan) bool { return plan.Pull.Number == pull }) + settle = index >= 0 && choice.prefix[index].Pull.HeadSHA == choice.head + if settle { + evaluated := choice.prefix[index].Pull + retained, err := currentReviewPull(ctx, tx, r.ProjectID, pull) + switch { + case missingCurrentPull(err): + // A new queue entry may not have a workspace projection yet. + // Disappearance of a previously pinned entry is a drift. + _, pinned := metadataPins[pull] + settle = !pinned + case err != nil: + resultErr, settle = err, false + default: + settle = retained.HeadSHA == evaluated.HeadSHA && + retained.BaseSHA == evaluated.BaseSHA && retained.BaseRef == evaluated.BaseRef + } + } + } // A source hold did not evaluate the live workspace facts // that settlement would hash. Keep its accepted basis. if settle && !(pull == 0 && choice.sourceReason != "") { @@ -886,6 +915,21 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return updateRun(ctx, tx, current, "held", "selection_changed", "") } boundPrefix = c.Queue[:limit] + if current.Channel == "hosted" && current.Revision >= 4 && choice.state == "selected" { + initial, err := automaticSourceInitialRead(ctx, tx, current) + if err != nil { + return err + } + if !initial { + revisions, err := readAutomaticPullSchedulingRevisionsBound(ctx, tx, r.ProjectID, boundPrefix, true, choice.automaticPullScheduling) + if err != nil { + return err + } + if !slices.Equal(revisions, choice.automaticPullScheduling) { + return updateRun(ctx, tx, current, "held", "selection_changed", "") + } + } + } } if err = publishSourcePlans(ctx, tx, core.Scope{ProjectID: current.ProjectID, PrincipalID: current.ActorID, WorkerID: current.WorkerID}, repo, metadataPins, choice.prefix); err != nil { return err diff --git a/internal/reviewexec/scheduling_authority.go b/internal/reviewexec/scheduling_authority.go index 431541166..9fc1b08b4 100644 --- a/internal/reviewexec/scheduling_authority.go +++ b/internal/reviewexec/scheduling_authority.go @@ -36,9 +36,8 @@ func schedulingAuthorityContinuity(ctx context.Context, tx *sql.Tx, project, act ) SELECT w.resource_id,w.actor_id,w.revision,w.sequence, CASE WHEN typeof(w.payload_json)='text' AND length(CAST(w.payload_json AS BLOB))<=4096 THEN w.payload_json END, - u.body - FROM events w JOIN settings u ON u.resource_id=w.resource_id AND u.revision=w.revision - AND u.copies=1 AND typeof(u.actor_id)='text' AND u.actor_id=w.actor_id AND u.sequence len(c.Queue) { + return 0, false, schedulingUnavailable() + } + if limit == 0 { + return 0, false, nil + } + queue, err := json.Marshal(c.Queue[:limit]) + if err != nil { + return 0, false, err + } + rows, err := tx.QueryContext(ctx, `SELECT q.key,g.pull_number FROM json_each(?) q + JOIN review_round_controls g ON g.pull_number=q.value + WHERE g.project_id=? AND g.channel=? AND (typeof(g.grant_revision)<>'integer' OR g.grant_revision<0) + ORDER BY q.key`, string(queue), project, channel) + if err != nil { + return 0, false, err + } + defer rows.Close() + for rows.Next() { + var i int + var pull int64 + if err := rows.Scan(&i, &pull); err != nil { + return 0, false, err + } + _, readable, err := automaticGrantRevision(ctx, tx, project, channel, pull) + if err != nil { + return 0, false, err + } + if !readable { + if i < 0 || i >= limit || c.Queue[i] != pull { + return 0, false, schedulingUnavailable() + } + return i, true, nil + } + } + if err := rows.Err(); err != nil { + return 0, false, err + } + return limit, false, rows.Close() +} + +func (e *Engine) automaticQueuedOperationPrefixChannel(ctx context.Context, tx *sql.Tx, project string, c Configuration, channel string) (int, error) { queue, err := json.Marshal(c.Queue) if err != nil { return 0, err diff --git a/internal/reviewexec/scheduling_boundary_compatibility_test.go b/internal/reviewexec/scheduling_boundary_compatibility_test.go index 28f09700d..de90d7763 100644 --- a/internal/reviewexec/scheduling_boundary_compatibility_test.go +++ b/internal/reviewexec/scheduling_boundary_compatibility_test.go @@ -20,12 +20,29 @@ func TestSchedulingBoundaryExistingChildAndUnselectedOwnership(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { tx := schedulingEventSnapshotFixture(t) - const settings = `{"automatic_hosted":true}` - if _, 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',?), - ('test-project','test-project','review.scheduling_updated',2,?,?), - ('test-project','test-project','review.scheduling_updated',3,'test-actor',?)`, settings, tc.intermediate, settings, settings); err != nil { - t.Fatal(err) + const settings = `{"automatic_hosted":true,"automatic_cli":false,"hosted_basis_revision":1,"cli_basis_revision":1}` + const insert = `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json,created_at) VALUES ('test-project','test-project',?,?,?,?,?)` + at := stamp() + for i, actor := range []string{"test-actor", tc.intermediate, "test-actor"} { + revision := int64(i + 1) + generation := int64(1) + if tc.intermediate != "test-actor" { + generation = revision + } + if _, err := tx.ExecContext(t.Context(), insert, "review.scheduling_updated", revision, actor, settings, at); err != nil { + t.Fatal(err) + } + if _, err := tx.ExecContext(t.Context(), insert, schedulingAuthorityBoundEvent, revision, actor, encoded(schedulingAuthorityPayload{Generation: generation}), at); err != nil { + t.Fatal(err) + } + } + if tc.intermediate == "test-actor" { + for _, stable := range []bool{false, true} { + got, err := schedulingAuthorityContinuity(t.Context(), tx, "test-project", "test-actor", 1, 3, stable) + if err != nil || got != 1 { + t.Fatalf("canonical authority continuity generation=%d err=%v", got, err) + } + } } current := schedulingRecord{Scheduling: Scheduling{ProjectID: "test-project", Revision: 3, AutomaticHosted: true}, actor: "test-actor"} r := Run{ProjectID: "test-project", Channel: "hosted", State: "selecting"} diff --git a/internal/reviewexec/scheduling_selected_basis_guard_test.go b/internal/reviewexec/scheduling_selected_basis_guard_test.go index afb72d7b8..172523221 100644 --- a/internal/reviewexec/scheduling_selected_basis_guard_test.go +++ b/internal/reviewexec/scheduling_selected_basis_guard_test.go @@ -3,19 +3,19 @@ package reviewexec import ( "context" "database/sql" + "net/http" "strings" "testing" "github.com/benhook1013/FireController/internal/core" "github.com/benhook1013/FireController/internal/reviewprovider" + "github.com/benhook1013/FireController/internal/reviews" ) func TestSelectedChildDoesNotSettleRearmedLaneBasis(t *testing.T) { - for _, rearm := range []bool{false, true} { - name := "stable-basis" - if rearm { - name = "rearmed-during-valid-read" - } + for _, name := range []string{"stable-basis", "rearmed-during-valid-read", "source-head-advanced-during-read"} { + rearm := name == "rearmed-during-valid-read" + drift := name == "source-head-advanced-during-read" t.Run(name, func(t *testing.T) { f := schedulingFixtureWithQueue(t, []int64{2}) scope := selectionScope(t, f, attemptProject, f.admin, "write") @@ -45,8 +45,35 @@ func TestSelectedChildDoesNotSettleRearmedLaneBasis(t *testing.T) { if err != nil { t.Fatal(err) } + advanced := false + newHead := strings.Repeat("f", 40) + if drift { + reviews.Register(f.handler.(*http.ServeMux), f.store) + initial := projectionPull(2) + rr := f.request(http.MethodPost, "/api/v1/projects/"+attemptProject+"/reviews/observations", f.admin, "initial-source-drift", encoded(reviews.ObservationRequest{ExpectedRevision: adjudicationRevision(0), RepositoryID: 801, Source: "source-drift-fixture", ObservedAt: stamp(), Queue: []reviews.PullInput{initial}, Retired: []reviews.RetiredPull{}})) + if rr.Code != http.StatusCreated { + t.Fatal(rr.Code, rr.Body.String()) + } + } edited := false reader := &refreshTestReader{repository: func(ctx context.Context, id int64) (reviewprovider.Repository, error) { + if drift && !advanced { + err := f.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + pins, err := reviews.PinSourceMetadata(ctx, tx, scope.ProjectID, []int64{2}) + if err != nil { + return err + } + next := projectionPull(2) + next.HeadSHA = newHead + next.CIState, next.Mergeability, next.MergeStateStatus, next.Complete = "", "", "", false + _, err = reviews.PublishSourceMetadata(ctx, tx, scope, id, pins, []reviews.PullInput{next}) + return err + }) + if err != nil { + return reviewprovider.Repository{}, err + } + advanced = true + } if rearm && !edited { err := f.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { if _, err := tx.ExecContext(ctx, `UPDATE review_scheduling SET revision=2, updated_at=? WHERE project_id=? AND revision=1`, stamp(), scope.ProjectID); err != nil { @@ -66,7 +93,7 @@ func TestSelectedChildDoesNotSettleRearmedLaneBasis(t *testing.T) { }} selectionNext(t, f, reader) got := selectionRead(t, f, receipt.ID) - if edited != rearm || got.State != "selected" || got.OperationID == "" { + if edited != rearm || (!drift || got.State != "held" || got.Reason != "selection_changed") && (got.State != "selected" || got.OperationID == "") { t.Fatalf("legitimate selection did not keep its linked child: rearm=%v callback=%v got=%+v", rearm, edited, got) } var settled, pullBasis string @@ -74,9 +101,23 @@ func TestSelectedChildDoesNotSettleRearmedLaneBasis(t *testing.T) { if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256,pull_number,pull_basis_sha256 FROM review_automatic_selections WHERE selection_id=? AND project_id=?`, receipt.ID, scope.ProjectID).Scan(&settled, &pull, &pullBasis); err != nil { t.Fatal(err) } - if rearm { + if drift { + if !advanced { + t.Fatal("fixture did not publish current head during source acquisition") + } + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + current, err := currentReviewPull(ctx, tx, scope.ProjectID, 2) + if err == nil && current.HeadSHA != newHead { + t.Fatalf("current head = %s; want %s", current.HeadSHA, newHead) + } + return err + }); err != nil { + t.Fatal(err) + } + } + if rearm || drift { if settled != "" || pull != 0 || pullBasis != "" { - t.Fatalf("old selection incorrectly marked a rearmed lane served") + t.Fatalf("old selection incorrectly marked an unevaluated basis served") } } else if !hash.MatchString(settled) || pull != 2 || !hash.MatchString(pullBasis) { t.Fatalf("stable selection did not settle its own lane/pull basis") diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index b452729c1..25efe35e7 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -248,7 +248,35 @@ const orphanPullSchedulingSelectSQL = ` CASE WHEN typeof(e.actor_id)='text' AND length(CAST(e.actor_id AS BLOB))<=128 THEN e.actor_id END, CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END` + latestOrphanPullResumesSQL +// Validate the entire orphan history before selecting its latest resume. +// Materializing a control must not hide earlier unreadable event timestamps. +func validateOrphanPullSchedulingTimes(ctx context.Context, tx *sql.Tx, scopeClause string, args ...any) error { + rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+scopeClause+`) + SELECT CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END + FROM orphan_history o JOIN events e ON e.sequence=o.sequence`, args...) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var at sql.NullString + if err := rows.Scan(&at); err != nil { + return err + } + if !at.Valid || !roundTime(at.String) { + return schedulingUnavailable() + } + } + if err := rows.Err(); err != nil { + return err + } + return rows.Close() +} + func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { + if err := validateOrphanPullSchedulingTimes(ctx, tx, ""); err != nil { + return err + } rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+orphanPullSchedulingRankSQL+orphanPullSchedulingSelectSQL) if err != nil { return err @@ -299,9 +327,13 @@ func editablePullScheduling(ctx context.Context, tx *sql.Tx, project string, pul if err != nil || current.Revision != 0 { return current, err } - orphan, err := scanOrphanPullResume(tx.QueryRowContext(ctx, orphanPullSchedulingSQL+` - AND e.project_id=? AND (e.resource_id=? OR (typeof(e.resource_id)='blob' AND CAST(e.resource_id AS TEXT)=?))`+ - orphanPullSchedulingRankSQL+orphanPullSchedulingSelectSQL, project, strconv.FormatInt(pull, 10), strconv.FormatInt(pull, 10))) + const scopeClause = ` AND e.project_id=? AND (e.resource_id=? OR (typeof(e.resource_id)='blob' AND CAST(e.resource_id AS TEXT)=?))` + pullID := strconv.FormatInt(pull, 10) + if err := validateOrphanPullSchedulingTimes(ctx, tx, scopeClause, project, pullID, pullID); err != nil { + return current, err + } + orphan, err := scanOrphanPullResume(tx.QueryRowContext(ctx, orphanPullSchedulingSQL+scopeClause+ + orphanPullSchedulingRankSQL+orphanPullSchedulingSelectSQL, project, pullID, pullID)) if errors.Is(err, sql.ErrNoRows) { return current, nil } diff --git a/internal/reviewexec/scheduling_snapshot_event_integrity_test.go b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go index 8358123fa..d400fddf2 100644 --- a/internal/reviewexec/scheduling_snapshot_event_integrity_test.go +++ b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go @@ -1,7 +1,9 @@ package reviewexec import ( + "context" "database/sql" + "slices" "strings" "testing" ) @@ -62,12 +64,13 @@ func TestSchedulingSnapshotRequiresNativeEventRevision(t *testing.T) { }{{"integer", int64(1), true}, {"real", float64(1), 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','2','review.pull_scheduling_updated',?,'test-actor','{"pull_number":2,"paused":true}')`, tc.revision) + at := stamp() + _, err := tx.ExecContext(t.Context(), `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json,created_at) + VALUES ('test-project','2','review.pull_scheduling_updated',?,'test-actor','{"pull_number":2,"paused":true}',?)`, tc.revision, at) if err != nil { t.Fatal(err) } - if _, err := tx.ExecContext(t.Context(), `INSERT INTO review_pull_scheduling VALUES ('test-project',2,1,1,'','test-actor',?)`, stamp()); err != nil { + if _, err := tx.ExecContext(t.Context(), `INSERT INTO review_pull_scheduling VALUES ('test-project',2,1,1,'','test-actor',?)`, at); err != nil { t.Fatal(err) } err = ValidateSchedulingSnapshot(t.Context(), tx) @@ -86,16 +89,17 @@ func TestSchedulingSnapshotRequiresNativeEventRevision(t *testing.T) { // one's newest event must remain attached to its own represented control. func TestSchedulingSnapshotPullEventStreamKeepsProjectIdentity(t *testing.T) { tx := schedulingEventSnapshotFixture(t) + at := stamp() if _, err := tx.ExecContext(t.Context(), `INSERT INTO review_pull_scheduling VALUES ('test-project',2,2,0,'','test-actor',?), - ('other-project',2,1,1,'','other-actor',?)`, stamp(), stamp()); err != nil { + ('other-project',2,1,1,'','other-actor',?)`, at, at); err != nil { t.Fatal(err) } - if _, err := tx.ExecContext(t.Context(), `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json) VALUES - ('test-project','2','review.pull_scheduling_updated',1,'test-actor','{"pull_number":2,"paused":true}'), - ('other-project','2','review.pull_scheduling_updated',1,'other-actor','{"pull_number":2,"paused":true}'), - ('test-project','2','review.pull_scheduling_updated',2,'test-actor','{"pull_number":2,"paused":false}'), - ('other-project','2','ordinary.event',9,'other-actor','{}')`); err != nil { + if _, err := tx.ExecContext(t.Context(), `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json,created_at) VALUES + ('test-project','2','review.pull_scheduling_updated',1,'test-actor','{"pull_number":2,"paused":true}',?), + ('other-project','2','review.pull_scheduling_updated',1,'other-actor','{"pull_number":2,"paused":true}',?), + ('test-project','2','review.pull_scheduling_updated',2,'test-actor','{"pull_number":2,"paused":false}',?), + ('other-project','2','ordinary.event',9,'other-actor','{}',?)`, at, at, at, at); err != nil { t.Fatal(err) } if err := ValidateSchedulingSnapshot(t.Context(), tx); err != nil { @@ -212,3 +216,31 @@ func TestOrphanResumeReadsRevisionWithSQLiteIntegerAffinity(t *testing.T) { } attemptCode(t, validateOrphanPullSchedulingEvent(tx.QueryRowContext(t.Context(), query, stamp(), 2)), "storage_unavailable") } + +func TestAutomaticGrantPrefixPreservesOrdinaryGrantsAndPausedOmission(t *testing.T) { + f := schedulingFixture(t) + roundGrant(t, f, 2, "hosted", 0, 2, 4, "ordinary-hosted-grant") + cfg := Configuration{Queue: []int64{2, 4}} + check := func(hosted, cli []int64) { + t.Helper() + err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + for channel, want := range map[string][]int64{"hosted": hosted, "cli": cli} { + limit, blocked, err := f.e.automaticQueuedPrefixBounds(ctx, tx, attemptProject, cfg, channel) + if err != nil || blocked || limit != len(cfg.Queue) { + t.Fatalf("prefix %s = %d,%v,%v", channel, limit, blocked, err) + } + got, err := readAutomaticGrantRevisions(ctx, tx, attemptProject, channel, cfg.Queue[:limit]) + if err != nil || !slices.Equal(got, want) { + t.Fatalf("%s grant revisions = %v,%v; want %v", channel, got, err, want) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + check([]int64{1, -1}, []int64{-1, -1}) + schedulingPause(t, f, 2, 0, true) + check([]int64{-2, -1}, []int64{-2, -1}) +} diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index 1f8cb888e..bcea5b603 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -92,12 +92,13 @@ func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, e } var count, distinct, first, last, invalid int64 err = tx.QueryRowContext(ctx, `WITH transitions AS ( - SELECT revision,sequence,actor_id,payload_json,lag(sequence) OVER (ORDER BY revision,sequence) AS previous_sequence - FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' + SELECT revision,sequence,actor_id,payload_json,event_type,lag(sequence) OVER (ORDER BY revision,sequence) AS previous_sequence + FROM events WHERE project_id=? AND resource_id=? AND (event_type='review.selection_updated' + OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.selection_updated')) ) SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( CASE WHEN typeof(revision)='integer' AND typeof(sequence)='integer' AND sequence>? AND - typeof(actor_id)='text' AND actor_id=? AND + typeof(actor_id)='text' AND actor_id=? AND typeof(event_type)='text' AND (previous_sequence IS NULL OR sequence>previous_sequence) AND typeof(payload_json)='text' THEN CASE WHEN payload_json=json_object('reason','','state',CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END) AND (revision<>? OR payload_json=json_object('reason','','state',?)) THEN 0 ELSE 1 END diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 91ab7a6d8..b006690b4 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -117,6 +117,7 @@ func settleOwnedCLIWithinWindows(ctx context.Context, settle func(context.Contex // returning a proven terminal result; unresolved outcomes return uncertain. type Result struct { State, Reason, ExternalID string + cliPause *cliPauseNoStart } // Driver is an in-process operator-selected adapter, never a client-provided @@ -994,6 +995,12 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri cancel() progressMu.Lock() defer progressMu.Unlock() + if err == nil && result.cliPause != nil { + if e.settleCLIPauseNoStart(ctx, o, a, result.cliPause) != nil { + return persistenceFailure() + } + return nil + } if err != nil { result = Result{State: "uncertain", Reason: "dispatch_interrupted", ExternalID: result.ExternalID} } diff --git a/internal/reviewexec/wait_deadline.go b/internal/reviewexec/wait_deadline.go index f5ae166b7..597eb1480 100644 --- a/internal/reviewexec/wait_deadline.go +++ b/internal/reviewexec/wait_deadline.go @@ -150,6 +150,11 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba cancelled = append(cancelled, id) continue } + if o.Channel == "cli" && state.Valid && retainedReason.Valid && state.String == "failed" && + attemptState == "failed" && retainedReason.String == cliPauseNoStartReason { + detachedHolds = append(detachedHolds, id) + continue + } if !state.Valid || !retainedReason.Valid || state.String != "held" || attemptState != "held" { return waitUnavailable() } diff --git a/internal/reviewprocess/process.go b/internal/reviewprocess/process.go index 676042f60..b3ffe2b09 100644 --- a/internal/reviewprocess/process.go +++ b/internal/reviewprocess/process.go @@ -58,6 +58,7 @@ type Usage struct { Limit int64 FullCapacityInMS int64 RollingWindowMS int64 + permit *usagePermit } type Capture struct { @@ -171,16 +172,17 @@ func (r *Runner) Usage(ctx context.Context, workspace reviewworkspace.Workspace, return usage, processError("rate_limited", false) } r.permit = &usagePermit{workspace: keyFor(workspace), issued: r.now()} + usage.permit = r.permit r.mu.Unlock() return usage, nil } // RetireUsagePermit proves the exact permit still existed and was never // consumed by Review. A different or absent permit is left untouched. -func (r *Runner) RetireUsagePermit(workspace reviewworkspace.Workspace) bool { +func (r *Runner) RetireUsagePermit(workspace reviewworkspace.Workspace, usage Usage) bool { r.mu.Lock() defer r.mu.Unlock() - if r.permit == nil || r.permit.workspace != keyFor(workspace) { + if r.permit == nil || r.permit != usage.permit || r.permit.workspace != keyFor(workspace) { return false } r.permit = nil diff --git a/internal/reviewprocess/process_test.go b/internal/reviewprocess/process_test.go index 20d32285f..de1925c2b 100644 --- a/internal/reviewprocess/process_test.go +++ b/internal/reviewprocess/process_test.go @@ -711,14 +711,22 @@ func TestZeroUsageRejectsWorkspaceChangedByCommand(t *testing.T) { } func TestRetireUsagePermitOnlyRemovesExactWorkspace(t *testing.T) { - want := reviewworkspace.Workspace{Directory: "owned-attempt", ComparisonRef: "pinned"} - other := want + f := newProcessFixture(t) + r := f.runner(t, fmt.Sprintf(`printf '%%s' %q`, usageJSON("owner/repo", "owner", 4, 5, 12000, 3600000))) + original, err := r.Usage(t.Context(), f.workspace, "owner/repo", "owner") + if err != nil { + t.Fatal(err) + } + current, err := r.Usage(t.Context(), f.workspace, "owner/repo", "owner") + if err != nil { + t.Fatal(err) + } + other := f.workspace other.Directory = "different-attempt" - r := &Runner{permit: &usagePermit{workspace: keyFor(want)}} - if r.RetireUsagePermit(other) || r.permit == nil { - t.Fatal("wrong workspace retired the permit") + if r.RetireUsagePermit(f.workspace, original) || r.RetireUsagePermit(other, current) { + t.Fatal("an unrelated allowance or workspace retired the current permit") } - if !r.RetireUsagePermit(want) || r.permit != nil || r.RetireUsagePermit(want) { - t.Fatal("matching permit was not retired exactly once") + if !r.RetireUsagePermit(f.workspace, current) || r.RetireUsagePermit(f.workspace, current) { + t.Fatal("matching allowance was not retired exactly once") } } diff --git a/internal/reviewruntime/cli_driver.go b/internal/reviewruntime/cli_driver.go index c50cd2c27..1b945ab90 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -27,7 +27,7 @@ type CLIDriver struct { reader reviewexec.TargetReader fetch func(context.Context, int64, string, string, string, string) error verify func(context.Context, reviewworkspace.Workspace) error - retireUsage func(reviewworkspace.Workspace) bool + retireUsage func(reviewworkspace.Workspace, reviewprocess.Usage) bool usage func(context.Context, reviewworkspace.Workspace, string, string) (reviewprocess.Usage, error) review func(context.Context, reviewworkspace.Workspace) (reviewprocess.Capture, error) mu sync.Mutex @@ -202,7 +202,7 @@ func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, } if err := d.engine.RecordCLIAllowance(ctx, operation.ProjectID, attempt.ID, attempt.Revision, reviewexec.CLIAllowanceObservation{Anchor: anchor, ObservedAt: time.Now().UTC().Format(time.RFC3339Nano), Remaining: usage.Remaining, Limit: usage.Limit, FullCapacityInMS: usage.FullCapacityInMS, RollingWindowMS: usage.RollingWindowMS, ChangedFiles: changedFiles}); err != nil { return preparation, reviewexec.CLIPreflightUnusedHandoff(err, func() bool { - return d.retireUsage != nil && d.retireUsage(workspace) + return d.retireUsage != nil && d.retireUsage(workspace, usage) }, releaseSettlement) } if err := publishPreparedAttempt(ctx, d.engine, operation.ProjectID, attempt.ID, plan); err != nil { @@ -245,9 +245,13 @@ func (d *CLIDriver) Dispatch(ctx context.Context, operation reviewexec.Operation if err := d.verify(ctx, prepared.workspace); err != nil { return failed("workspace_changed") } - if err := d.engine.VerifyAction(ctx, operation.ProjectID, attempt.ID, attempt.Revision, predecessors...); err != nil { + refusal, err := d.engine.VerifyCLIAction(ctx, operation.ProjectID, attempt.ID, attempt.Revision, predecessors...) + if err != nil { return failed("admission_changed") } + if refusal.HasCLIStartRefusal() { + return refusal, nil + } started := time.Now().UTC() capture, executionErr := d.review(ctx, prepared.workspace) finished := time.Now().UTC() diff --git a/internal/reviewruntime/cli_driver_test.go b/internal/reviewruntime/cli_driver_test.go index ba10c8c95..fcb66af2b 100644 --- a/internal/reviewruntime/cli_driver_test.go +++ b/internal/reviewruntime/cli_driver_test.go @@ -2,6 +2,7 @@ package reviewruntime import ( "context" + "database/sql" "encoding/json" "errors" "fmt" @@ -339,6 +340,104 @@ WHERE (project_id,source,source_attempt_id,version_revision) IN ( // intentionally distinct identities. func (f *cliDriverFixture) readerToken() string { return f.cliEvidenceFixture.reader } +func TestCLISupervisorResumesOriginalRequestAfterPreStartPause(t *testing.T) { + f := newCLIDriverFixture(t) + scope := f.scope(t, f.writer, false) + setPaused := func(ctx context.Context, expected int64, paused bool) error { + _, err := f.engine.ConfigurePullScheduling(ctx, scope, core.NewID("pause"), 2, reviewexec.PullSchedulingRequest{ExpectedRevision: &expected, Paused: &paused, Reason: "Review updates"}) + return err + } + raw, err := f.engine.Enqueue(t.Context(), scope, "normal-pause-before-start", reviewexec.Request{ExpectedConfigurationRevision: 1, PullNumber: 2, Channel: "cli", HeadSHA: f.headSHA}) + if err != nil { + t.Fatal(err) + } + var receipt reviewexec.Receipt + if err := json.Unmarshal(raw, &receipt); err != nil { + t.Fatal(err) + } + var pauseOnce sync.Once + var pauseErr error + originalVerify := f.driver.verify + f.driver.verify = func(ctx context.Context, w reviewworkspace.Workspace) error { + if err := originalVerify(ctx, w); err != nil { + return err + } + current, err := f.engine.ReadOperation(ctx, scope, receipt.ID) + if err != nil || current.State != "active" { + return err + } + pauseOnce.Do(func() { pauseErr = setPaused(ctx, 0, true) }) + return pauseErr + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done, err := f.engine.Start(ctx, map[string]reviewexec.Driver{f.capability.ID: f.driver}) + if err != nil { + t.Fatal(err) + } + waitFor := func(wanted string) reviewexec.Operation { + t.Helper() + deadline := time.NewTimer(10 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(5 * time.Millisecond) + defer tick.Stop() + for { + o, err := f.engine.ReadOperation(t.Context(), scope, receipt.ID) + if err != nil { + t.Fatal(err) + } + if o.State == wanted && (wanted != "queued" || o.Reason == "pull_scheduling_paused_before_cli_start") { + return o + } + select { + case err := <-done: + t.Fatalf("supervisor stopped before %s: %v; operation=%+v", wanted, err, o) + case <-deadline.C: + t.Fatalf("request did not reach %s: %+v", wanted, o) + case <-tick.C: + } + } + } + paused := waitFor("queued") + if paused.AttemptID != "" { + t.Fatal("paused request retained attached attempt") + } + var original string + if err := f.store.DB().QueryRow(`SELECT id FROM review_execution_attempts WHERE operation_id=? AND state='failed'`, receipt.ID).Scan(&original); err != nil { + t.Fatal(err) + } + log, err := os.ReadFile(f.log) + if err != nil || !strings.Contains(string(log), "usage --agent") || strings.Contains(string(log), "review ") { + t.Fatalf("review started before resume: %v", err) + } + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return reviewexec.ValidateOperationWaitsSnapshot(ctx, tx) }); err != nil { + t.Fatal("paused snapshot:", err) + } + if err := setPaused(t.Context(), 1, false); err != nil { + t.Fatal(err) + } + completed := waitFor("completed") + if completed.AttemptID == "" || completed.AttemptID == original { + t.Fatal("resume did not create a fresh attempt on the same request") + } + log, err = os.ReadFile(f.log) + if err != nil || strings.Count(string(log), "review ") != 1 { + t.Fatalf("resumed request did not run exactly once: %v", err) + } + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return reviewexec.ValidateOperationWaitsSnapshot(ctx, tx) }); err != nil { + t.Fatal("resumed snapshot:", err) + } + cancel() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("supervisor did not stop") + } +} + func TestCLIDriverFinalGuardsPreventProcessStart(t *testing.T) { for _, mode := range []string{"source-head", "policy", "revocation", "workspace", "expired-context"} { t.Run(mode, func(t *testing.T) { From 7128b4dc4a8da779973092e52e0aad86d96dfb1b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 22:37:48 +1300 Subject: [PATCH 24/34] Test guarded legacy Hosted continuity --- .../reviewexec/hosted_control_batch_regression_test.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/internal/reviewexec/hosted_control_batch_regression_test.go b/internal/reviewexec/hosted_control_batch_regression_test.go index 65f1395a1..870311578 100644 --- a/internal/reviewexec/hosted_control_batch_regression_test.go +++ b/internal/reviewexec/hosted_control_batch_regression_test.go @@ -149,10 +149,17 @@ func TestContinuityValidatesCurrentBasisAndNativeProjectActor(t *testing.T) { 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"}, 1, "test-actor", current) + 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) + } + } }) } } From 87a63662797831d86cfe00bb79122baf5a315dd9 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 22:43:06 +1300 Subject: [PATCH 25/34] Separate retained review regression qualification --- ...ission_binding_boundary_regression_test.go | 67 ------- .../reviewexec/finish_front_local_test.go | 23 --- .../hosted_control_batch_regression_test.go | 165 ------------------ ...hosted_detached_preflight_snapshot_test.go | 63 ------- .../local_refusal_boundaries_test.go | 48 ----- .../run_selection_claim_read_test.go | 105 ----------- .../scheduling_ancestor_memo_test.go | 50 ------ .../scheduling_cooldown_history_test.go | 69 -------- .../scheduling_paused_grant_basis_test.go | 31 ---- .../scheduling_source_acceptance_test.go | 69 -------- 10 files changed, 690 deletions(-) delete mode 100644 internal/reviewexec/admission_binding_boundary_regression_test.go delete mode 100644 internal/reviewexec/finish_front_local_test.go delete mode 100644 internal/reviewexec/hosted_control_batch_regression_test.go delete mode 100644 internal/reviewexec/hosted_detached_preflight_snapshot_test.go delete mode 100644 internal/reviewexec/local_refusal_boundaries_test.go delete mode 100644 internal/reviewexec/run_selection_claim_read_test.go delete mode 100644 internal/reviewexec/scheduling_ancestor_memo_test.go delete mode 100644 internal/reviewexec/scheduling_cooldown_history_test.go delete mode 100644 internal/reviewexec/scheduling_paused_grant_basis_test.go delete mode 100644 internal/reviewexec/scheduling_source_acceptance_test.go diff --git a/internal/reviewexec/admission_binding_boundary_regression_test.go b/internal/reviewexec/admission_binding_boundary_regression_test.go deleted file mode 100644 index 719317e65..000000000 --- a/internal/reviewexec/admission_binding_boundary_regression_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package reviewexec - -import ( - "context" - "testing" -) - -func TestAdmitReleasesOnlyMalformedSelectionLink(t *testing.T) { - for _, outcome := range []string{"malformed-link", "proved-custody"} { - t.Run(outcome, func(t *testing.T) { - f := selectionFixtureWithQueue(t, []int64{2}) - r, _ := selectionEnqueue(t, f, "prepare-boundary", "hosted", nil) - selectionNext(t, f, &refreshTestReader{}) - id := selectionRead(t, f, r.ID).OperationID - if id == "" { - t.Fatal("fixture did not retain a selected child") - } - before := roundOperation(t, f, id) - var prep Attempt - driver := &controlledDriver{prepare: func(ctx context.Context, op Operation, _ Configuration, a Attempt) (Preparation, error) { - if op.ID != id { - t.Fatal("unrelated operation entered fixture", op.ID) - } - if _, err := f.e.ExecutionContext(ctx, op.ProjectID, op.ID); err != nil { - t.Fatal("expected valid preflight before controlled state change", err) - } - prep = a - if outcome == "malformed-link" { - admissionSQL(t, f, "UPDATE review_selections SET worker_id=? WHERE id=?", "different-fixture-worker", r.ID) - } else { - admissionSQL(t, f, "UPDATE review_selections SET state='held',reason='linked_selection_quarantined',operation_id=NULL,revision=3 WHERE id=?", r.ID) - admissionSQL(t, f, "INSERT INTO review_selection_quarantine (selection_id,project_id,original_operation_id,original_state,observed_revision) VALUES(?,?,?,'selecting',2)", r.ID, attemptProject, id) - if err := requireUnquarantinedSelectionLink(ctx, f.store.DB(), attemptProject, id); !isLinkedSelectionCustodyHeld(err) { - t.Fatal("fixture has no proved custody", err) - } - } - return Preparation{Anchor: attemptAnchor(op.ProjectID, op.PullNumber), Intent: "unposted-boundary-intent"}, nil - }} - if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { - t.Fatal("local refusal became a worker-wide error", err) - } - after := roundOperation(t, f, id) - if prep.ID == "" || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || - after.ID != before.ID || after.HeadSHA != before.HeadSHA || after.ActorID != before.ActorID || - after.WorkerID != before.WorkerID || after.ConfigurationRevision != before.ConfigurationRevision { - t.Fatal("preparation changed original operation or dispatched", before, after) - } - expectedAttempt := "preparing" - expectedReservations := 1 - if outcome == "malformed-link" { - expectedAttempt, expectedReservations = "held", 0 - if after.State != "queued" || after.Reason != "automatic_scheduling_unavailable" || after.AttemptID != "" { - t.Fatal("malformed direct link did not release unused preparation", after) - } - } else if after.State != "preparing" || after.AttemptID != prep.ID { - t.Fatal("proved custody was treated as malformed direct link", after) - } - if n := attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations"); n != expectedReservations { - t.Fatal("unexpected reservation count", n, expectedReservations) - } - var state, intent, external string - if err := f.store.DB().QueryRow("SELECT state,intent,external_id FROM review_execution_attempts WHERE id=?", prep.ID).Scan(&state, &intent, &external); err != nil || state != expectedAttempt || intent != "" || external != "" { - t.Fatal("refusal recorded external state or unexpected attempt lifecycle", state, intent, external, err) - } - }) - } -} diff --git a/internal/reviewexec/finish_front_local_test.go b/internal/reviewexec/finish_front_local_test.go deleted file mode 100644 index c366281d9..000000000 --- a/internal/reviewexec/finish_front_local_test.go +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 870311578..000000000 --- a/internal/reviewexec/hosted_control_batch_regression_test.go +++ /dev/null @@ -1,165 +0,0 @@ -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 deleted file mode 100644 index 8ca6a54d9..000000000 --- a/internal/reviewexec/hosted_detached_preflight_snapshot_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package reviewexec - -import ( - "testing" -) - -func TestHostedSnapshotRetainsUnusedSchedulingPreflight(t *testing.T) { - for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_scheduling_unavailable"} { - t.Run(reason, func(t *testing.T) { - f, first, _, input := hostedAllowanceFixture(t) - if err := f.e.RecordHostedAllowance(t.Context(), attemptProject, first.ID, first.Revision, input); err != nil { - t.Fatal(err) - } - if _, err := f.e.Advance(t.Context(), attemptProject, first.ID, first.Revision, "held", reason, ""); err != nil { - t.Fatal(err) - } - check := func() { - t.Helper() - tables := []string{"review_hosted_preflight", "review_hosted_allowance_queries", "review_operations", "review_operation_waits"} - before := make([]string, len(tables)) - for i, table := range tables { - before[i] = snapshotTable(t, f, table) - } - tx, err := f.store.DB().BeginTx(t.Context(), nil) - if err != nil { - t.Fatal(err) - } - defer tx.Rollback() - if err := ValidateAllowanceSnapshot(t.Context(), tx, 10); err != nil { - t.Fatalf("valid detached Hosted preflight refused: %v", err) - } - if err := ValidateOperationWaitsSnapshot(t.Context(), tx); err != nil { - t.Fatalf("valid detached Hosted preflight wait history refused: %v", err) - } - for i, table := range tables { - if after := snapshotTableThrough(t, tx, table); before[i] != after { - t.Fatalf("snapshot wrote to %s inside inspection", table) - } - } - } - check() - next := f.start(t, attemptProject, Receipt{ID: first.OperationID}) - if next.ID == "" || next.ID == first.ID { - t.Fatal("new attempt not independently attached", next) - } - check() - o, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, first.OperationID) - if err != nil { - t.Fatal(err) - } - if o.AttemptID != next.ID { - t.Fatal("snapshot rebound the current operation", o.AttemptID) - } - detached, err := readAttempt(t.Context(), f.store.DB(), attemptProject, first.ID) - if err != nil { - t.Fatal(err) - } - if _, err := readHostedAllowanceRecord(t.Context(), f.store.DB(), o, detached); err == nil { - t.Fatal("live allowance lookup accepted detached scheduling history") - } - }) - } -} diff --git a/internal/reviewexec/local_refusal_boundaries_test.go b/internal/reviewexec/local_refusal_boundaries_test.go deleted file mode 100644 index 3ca2cadad..000000000 --- a/internal/reviewexec/local_refusal_boundaries_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package reviewexec - -import ( - "context" - "database/sql" - "errors" - "strings" - "testing" - - "github.com/benhook1013/FireController/internal/core" -) - -func TestAutomaticAdoptionCountRetainsLocalRepositoryRefusal(t *testing.T) { - f := selectionFixture(t) - retainObligationSource(t, f, attemptProject, "local-refusal-importer", "local-refusal-source", strings.Repeat("c", 64), 0) - if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - if count, err := sourceObligationCount(ctx, tx, attemptProject, 2); count != 1 || err != nil { - t.Fatalf("valid retained source count=%d err=%v", count, err) - } - repositoryChanged := core.Fail("repository_changed", "Synthetic retained source bound to a different repository.", 409) - for _, tt := range []struct { - failure error - local bool - }{ - {repositoryChanged, true}, - {errors.New("synthetic shared SQL failure"), false}, - {context.Canceled, false}, - {context.DeadlineExceeded, false}, - } { - count, err := sourceObligationCount(ctx, admissionObligationFailure{Tx: tx, failure: tt.failure}, attemptProject, 2) - if count != 0 || err == nil || automaticProjectRefused(err) != tt.local || isSourceObligationProjectStateError(err) { - t.Errorf("automatic read count=%d local=%t ordinary-admission marker=%t err=%v", count, automaticProjectRefused(err), isSourceObligationProjectStateError(err), err) - } - if tt.local { - attemptCode(t, err, "review_held") - attemptCode(t, sourceObligationReadError(tt.failure), "review_held") - if preparationReason(err) != "repository_changed" || automaticProjectRefused(sourceObligationReadError(tt.failure)) { - t.Errorf("public reason/ordinary admission changed: %v", err) - } - } else if !errors.Is(err, tt.failure) { - t.Errorf("shared error lost: got %v want %v", err, tt.failure) - } - } - return nil - }); err != nil { - t.Fatal(err) - } -} diff --git a/internal/reviewexec/run_selection_claim_read_test.go b/internal/reviewexec/run_selection_claim_read_test.go deleted file mode 100644 index 11df22624..000000000 --- a/internal/reviewexec/run_selection_claim_read_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package reviewexec - -import ( - "context" - "testing" - "time" -) - -func TestRunSelectionClaimedExplicitReadContention(t *testing.T) { - for _, tc := range []struct { - name, state, reason string - calls, children int - }{ - {name: "brief", state: "selected", calls: 3, children: 1}, - {name: "exhausted", state: "held", reason: "local_read_unavailable"}, - } { - t.Run(tc.name, func(t *testing.T) { - f := selectionFixture(t) - receipt, _ := selectionEnqueue(t, f, "post-claim-reader", "cli", nil) - r := &refreshTestReader{} - ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) - defer cancel() - - // Pause at the existing post-commit notification, not at the - // provider callback (which would exercise the later prefix read). - f.e.operationMu.Lock() - unlocked := false - defer func() { - if !unlocked { - f.e.operationMu.Unlock() - } - }() - type result struct { - worked bool - err error - } - done := make(chan result, 1) - go func() { - worked, err := f.e.runNext(ctx, map[string]TargetReader{"test-capability": r}) - done <- result{worked, err} - }() - claimDeadline := time.Now().Add(4 * time.Second) - for { - var state string - var revision int64 - err := f.store.DB().QueryRowContext(ctx, "SELECT state,revision FROM review_selections WHERE id=?", receipt.ID).Scan(&state, &revision) - if err != nil { - t.Fatal(err) - } - if state == "selecting" && revision == 2 { - break - } - if time.Now().After(claimDeadline) { - t.Fatal("selection claim did not commit", state, revision) - } - time.Sleep(5 * time.Millisecond) - } - db := f.store.DB() - db.SetMaxOpenConns(1) - conn, err := db.Conn(ctx) - if err != nil { - t.Fatal(err) - } - defer conn.Close() - waitCount := db.Stats().WaitCount - f.e.operationMu.Unlock() - unlocked = true - - if tc.name == "brief" { - // A second wait proves the first bounded admission expired. - deadline := time.NewTimer(5 * time.Second) - defer deadline.Stop() - tick := time.NewTicker(5 * time.Millisecond) - defer tick.Stop() - for db.Stats().WaitCount < waitCount+2 { - select { - case result := <-done: - t.Fatalf("claimed selection stopped instead of retrying: %+v", result) - case <-deadline.C: - t.Fatal("no second read admission after expiry") - case <-tick.C: - } - } - if r.calls.Load() != 0 { - t.Fatal("provider called before local admission") - } - conn.Close() - } - select { - case result := <-done: - if result.err != nil || !result.worked { - t.Fatalf("claimed selection did not finish locally: %+v", result) - } - case <-ctx.Done(): - t.Fatal("claimed selection did not finish", ctx.Err()) - } - conn.Close() - got := selectionContentionRead(t, f, receipt.ID) - if got.State != tc.state || got.Reason != tc.reason || got.Revision != 3 || - int(r.calls.Load()) != tc.calls || attemptCount(t, f.store, "SELECT count(*) FROM review_operations") != tc.children { - t.Fatal("unexpected state or duplicate work", got, r.calls.Load()) - } - }) - } -} diff --git a/internal/reviewexec/scheduling_ancestor_memo_test.go b/internal/reviewexec/scheduling_ancestor_memo_test.go deleted file mode 100644 index 02d58f01d..000000000 --- a/internal/reviewexec/scheduling_ancestor_memo_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package reviewexec - -import ( - "context" - "database/sql" - "fmt" - "testing" -) - -func TestAutomaticDependenciesReuseSharedAncestorWithinSnapshot(t *testing.T) { - f := schedulingFixture(t) - frame := frontFrame{repository: 1, prefix: []frontPull{{Number: 2, HeadSHA: "parent"}, {Number: 4, HeadSHA: "intermediate", ParentPullNumber: 2}}} - for pull := int64(10); pull < 60; pull++ { - parent := int64(2) - if pull%2 == 0 { - parent = 4 - } - frame.prefix = append(frame.prefix, frontPull{Number: pull, ParentPullNumber: parent}) - } - if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - memo := make(map[int64][]any) - index := frontPullIndex(frame) - reads := 0 - for pull := int64(10); pull < 60; pull++ { - direct, err := automaticDependenciesWithFrame(ctx, tx, attemptProject, pull, "hosted", frame, true, nil, nil) - if err != nil { - return err - } - cached, err := automaticDependenciesWithAncestorRead(pull, frame, true, index, memo, func(p frontPull) ([]any, error) { - reads++ - return readAutomaticAncestorFacts(ctx, tx, attemptProject, "hosted", frame.repository, p) - }) - if err != nil { - return err - } - if encoded(direct) != encoded(cached) { - return fmt.Errorf("pull %d: planning facts changed: direct %v, memo %v", pull, direct, cached) - } - } - if reads != 2 { - return fmt.Errorf("evaluated %d ancestors, want exactly two across all siblings", reads) - } - if len(memo) != 2 { - return fmt.Errorf("memo has %d entries, want exactly two shared ancestors", len(memo)) - } - return nil - }); err != nil { - t.Fatal(err) - } -} diff --git a/internal/reviewexec/scheduling_cooldown_history_test.go b/internal/reviewexec/scheduling_cooldown_history_test.go deleted file mode 100644 index 007c69106..000000000 --- a/internal/reviewexec/scheduling_cooldown_history_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package reviewexec - -import ( - "reflect" - "testing" -) - -func TestSchedulingHoldKeepsCooldownHistoryStrict(t *testing.T) { - for _, channel := range []string{"cli", "hosted"} { - for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_scheduling_unavailable"} { - for _, damage := range []string{"none", "first-reason", "missing-first", "extra-transition", "intent", "reservation", "evidence"} { - t.Run(channel+"/"+reason+"/"+damage, func(t *testing.T) { - f, original, now := deadlineRuntimeFixture(t, channel) - before := cliWaitRead(t, f, original.OperationID) - *now = cliWaitDue(t, before) - retry := f.start(t, attemptProject, Receipt{ID: original.OperationID}) - if _, err := f.e.Advance(t.Context(), attemptProject, retry.ID, retry.Revision, "held", reason, ""); err != nil { - t.Fatal(err) - } - after := cliWaitRead(t, f, original.OperationID) - if after.State != "queued" || after.AttemptID != "" || !reflect.DeepEqual(before.Wait, after.Wait) { - t.Fatal("lost original timer", after) - } - switch damage { - case "first-reason": - admissionSQL(t, f, `UPDATE review_execution_transitions SET reason='not-preparing' WHERE attempt_id=? AND revision=1`, retry.ID) - case "missing-first": - admissionSQL(t, f, `DELETE FROM review_execution_transitions WHERE attempt_id=? AND revision=1`, retry.ID) - case "extra-transition": - admissionSQL(t, f, `INSERT INTO review_execution_transitions SELECT attempt_id,3,state,reason,external_id,created_at FROM review_execution_transitions WHERE attempt_id=? AND revision=2`, retry.ID) - case "intent": - admissionSQL(t, f, `UPDATE review_execution_attempts SET intent='issued' WHERE id=?`, retry.ID) - case "reservation": - admissionSQL(t, f, `INSERT INTO review_execution_reservations VALUES(?,901,2,?,?,?)`, retry.Provider, channel, retry.Account, retry.ID) - case "evidence": - admissionSQL(t, f, `INSERT INTO review_execution_evidence VALUES('bad-evidence',?,?,?,'{}','bad')`, attemptProject, retry.ID, after.ID) - } - state := deadlineRuntimeState(t, f) - wait, err := readOperationWait(t.Context(), f.store.DB(), after) - if damage == "none" { - if err != nil || !reflect.DeepEqual(wait, before.Wait) { - t.Fatal("valid history refused", wait, err) - } - } else if err == nil || wait != nil { - t.Fatal("runtime accepted corruption", wait, err) - } - tx, err := f.store.DB().BeginTx(t.Context(), nil) - if err != nil { - t.Fatal(err) - } - defer tx.Rollback() - err = ValidateOperationWaitsSnapshot(t.Context(), tx) - if state != deadlineRuntimeStateThrough(t, tx) { - t.Fatal("validation wrote inside the retained-history transaction") - } - if rollbackErr := tx.Rollback(); rollbackErr != nil { - t.Fatal(rollbackErr) - } - if (err == nil) != (damage == "none") { - t.Fatal("snapshot history classification", err) - } - if state != deadlineRuntimeState(t, f) { - t.Fatal("validation mutated retained history") - } - }) - } - } - } -} diff --git a/internal/reviewexec/scheduling_paused_grant_basis_test.go b/internal/reviewexec/scheduling_paused_grant_basis_test.go deleted file mode 100644 index 759b1c3de..000000000 --- a/internal/reviewexec/scheduling_paused_grant_basis_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package reviewexec - -import ( - "context" - "database/sql" - "slices" - "testing" -) - -func TestAutomaticGrantBasisOmitsPausedPullAndIncludesItAfterResume(t *testing.T) { - f := schedulingFixture(t) - roundGrant(t, f, 2, "hosted", 0, 1, 2, "paused-basis-grant") - roundGrant(t, f, 4, "hosted", 0, 1, 2, "neighbor-basis-grant") - schedulingPause(t, f, 2, 0, true) - check := func(want []int64) { - t.Helper() - err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - got, err := readAutomaticGrantRevisions(ctx, tx, attemptProject, "hosted", []int64{2, 4}) - if err == nil && !slices.Equal(got, want) { - t.Errorf("grant revisions = %v, want %v", got, want) - } - return err - }) - if err != nil { - t.Fatal(err) - } - } - check([]int64{-2, 1}) - schedulingPause(t, f, 2, 1, false) - check([]int64{1, 1}) -} diff --git a/internal/reviewexec/scheduling_source_acceptance_test.go b/internal/reviewexec/scheduling_source_acceptance_test.go deleted file mode 100644 index e2fb445c3..000000000 --- a/internal/reviewexec/scheduling_source_acceptance_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package reviewexec - -import ( - "context" - "database/sql" - "testing" - "time" -) - -func TestInitialAutomaticSourceAcceptanceRequiresCanonicalEvidence(t *testing.T) { - f := selectionFixture(t) - accepted, _ := selectionEnqueue(t, f, "acceptance-contract-fixture", "hosted", nil) - selection := selectionRead(t, f, accepted.ID) - var missing Run = selection - missing.ID = "no-retained-acceptance" - err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - check := func(r Run, expected bool, expectError bool) { - t.Helper() - got, err := verifiedInitialAutomaticSourceAcceptance(ctx, tx, r) - if got != expected || (err != nil) != expectError { - t.Fatalf("canonical automatic acceptance = %v (%v), want %v (error=%v)", got, err, expected, expectError) - } - } - check(missing, false, false) - check(selection, false, false) // An explicit receipt is not an automatic grant. - automatic := encoded(selectionRequestedEvent{Channel: selection.Channel, Origin: selectionOriginAutomatic, WorkerID: selection.WorkerID}) - if _, err := tx.ExecContext(ctx, `UPDATE events SET payload_json=? WHERE project_id=? AND resource_id=? AND event_type='review.selection_requested' AND revision=1`, automatic, selection.ProjectID, selection.ID); err != nil { - return err - } - check(selection, true, false) - other := selection - other.WorkerID = "different-test-worker" - check(other, false, true) - return nil - }) - if err != nil { - t.Fatal(err) - } -} - -// A valid restart's retained revision order follows journal append order. -func TestInitialAutomaticSourceAcceptsOrderedRestartJournal(t *testing.T) { - f := selectionFixture(t) - accepted, _ := selectionEnqueue(t, f, "restart-journal-order", "hosted", nil) - selection := selectionRead(t, f, accepted.ID) - err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - for _, state := range []string{"selecting", "queued", "selecting"} { - run, err := readRun(ctx, tx, selection.ProjectID, accepted.ID) - if err != nil { - return err - } - if err := updateRunAt(ctx, tx, run, state, "", "", time.Now()); err != nil { - return err - } - } - run, err := readRun(ctx, tx, selection.ProjectID, accepted.ID) - if err != nil { - return err - } - valid, err := automaticSourceInitialRead(ctx, tx, run) - if !valid || err != nil { - t.Fatalf("classify canonical restart journal: got %v (%v), want true", valid, err) - } - return nil - }) - if err != nil { - t.Fatal(err) - } -} From da4ef7c64ba5eb16d7648dc7145cb1f4826e59db Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 22:48:40 +1300 Subject: [PATCH 26/34] Separate additional retained review compatibility tests --- .../owned_cli_settlement_retry_test.go | 40 ------- .../preferred_cli_wait_integrity_test.go | 52 --------- .../scheduling_basis_contract_test.go | 46 -------- .../scheduling_historical_basis_test.go | 107 ------------------ .../scheduling_pause_history_test.go | 47 -------- .../scheduling_snapshot0030_test.go | 56 --------- .../reviewexec/selection_native_key_test.go | 106 ----------------- 7 files changed, 454 deletions(-) delete mode 100644 internal/reviewexec/owned_cli_settlement_retry_test.go delete mode 100644 internal/reviewexec/preferred_cli_wait_integrity_test.go delete mode 100644 internal/reviewexec/scheduling_basis_contract_test.go delete mode 100644 internal/reviewexec/scheduling_historical_basis_test.go delete mode 100644 internal/reviewexec/scheduling_pause_history_test.go delete mode 100644 internal/reviewexec/scheduling_snapshot0030_test.go delete mode 100644 internal/reviewexec/selection_native_key_test.go diff --git a/internal/reviewexec/owned_cli_settlement_retry_test.go b/internal/reviewexec/owned_cli_settlement_retry_test.go deleted file mode 100644 index ad6adb917..000000000 --- a/internal/reviewexec/owned_cli_settlement_retry_test.go +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index d70010659..000000000 --- a/internal/reviewexec/preferred_cli_wait_integrity_test.go +++ /dev/null @@ -1,52 +0,0 @@ -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/scheduling_basis_contract_test.go b/internal/reviewexec/scheduling_basis_contract_test.go deleted file mode 100644 index edd02a312..000000000 --- a/internal/reviewexec/scheduling_basis_contract_test.go +++ /dev/null @@ -1,46 +0,0 @@ -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_historical_basis_test.go b/internal/reviewexec/scheduling_historical_basis_test.go deleted file mode 100644 index b6ccb2f41..000000000 --- a/internal/reviewexec/scheduling_historical_basis_test.go +++ /dev/null @@ -1,107 +0,0 @@ -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") - var unreadable *automaticPullAdjudicationUnavailable - if plan != "" || eligible || !errors.As(err, &unreadable) { - t.Fatalf("active unreadable row was not refused: %q %v %v", plan, eligible, 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 deleted file mode 100644 index 3bac26acd..000000000 --- a/internal/reviewexec/scheduling_pause_history_test.go +++ /dev/null @@ -1,47 +0,0 @@ -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_snapshot0030_test.go b/internal/reviewexec/scheduling_snapshot0030_test.go deleted file mode 100644 index 95b97b0e4..000000000 --- a/internal/reviewexec/scheduling_snapshot0030_test.go +++ /dev/null @@ -1,56 +0,0 @@ -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/selection_native_key_test.go b/internal/reviewexec/selection_native_key_test.go deleted file mode 100644 index 90a4878be..000000000 --- a/internal/reviewexec/selection_native_key_test.go +++ /dev/null @@ -1,106 +0,0 @@ -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) - } -} From 70b00bbe52b6184ee4924bb5f320739c11c69edc Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 23:17:49 +1300 Subject: [PATCH 27/34] Complete batched Hosted and CLI review fixes --- internal/backup/review_selection_test.go | 8 +- internal/backup/scheduling_test.go | 4 + internal/reviewexec/attempts.go | 72 ++++++-- internal/reviewexec/cli_pause_no_start.go | 104 +++++++++-- .../reviewexec/cli_policy_settlement_test.go | 76 +++++++- .../reviewexec/cli_prepared_settlement.go | 173 ++++++++++++++++++ .../live_cli_preparation_settlement_test.go | 4 + internal/reviewexec/run_selection.go | 5 +- internal/reviewexec/run_selection_origin.go | 9 +- internal/reviewexec/run_selection_schema.go | 6 +- internal/reviewexec/run_selection_worker.go | 14 +- internal/reviewexec/scheduling.go | 2 +- internal/reviewexec/scheduling_authority.go | 25 ++- .../scheduling_boundary_compatibility_test.go | 35 +++- internal/reviewexec/scheduling_snapshot.go | 12 +- .../scheduling_source_hold_basis_test.go | 9 +- internal/reviewexec/supervisor.go | 3 +- 17 files changed, 493 insertions(+), 68 deletions(-) create mode 100644 internal/reviewexec/cli_prepared_settlement.go diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index a30505f53..fb81a2582 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -244,9 +244,9 @@ func dropSelectionPredecessorDomains(t *testing.T, db *sql.DB) { } } -// Removing the new optional domains reconstructs a valid parent schema without -// relabeling a newer reviews/execution migration. -func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testing.T) { +// Removing the optional selection, scheduling, and front domains models an +// archive where those domains are absent, not an exact parent checkout. +func TestSelectionInventoryReinstallsAbsentOptionalDomainsWithoutChangingRows(t *testing.T) { f := newRestoreFixture(t) db := f.store.DB() dropSelectionPredecessorDomains(t, db) @@ -261,7 +261,7 @@ func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testin } bundle := restoreBundle(t, f) if _, err := Inspect(t.Context(), bundle.Path); err != nil { - t.Fatal("actual predecessor schema refused", err) + t.Fatal("archive with absent optional selection/front domains refused", err) } destination := filepath.Join(t.TempDir(), "inactive-parent") if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index 2a0817eab..33e7b9492 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -85,6 +85,10 @@ func TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { reviewexec.PullSchedulingRequest{ExpectedRevision: &one, Paused: &resumed}); err != nil { t.Fatal(err) } + represented := restoreBundle(t, f) + if _, err := Inspect(t.Context(), represented.Path); err != nil { + t.Fatal("normal represented pause and resume history was not inspectable", err) + } event := restoreRows(t, f.store.DB(), `SELECT project_id,4,revision,0,'',actor_id,created_at FROM events WHERE event_type='review.pull_scheduling_updated' AND resource_id='4' AND revision=2`) if len(event) != 1 || len(event[0]) != 7 { diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index b51d69593..66004c23e 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -256,7 +256,7 @@ func (e *Engine) admit(ctx context.Context, project, id string, expectedRevision return Attempt{}, invalid() } var result Attempt - var handlingPreparedRefusal bool + var settlement *preparedCLISettlement err = e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { a, err := readAttempt(ctx, tx, project, id) if err != nil { @@ -288,8 +288,8 @@ func (e *Engine) admit(ctx context.Context, project, id string, expectedRevision } var schedulingHistory *schedulingHistoryUnavailable if settlePreparedCLI && o.Channel == "cli" && intent == "" && !schedulingRefused(err) && errors.As(err, &schedulingHistory) { - handlingPreparedRefusal = true - result, err = e.settleCLIAdmissionRefusal(ctx, tx, o, a, anchor, err) + settlement = &preparedCLISettlement{operation: o, attempt: a, anchor: anchor, refusal: err, kind: preparedCLIRefusalScheduling} + result, err = e.recordPreparedCLISettlement(ctx, tx, settlement) } return err } @@ -325,8 +325,8 @@ func (e *Engine) admit(ctx context.Context, project, id string, expectedRevision _, reason, err := boundPolicy(ctx, tx, o) if err != nil { if settlePreparedCLI && o.Channel == "cli" && intent == "" && isStoredUnavailable(err, storedPolicyHistory) { - handlingPreparedRefusal = true - result, err = e.settleCLIAdmissionRefusal(ctx, tx, o, a, anchor, err) + settlement = &preparedCLISettlement{operation: o, attempt: a, anchor: anchor, refusal: err, kind: preparedCLIRefusalPolicy} + result, err = e.recordPreparedCLISettlement(ctx, tx, settlement) } return err } @@ -370,7 +370,25 @@ func (e *Engine) admit(ctx context.Context, project, id string, expectedRevision }) if err == nil { e.notifyOperation(result.OperationID) - } else if handlingPreparedRefusal { + } else if settlement != nil { + if settlement.sequence != 0 { + readCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + committed, _ := e.readPreparedCLISettlement(readCtx, settlement) + cancel() + if committed { + e.notifyOperation(settlement.operation.ID) + return settlement.result, nil + } + } + if ctx.Err() == nil && transientPreparedCLISettlement(err) { + retryCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + result, err = e.retryPreparedCLISettlement(retryCtx, settlement) + cancel() + if err == nil { + e.notifyOperation(result.OperationID) + return result, nil + } + } // Guard or transaction failures must not enter generic admission // settlement, even if the caller is also shutting down. return Attempt{}, &preparedCLIAdmissionRefusal{err} @@ -425,9 +443,40 @@ type unusedCLISettlementRecord struct { // The driver has finished its exclusively owned preparation without authorizing review. // Release only the original revision-1 reservation and retain the queued request. +type unusedCLISettlementAck struct { + attempt Attempt + sequence int64 +} + func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operation, captured Attempt) error { - var proposed Attempt - var receiptSequence int64 + return e.settleUnusedCLIPreparationWithAck(ctx, original, captured, &unusedCLISettlementAck{}) +} + +func (e *Engine) settleUnusedCLIPreparationWithAck(ctx context.Context, original Operation, captured Attempt, ack *unusedCLISettlementAck) error { + if ack.sequence != 0 { + // Reconcile the previous callback before trying the original claim again. + // It may already be terminal even though the supervisor lost its acknowledgement. + if e.readUnusedCLISettlementReceipt(ctx, original, captured, ack.attempt, ack.sequence) { + e.notifyOperation(captured.OperationID) + return nil + } + var exists bool + if err := e.store.DB().QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM events WHERE sequence=?)", ack.sequence).Scan(&exists); err != nil { + return err + } + if exists { + // A separate successful read saw that position; try the exact receipt + // again before refusing. Never write across an ambiguous receipt. + if e.readUnusedCLISettlementReceipt(ctx, original, captured, ack.attempt, ack.sequence) { + e.notifyOperation(captured.OperationID) + return nil + } + return conflict() + } + // No committed event at that position. The original transaction guards + // still prove ownership and prevent a stale claim from doing anything. + *ack = unusedCLISettlementAck{} + } err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { a, err := readAttempt(ctx, tx, captured.ProjectID, captured.ID) if err != nil { @@ -465,22 +514,23 @@ func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operat unusedCLISettlementEvent, a.ID, candidate.Revision, record); err != nil { return err } + var receiptSequence int64 if err := tx.QueryRowContext(ctx, `SELECT last_insert_rowid()`).Scan(&receiptSequence); err != nil { return err } if receiptSequence <= 0 { return conflict() } - proposed = candidate + *ack = unusedCLISettlementAck{attempt: candidate, sequence: receiptSequence} return nil }) // A nonzero proposal means the entire transaction callback completed; // only then can this caller have lost the acknowledgement of a commit. - if err != nil && proposed.ID != "" { + if err != nil && ack.sequence != 0 { // The settlement window may have expired after commit. Give // this exact read-only acknowledgement check its own short window. readCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) - committed := e.readUnusedCLISettlementReceipt(readCtx, original, captured, proposed, receiptSequence) + committed := e.readUnusedCLISettlementReceipt(readCtx, original, captured, ack.attempt, ack.sequence) cancel() if committed { err = nil diff --git a/internal/reviewexec/cli_pause_no_start.go b/internal/reviewexec/cli_pause_no_start.go index b61ae0d59..6db38cebf 100644 --- a/internal/reviewexec/cli_pause_no_start.go +++ b/internal/reviewexec/cli_pause_no_start.go @@ -111,31 +111,101 @@ func (e *Engine) settleCLIPauseNoStart(ctx context.Context, original Operation, if w.engine != e || !sameCLIPauseAttempt(admitted, w.attempt) || !w.consumed.CompareAndSwap(false, true) { return conflict() } - local, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) - defer cancel() - err := e.store.BackgroundWrite(local, func(ctx context.Context, tx *sql.Tx) error { - a, o, err := readCLIPauseNoStart(ctx, tx, admitted.ProjectID, admitted.ID) - if err != nil { - return err - } - claim := o - claim.State = "preparing" - if !sameCLIPauseAttempt(a, w.attempt) || !sameCLIClaim(original, claim, a, original.Revision+2) || - !sameCLIClaim(w.operation, claim, a, w.operation.Revision) || !sameCLIWait(original.Wait, o.Wait) || !sameCLIWait(w.operation.Wait, o.Wait) { - return conflict() - } - if err = core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, cliPauseNoStartEvent, a.ID, a.Revision+1, cliPauseNoStartRecord{OperationID: o.ID, PauseRevision: w.pauseRevision}); err != nil { - return err + var receipt int64 + err := settleOwnedCLIWithinWindows(ctx, func(local context.Context) error { + if receipt != 0 { + committed, err := e.readCLIPauseSettlement(local, w, receipt) + if err != nil || committed { + return err + } + receipt = 0 } - _, err = e.advanceAttemptWithCLIPause(ctx, tx, o, a, "failed", cliPauseNoStartReason, "", true) - return err + return e.store.BackgroundWrite(local, func(ctx context.Context, tx *sql.Tx) error { + a, o, err := readCLIPauseNoStart(ctx, tx, admitted.ProjectID, admitted.ID) + if err != nil { + return err + } + claim := o + claim.State = "preparing" + if !sameCLIPauseAttempt(a, w.attempt) || !sameCLIClaim(original, claim, a, original.Revision+2) || + !sameCLIClaim(w.operation, claim, a, w.operation.Revision) || !sameCLIWait(original.Wait, o.Wait) || !sameCLIWait(w.operation.Wait, o.Wait) { + return conflict() + } + if err = core.AppendEvent(ctx, tx, core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID}, + cliPauseNoStartEvent, a.ID, a.Revision+1, cliPauseNoStartRecord{OperationID: o.ID, PauseRevision: w.pauseRevision}); err != nil { + return err + } + var sequence int64 + if err := tx.QueryRowContext(ctx, "SELECT last_insert_rowid()").Scan(&sequence); err != nil { + return err + } + if sequence <= 0 { + return conflict() + } + if _, err := e.advanceAttemptWithCLIPause(ctx, tx, o, a, "failed", cliPauseNoStartReason, "", true); err != nil { + return err + } + receipt = sequence + return nil + }) }) + if err != nil && receipt != 0 { + readCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + defer cancel() + if committed, _ := e.readCLIPauseSettlement(readCtx, w, receipt); committed { + err = nil + } + } if err == nil { e.notifyOperation(admitted.OperationID) } return err } +// Acknowledgement is read-only and belongs to the one-use live witness. +// A live successor cannot substitute for proof of the original settlement. +func (e *Engine) readCLIPauseSettlement(ctx context.Context, w *cliPauseNoStart, sequence int64) (bool, error) { + tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return false, err + } + defer tx.Rollback() + o := w.operation + var exact bool + var recorded any + err = tx.QueryRowContext(ctx, `SELECT project_id=? AND event_type=? AND resource_id=? AND actor_id=? AND typeof(revision)='integer' AND revision=? AND payload_json=?,created_at + FROM events WHERE sequence=?`, o.ProjectID, cliPauseNoStartEvent, w.attempt.ID, o.ActorID, w.attempt.Revision+1, + encoded(cliPauseNoStartRecord{OperationID: o.ID, PauseRevision: w.pauseRevision}), sequence).Scan(&exact, &recorded) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + stamp, ok := recorded.(string) + if !exact || !ok || !roundTime(stamp) { + return false, conflict() + } + a, err := readAttempt(ctx, tx, o.ProjectID, w.attempt.ID) + if err != nil { + return false, err + } + expected := w.attempt + expected.State, expected.Revision = "failed", expected.Revision+1 + if !sameCLIPauseAttempt(a, expected) { + return false, conflict() + } + o.AttemptID = "" + _, proved, err := historicalCLIPauseBeforeStart(ctx, tx, o, a) + if err != nil { + return false, err + } + if !proved { + return false, conflict() + } + return true, nil +} + func validateCLIPauseNoStartRecord(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) error { var body sql.NullString var actor, revision, eventType any diff --git a/internal/reviewexec/cli_policy_settlement_test.go b/internal/reviewexec/cli_policy_settlement_test.go index 65e2d65c6..7c361ea98 100644 --- a/internal/reviewexec/cli_policy_settlement_test.go +++ b/internal/reviewexec/cli_policy_settlement_test.go @@ -41,12 +41,18 @@ func TestPreparedCLIAdmissionRefusalSettlement(t *testing.T) { before := cliAllowanceState(t, f, a) original := roundOperation(t, f, a.OperationID) var settled Attempt + var receipt *preparedCLISettlement err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { op, err := readOperationBase(ctx, tx, a.ProjectID, a.OperationID) if err != nil { return err } - settled, err = f.e.settleCLIAdmissionRefusal(ctx, tx, op, a, anchor, refusal) + kind := preparedCLIRefusalPolicy + if scenario == "scheduling" { + kind = preparedCLIRefusalScheduling + } + receipt = &preparedCLISettlement{operation: op, attempt: a, anchor: anchor, refusal: refusal, kind: kind} + settled, err = f.e.recordPreparedCLISettlement(ctx, tx, receipt) if scenario == "publication-failure" && !errors.Is(err, publicationFailure) { t.Errorf("expected attempt publication to fail, got %v", err) } @@ -64,6 +70,9 @@ func TestPreparedCLIAdmissionRefusalSettlement(t *testing.T) { if err != nil { t.Fatal(err) } + if exact, err := f.e.readPreparedCLISettlement(t.Context(), receipt); err != nil || !exact { + t.Fatal("ordinary settlement did not retain its exact positive allowance acknowledgement", exact, err) + } queued := roundOperation(t, f, a.OperationID) if settled.ID != a.ID || settled.Revision != 2 || settled.State != "held" || queued.ID != original.ID || queued.Revision != original.Revision+1 || queued.State != "queued" || @@ -78,3 +87,68 @@ func TestPreparedCLIAdmissionRefusalSettlement(t *testing.T) { }) } } + +func TestPreparedCLISettlementDoesNotAdmitAfterPolicyRecovers(t *testing.T) { + f, a, input := cliAllowanceFixture(t) + if err := f.e.RecordCLIAllowance(t.Context(), a.ProjectID, a.ID, a.Revision, input); err != nil { + t.Fatal(err) + } + o := roundOperation(t, f, a.OperationID) + before := cliAllowanceState(t, f, a) + refused := newStoredUnavailable(storedPolicyHistory, "Policy history was not available before retry.") + pending := &preparedCLISettlement{operation: o, attempt: a, anchor: input.Anchor, refusal: refused, kind: preparedCLIRefusalPolicy} + if _, err := f.e.retryPreparedCLISettlement(t.Context(), pending); !errors.Is(err, refused) { + t.Fatalf("healthy policy was not left to a fresh admission: %v", err) + } + if after := cliAllowanceState(t, f, a); after != before { + t.Fatal("resolving the original refusal changed the retained preparation") + } +} + +func TestCLIPauseSettlementReadsOnlyOriginalReceipt(t *testing.T) { + f := schedulingFixture(t) + request := f.enqueue(t, attemptProject, "pause-original-receipt", "cli", 2, 1) + original := roundOperation(t, f, request.ID) + prepared, err := f.e.startAttempt(t.Context(), original.ProjectID, original.ID, 0, original.Revision) + if err != nil { + t.Fatal(err) + } + anchor := attemptAnchor(original.ProjectID, original.PullNumber) + observation := CLIAllowanceObservation{Anchor: anchor, ObservedAt: stamp(), Remaining: 2, Limit: 5, RollingWindowMS: 3600000, ChangedFiles: 2} + if err = f.e.RecordCLIAllowance(t.Context(), original.ProjectID, prepared.ID, prepared.Revision, observation); err != nil { + t.Fatal(err) + } + admitted, err := f.e.Admit(t.Context(), original.ProjectID, prepared.ID, prepared.Revision, anchor, "") + if err != nil { + t.Fatal(err) + } + schedulingPause(t, f, 2, 0, true) + refusal, err := f.e.VerifyCLIAction(t.Context(), original.ProjectID, admitted.ID, admitted.Revision) + if err != nil || !refusal.HasCLIStartRefusal() { + t.Fatalf("scoped pause not recognized: %v", err) + } + if err = f.e.settleCLIPauseNoStart(t.Context(), original, admitted, refusal.cliPause); err != nil { + t.Fatal(err) + } + var sequence int64 + if err = f.store.DB().QueryRow("SELECT sequence FROM events WHERE project_id=? AND resource_id=? AND event_type=?", original.ProjectID, admitted.ID, cliPauseNoStartEvent).Scan(&sequence); err != nil { + t.Fatal(err) + } + schedulingPause(t, f, 2, 1, false) + 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 == admitted.ID { + t.Fatalf("ordinary successor did not receive a fresh claim: %v", err) + } + before := roundOperation(t, f, request.ID) + if committed, err := f.e.readCLIPauseSettlement(t.Context(), refusal.cliPause, sequence); err != nil || !committed { + t.Fatalf("original acknowledgement not confirmed: %v", err) + } + if err = f.e.settleCLIPauseNoStart(t.Context(), original, admitted, refusal.cliPause); err == nil { + t.Fatal("separate invocation reused consumed witness") + } + after := roundOperation(t, f, request.ID) + if after.Revision != before.Revision || after.AttemptID != before.AttemptID || after.State != before.State { + t.Fatal("original acknowledgement changed successor") + } +} diff --git a/internal/reviewexec/cli_prepared_settlement.go b/internal/reviewexec/cli_prepared_settlement.go new file mode 100644 index 000000000..3788fa2cc --- /dev/null +++ b/internal/reviewexec/cli_prepared_settlement.go @@ -0,0 +1,173 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "time" + + "github.com/benhook1013/FireController/internal/core" +) + +const ( + preparedCLISettlementEvent = "review.cli_prepared_admission_settlement" + preparedCLIRefusalScheduling = "scheduling" + preparedCLIRefusalPolicy = "policy" +) + +// Kept only by the live caller that observed the exact prepared refusal. +type preparedCLISettlement struct { + operation Operation + attempt Attempt + anchor Anchor + refusal error + kind string + result Attempt + sequence int64 +} + +func transientPreparedCLISettlement(err error) bool { + var failure *core.Error + return errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &failure) && failure.Code == "overloaded") +} + +func (e *Engine) recordPreparedCLISettlement(ctx context.Context, tx *sql.Tx, p *preparedCLISettlement) (Attempt, error) { + result, err := e.settleCLIAdmissionRefusal(ctx, tx, p.operation, p.attempt, p.anchor, p.refusal) + if err != nil { + return Attempt{}, err + } + o := p.operation + scope := core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID} + claim := unusedCLISettlementRecord{OperationID: o.ID, ClaimRevision: o.Revision} + if err := core.AppendEvent(ctx, tx, scope, preparedCLISettlementEvent, p.attempt.ID, result.Revision, claim); err != nil { + return Attempt{}, err + } + var sequence int64 + if err := tx.QueryRowContext(ctx, "SELECT last_insert_rowid()").Scan(&sequence); err != nil { + return Attempt{}, err + } + if sequence <= 0 { + return Attempt{}, conflict() + } + p.result, p.sequence = result, sequence + return result, nil +} + +func (e *Engine) retryPreparedCLISettlement(ctx context.Context, p *preparedCLISettlement) (Attempt, error) { + var result Attempt + err := retryRunSelectionLocal(ctx, func() error { + if p.sequence != 0 { + committed, err := e.readPreparedCLISettlement(ctx, p) + if err != nil { + return err + } + if committed { + result = p.result + return nil + } + p.sequence = 0 + } + return e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + a, err := readAttempt(ctx, tx, p.operation.ProjectID, p.attempt.ID) + if err != nil { + return err + } + o, err := readOperation(ctx, tx, p.operation.ProjectID, p.operation.ID) + if err != nil { + return err + } + if a != p.attempt || !sameCLIClaim(p.operation, o, a, p.operation.Revision) || !sameCLIWait(p.operation.Wait, o.Wait) { + return conflict() + } + switch p.kind { + case preparedCLIRefusalScheduling: + var history *schedulingHistoryUnavailable + var binding *operationSelectionBindingStateError + err = e.requireAutomaticOperation(ctx, tx, o) + if errors.As(err, &binding) { + return p.refusal + } + if err == nil || schedulingRefused(err) || !errors.As(err, &history) { + if transientPreparedCLISettlement(err) { + return err + } + return p.refusal + } + case preparedCLIRefusalPolicy: + _, _, err = boundPolicy(ctx, tx, o) + if !isStoredUnavailable(err, storedPolicyHistory) { + if transientPreparedCLISettlement(err) { + return err + } + return p.refusal + } + default: + return conflict() + } + result, err = e.recordPreparedCLISettlement(ctx, tx, p) + return err + }) + }) + if err != nil && p.sequence != 0 { + readCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + defer cancel() + if committed, _ := e.readPreparedCLISettlement(readCtx, p); committed { + return p.result, nil + } + } + return result, err +} + +// A confirmed missing sequence permits only the original guarded write. Any +// unreadable or mismatched evidence fails closed and cannot authorize retry. +func (e *Engine) readPreparedCLISettlement(ctx context.Context, p *preparedCLISettlement) (bool, error) { + tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return false, err + } + defer tx.Rollback() + o, a := p.operation, p.attempt + var exact bool + var at any + err = tx.QueryRowContext(ctx, `SELECT project_id=? AND event_type=? AND resource_id=? AND typeof(revision)='integer' + AND revision=? AND actor_id=? AND payload_json=?, created_at FROM events WHERE sequence=?`, + o.ProjectID, preparedCLISettlementEvent, a.ID, p.result.Revision, o.ActorID, + encoded(unusedCLISettlementRecord{OperationID: o.ID, ClaimRevision: o.Revision}), p.sequence).Scan(&exact, &at) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + stamp, ok := at.(string) + if !exact || !ok || !roundTime(stamp) { + return false, conflict() + } + held, err := readAttempt(ctx, tx, o.ProjectID, a.ID) + if err != nil { + return false, err + } + if held != p.result || held.State != "held" || held.Revision != a.Revision+1 { + return false, conflict() + } + preflight, err := readCLIAllowanceRecord(ctx, tx, o, held) + if err != nil { + return false, err + } + if preflight.Observation.Remaining <= 0 || preflight.Observation.Anchor != p.anchor { + return false, conflict() + } + err = tx.QueryRowContext(ctx, `SELECT + (SELECT count(*) FROM review_execution_transitions WHERE attempt_id=?)=2 + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=1 AND state='preparing' AND reason='preparing' AND external_id='') + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=2 AND state='held' AND reason='automatic_scheduling_unavailable' AND external_id='') + AND NOT EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=?) + AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, a.ID, a.ID, a.ID, a.ID, a.ID).Scan(&exact) + if err != nil { + return false, err + } + if !exact { + return false, conflict() + } + return true, nil +} diff --git a/internal/reviewexec/live_cli_preparation_settlement_test.go b/internal/reviewexec/live_cli_preparation_settlement_test.go index e7a38ca31..5a0ec54ba 100644 --- a/internal/reviewexec/live_cli_preparation_settlement_test.go +++ b/internal/reviewexec/live_cli_preparation_settlement_test.go @@ -195,6 +195,10 @@ func TestUnusedCLIPreparationConfirmsExactCommittedSettlement(t *testing.T) { 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/run_selection.go b/internal/reviewexec/run_selection.go index e78df5929..08d23bbb4 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -543,7 +543,7 @@ func unprovedQueuedHostedPause(ctx context.Context, tx *sql.Tx, project string) return false, err } for _, pull := range pulls { - s, err := readPullScheduling(ctx, tx, project, pull) + _, err := readPullScheduling(ctx, tx, project, pull) if err != nil { var invalid *pullSchedulingStateError if errors.As(err, &invalid) { @@ -551,9 +551,6 @@ func unprovedQueuedHostedPause(ctx context.Context, tx *sql.Tx, project string) } return false, err } - if !s.Paused { - return true, nil - } } return false, nil } diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index b6b2a7136..79dff8dc0 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -22,9 +22,9 @@ type selectionRequestedEvent struct { } func readSelectionRequestedEvent(ctx context.Context, q EvidenceQuery, r Run) (selectionRequestedEvent, error) { - rows, err := q.QueryContext(ctx, `SELECT sequence,actor_id, + rows, err := q.QueryContext(ctx, `SELECT sequence,actor_id,typeof(event_type), CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END - FROM events WHERE project_id=? AND event_type='review.selection_requested' AND resource_id=? AND revision=1 LIMIT 2`, r.ProjectID, r.ID) + FROM events WHERE project_id=? AND (event_type='review.selection_requested' OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.selection_requested')) AND resource_id=? AND revision=1 LIMIT 2`, r.ProjectID, r.ID) if err != nil { return selectionRequestedEvent{}, err } @@ -34,12 +34,13 @@ func readSelectionRequestedEvent(ctx context.Context, q EvidenceQuery, r Run) (s } var actor any var sequence int64 + var eventType string var body sql.NullString - if err = rows.Scan(&sequence, &actor, &body); err != nil { + if err = rows.Scan(&sequence, &actor, &eventType, &body); err != nil { return selectionRequestedEvent{}, err } var event selectionRequestedEvent - if sequence < 1 || actor != r.ActorID || !body.Valid || strictjson.Decode([]byte(body.String), &event) != nil || event.Channel != r.Channel || body.String != encoded(event) { + if sequence < 1 || eventType != "text" || actor != r.ActorID || !body.Valid || strictjson.Decode([]byte(body.String), &event) != nil || event.Channel != r.Channel || body.String != encoded(event) { return selectionRequestedEvent{}, schedulingUnavailable() } switch event.Origin { diff --git a/internal/reviewexec/run_selection_schema.go b/internal/reviewexec/run_selection_schema.go index 4dfaa4eaa..dcf237017 100644 --- a/internal/reviewexec/run_selection_schema.go +++ b/internal/reviewexec/run_selection_schema.go @@ -79,7 +79,11 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro SELECT 1 FROM review_selections s WHERE s.project_id=? AND s.reason='linked_selection_quarantined' AND NOT EXISTS (SELECT 1 FROM review_selection_quarantine d - WHERE d.project_id=s.project_id AND d.selection_id=s.id))`, project).Scan(&unproved); err != nil { + WHERE d.project_id=s.project_id AND d.selection_id=s.id + AND typeof(d.original_operation_id)='text' + AND length(CAST(d.original_operation_id AS BLOB)) BETWEEN 1 AND 128 + AND length(CAST(d.original_operation_id AS BLOB))=length(d.original_operation_id) + AND d.original_operation_id NOT GLOB '*[^A-Za-z0-9_-]*'))`, project).Scan(&unproved); err != nil { return err } if unproved { diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 029f73e8e..5efa2d3e3 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -170,6 +170,7 @@ type runChoice struct { number int64 head string automaticQueueLimit *int + automaticGrantBlocked bool claimAutomaticQueueLimit *int automaticBasisRevision int64 automaticPullScheduling []int64 @@ -304,6 +305,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 var pullScheduling, grantRevisions []int64 defer func() { result.automaticQueueLimit = automaticQueueLimit + result.automaticGrantBlocked = grantBlocked result.automaticBasisRevision = basisRevision result.automaticPullScheduling = pullScheduling result.automaticGrantRevisions = grantRevisions @@ -837,14 +839,15 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat // front frame; it is not equivalent to an ordinary revision change. revisions, resultErr = readAutomaticPullSchedulingRevisionsBound(ctx, tx, r.ProjectID, boundPrefix, true, choice.automaticPullScheduling) settle = resultErr == nil && slices.Equal(revisions, choice.automaticPullScheduling) - if settle && (pull > 0 || choice.sourceReason != "") { + if settle { grants, err := readAutomaticGrantRevisions(ctx, tx, r.ProjectID, r.Channel, boundPrefix) resultErr = err settle = err == nil && slices.Equal(grants, choice.automaticGrantRevisions) } } } - if settle && pull > 0 { + // Explicit selection has no automatic basis to acknowledge. + if settle && pull > 0 && choice.automaticQueueLimit != nil { index := slices.IndexFunc(choice.prefix, func(plan SourcePlan) bool { return plan.Pull.Number == pull }) settle = index >= 0 && choice.prefix[index].Pull.HeadSHA == choice.head if settle { @@ -907,10 +910,15 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat // The existing binding pins the configured queue. If its // waiting boundary moved while reading source, do not settle // stale source bounds without an ordinary fresh read. - limit, err := e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + limit, blocked, err := e.automaticQueuedPrefixBounds(ctx, tx, r.ProjectID, c, r.Channel) if err != nil { return err } + if blocked != choice.automaticGrantBlocked { + // Equal numeric prefixes need not carry the same grant proof. + bindingValidated = false + return updateRun(ctx, tx, current, "held", "automatic_scheduling_unavailable", "") + } if limit != *choice.automaticQueueLimit || (choice.claimAutomaticQueueLimit != nil && limit > *choice.claimAutomaticQueueLimit) { return updateRun(ctx, tx, current, "held", "selection_changed", "") } diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index 64fbf0df1..7a7ab9222 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -281,7 +281,7 @@ func (e *Engine) ConfigurePullScheduling(ctx context.Context, scope core.Scope, if err != nil { return nil, err } - if old.Revision != *input.ExpectedRevision { + if old.Revision != *input.ExpectedRevision || (*input.Paused && old.Revision == math.MaxInt64-1) { return nil, conflict() } reason := input.Reason diff --git a/internal/reviewexec/scheduling_authority.go b/internal/reviewexec/scheduling_authority.go index 9fc1b08b4..0b6edb00c 100644 --- a/internal/reviewexec/scheduling_authority.go +++ b/internal/reviewexec/scheduling_authority.go @@ -30,16 +30,16 @@ func schedulingAuthorityContinuity(ctx context.Context, tx *sql.Tx, project, act } rows, err := tx.QueryContext(ctx, `WITH settings AS ( SELECT resource_id,revision,count(*) AS copies,max(actor_id) AS actor_id,max(sequence) AS sequence, - max(CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END) AS body - FROM events WHERE project_id=? AND resource_id=? AND event_type='review.scheduling_updated' AND revision BETWEEN ? AND ? + max(CASE WHEN typeof(event_type)='text' AND typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END) AS body + FROM events WHERE project_id=? AND resource_id=? AND (event_type='review.scheduling_updated' OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.scheduling_updated')) AND revision BETWEEN ? AND ? GROUP BY resource_id,revision ) SELECT w.resource_id,w.actor_id,w.revision,w.sequence, - CASE WHEN typeof(w.payload_json)='text' AND length(CAST(w.payload_json AS BLOB))<=4096 THEN w.payload_json END, + CASE WHEN typeof(w.event_type)='text' AND typeof(w.payload_json)='text' AND length(CAST(w.payload_json AS BLOB))<=4096 THEN w.payload_json END, CASE WHEN u.copies=1 AND typeof(u.actor_id)='text' AND u.actor_id=w.actor_id AND u.sequence0 AND typeof(w.revision)='integer' AND w.revision>0 AND w.copies=1 AND typeof(w.payload_json)='text' AND length(CAST(w.payload_json AS BLOB))<=4096 AND (SELECT count(*) FROM events u WHERE u.project_id=w.project_id AND u.resource_id=w.resource_id - AND u.event_type='review.scheduling_updated' AND u.revision=w.revision)=1 + AND (u.event_type='review.scheduling_updated' OR (typeof(u.event_type)='blob' AND CAST(u.event_type AS TEXT)='review.scheduling_updated')) AND u.revision=w.revision)=1 AND EXISTS(SELECT 1 FROM events u WHERE u.project_id=w.project_id AND u.resource_id=w.resource_id AND u.event_type='review.scheduling_updated' AND u.revision=w.revision AND u.actor_id=w.actor_id AND u.sequence'text' OR typeof(revision)<>'integer' OR revision<1 OR created_at IS NULL OR julianday(created_at) IS NULL OR + SELECT *, (typeof(event_type)<>'text' OR typeof(revision)<>'integer' OR revision<1 OR created_at IS NULL OR (prev_revision IS NOT NULL AND revision<=prev_revision)) AS invalid_event FROM represented_history ) SELECT project_id,pull_number,control_revision,paused,control_actor, CASE WHEN NOT invalid_event THEN revision END,actor_id,payload,created_at - FROM relevant WHERE invalid_event OR revision>=control_revision + FROM relevant ORDER BY project_id,pull_number` func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) error { @@ -434,8 +434,14 @@ func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) return err } revision, integer := nativeRevision.(int64) + if !integer || !createdAt.Valid || !roundTime(createdAt.String) { + return schedulingUnavailable() + } + if revision < controlRevision { + continue + } eventActor, textActor := nativeEventActor.(string) - if (project == lastProject && pull == lastPull) || !integer || !textActor || revision != controlRevision || eventActor != actor || !createdAt.Valid || !roundTime(createdAt.String) || !validPullSchedulingPayload(payload, pull, paused == 1) { + if (project == lastProject && pull == lastPull) || !textActor || revision != controlRevision || eventActor != actor || !validPullSchedulingPayload(payload, pull, paused == 1) { return schedulingUnavailable() } count++ diff --git a/internal/reviewexec/scheduling_source_hold_basis_test.go b/internal/reviewexec/scheduling_source_hold_basis_test.go index 7ed1d2289..72f0498e3 100644 --- a/internal/reviewexec/scheduling_source_hold_basis_test.go +++ b/internal/reviewexec/scheduling_source_hold_basis_test.go @@ -54,12 +54,13 @@ func TestAutomaticSourceHoldRetainsOnlyItsBoundPullSchedulingBasis(t *testing.T) 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 string - if err := f.store.DB().QueryRow(`SELECT basis_sha256,settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, receipt.ID).Scan(&accepted, &settled); err != nil { + 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 != "" { - t.Fatalf("unverified source hold did not retain only accepted basis: edited=%v accepted=%q settled=%q", edited, accepted, settled) + 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/supervisor.go b/internal/reviewexec/supervisor.go index b006690b4..f92b4456c 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -70,8 +70,9 @@ func RetainedCLIExhaustionHandoff(err error, source CLIExhaustionRecoverySource, func (e *Engine) settleCLIPreparationHandoff(ctx context.Context, original Operation, a Attempt, h *CLIPreparationHandoff) error { if h.source == nil { + ack := &unusedCLISettlementAck{} return settleOwnedCLIWithinWindows(ctx, func(local context.Context) error { - return e.settleUnusedCLIPreparation(local, original, a) + return e.settleUnusedCLIPreparationWithAck(local, original, a, ack) }) } local, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) From 32eac8c45d68b1ea29b1a6796c7c886cc94e0be3 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 00:26:59 +1300 Subject: [PATCH 28/34] Address combined Hosted and CLI review findings --- internal/backup/inventory.go | 25 +++++ .../adoption_holds_integration_test.go | 8 +- internal/reviewexec/attempts.go | 92 ++++++++++++------- internal/reviewexec/cli_pause_no_start.go | 19 ++-- .../reviewexec/cli_prepared_settlement.go | 37 +++----- internal/reviewexec/front_evaluator.go | 6 +- internal/reviewexec/hosted_priority.go | 12 ++- internal/reviewexec/run_selection.go | 40 ++++---- internal/reviewexec/run_selection_origin.go | 21 ++++- internal/reviewexec/run_selection_schema.go | 73 +++++++++++---- internal/reviewexec/run_selection_snapshot.go | 8 ++ internal/reviewexec/run_selection_worker.go | 24 ++++- internal/reviewexec/scheduling.go | 7 +- internal/reviewexec/scheduling_authority.go | 9 +- .../scheduling_authorization_continuity.go | 7 +- internal/reviewexec/scheduling_snapshot.go | 49 +++++++--- internal/reviewexec/supervisor.go | 2 +- 17 files changed, 296 insertions(+), 143 deletions(-) diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index 6e47d067b..62c6c8d78 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -632,7 +632,13 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ } return nil, err } + } else if err = validateAbsentSchedulingSchema(ctx, db); err != nil { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, err } + if versions["worker_retirements"] > 0 { if err := validatePhysicalSchemaObjects(ctx, db, map[string]physicalSchemaObject{"worker_retirements": {"table", `CREATE TABLE worker_retirements(project_id TEXT NOT NULL REFERENCES projects(id),worker_id TEXT NOT NULL,retired_at TEXT NOT NULL,actor_id TEXT NOT NULL,PRIMARY KEY(project_id,worker_id),FOREIGN KEY(project_id,worker_id) REFERENCES workers(project_id,id))`}}, []string{"worker_retirements"}); err != nil { if contextErr := checkContext(ctx); contextErr != nil { @@ -1701,6 +1707,25 @@ func validateExternalHostedEvidenceIndexes(ctx context.Context, db sqlReader, ve return nil } +func validateAbsentSchedulingSchema(ctx context.Context, db sqlReader) error { + var params []string + var names []any + for _, statement := range reviewexec.SchedulingSchemaV2SQL() { + fields := strings.Fields(statement) + if len(fields) < 3 { + return invalid() + } + name, _, _ := strings.Cut(fields[2], "(") + params = append(params, "?") + names = append(names, name) + } + var present bool + if err := db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name COLLATE NOCASE IN ("+strings.Join(params, ",")+"))", names...).Scan(&present); err != nil || present { + return invalid() + } + return nil +} + func validateSchedulingPhysicalSchema(ctx context.Context, db sqlReader, version int) error { expected := map[string]physicalSchemaObject{} statements := reviewexec.SchedulingSchemaSQL() diff --git a/internal/reviewexec/adoption_holds_integration_test.go b/internal/reviewexec/adoption_holds_integration_test.go index df8dca9c7..84a25474a 100644 --- a/internal/reviewexec/adoption_holds_integration_test.go +++ b/internal/reviewexec/adoption_holds_integration_test.go @@ -712,9 +712,13 @@ func TestSchedulingCorruptionContinuesHealthyCandidateInSamePass(t *testing.T) { t.Run(channel, func(t *testing.T) { f := newAttemptFixture(t) f.configure(t, attemptProject, "test-capability", 0, false) - f.enqueue(t, attemptProject, "first-corrupt", channel, 2, 1) + first := f.enqueue(t, attemptProject, "first-corrupt", channel, 2, 1) f.configure(t, otherAttemptProject, "test-capability", 0, false) - f.enqueue(t, otherAttemptProject, "later-healthy", channel, 2, 1) + later := f.enqueue(t, otherAttemptProject, "later-healthy", channel, 2, 1) + // Fixed-width second boundaries make the persisted queue order + // independent of RFC3339Nano fractional-length text sorting. + admissionSQL(t, f, `UPDATE review_operations SET created_at=? WHERE id=?`, "2001-01-01T00:00:00Z", first.ID) + admissionSQL(t, f, `UPDATE review_operations SET created_at=? WHERE id=?`, "2001-01-01T00:00:01Z", later.ID) corruptPrepared := false driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { if o.ProjectID == attemptProject { diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 66004c23e..56b8fb453 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -380,8 +380,10 @@ func (e *Engine) admit(ctx context.Context, project, id string, expectedRevision return settlement.result, nil } } - if ctx.Err() == nil && transientPreparedCLISettlement(err) { - retryCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + if transientPreparedCLISettlement(err) || ctx.Err() != nil && errors.Is(err, ctx.Err()) { + // Finish only the bounded, readback-proved local settlement, even + // when the admitting worker is stopped. This cannot admit work. + retryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) result, err = e.retryPreparedCLISettlement(retryCtx, settlement) cancel() if err == nil { @@ -454,27 +456,14 @@ func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operat func (e *Engine) settleUnusedCLIPreparationWithAck(ctx context.Context, original Operation, captured Attempt, ack *unusedCLISettlementAck) error { if ack.sequence != 0 { - // Reconcile the previous callback before trying the original claim again. - // It may already be terminal even though the supervisor lost its acknowledgement. - if e.readUnusedCLISettlementReceipt(ctx, original, captured, ack.attempt, ack.sequence) { - e.notifyOperation(captured.OperationID) - return nil - } - var exists bool - if err := e.store.DB().QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM events WHERE sequence=?)", ack.sequence).Scan(&exists); err != nil { + committed, err := e.probeUnusedCLISettlementReceipt(ctx, original, captured, ack.attempt, 0) + if err != nil { return err } - if exists { - // A separate successful read saw that position; try the exact receipt - // again before refusing. Never write across an ambiguous receipt. - if e.readUnusedCLISettlementReceipt(ctx, original, captured, ack.attempt, ack.sequence) { - e.notifyOperation(captured.OperationID) - return nil - } - return conflict() + if committed { + e.notifyOperation(captured.OperationID) + return nil } - // No committed event at that position. The original transaction guards - // still prove ownership and prevent a stale claim from doing anything. *ack = unusedCLISettlementAck{} } err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { @@ -545,27 +534,56 @@ func (e *Engine) settleUnusedCLIPreparationWithAck(ctx context.Context, original // Reconcile the exact attempt-local settlement receipt without consulting the // successor. This is acknowledgement only; it cannot grant new work. func (e *Engine) readUnusedCLISettlementReceipt(ctx context.Context, original Operation, captured, proposed Attempt, sequence int64) bool { - if sequence <= 0 || original.ProjectID != captured.ProjectID || original.ID != captured.OperationID || original.Channel != "cli" || - captured.State != "preparing" || captured.Revision != 1 || captured.Anchor != nil || captured.Intent != "" || captured.ExternalID != "" { + if sequence <= 0 { return false } + committed, _ := e.probeUnusedCLISettlementReceipt(ctx, original, captured, proposed, sequence) + return committed +} + +// A rolled-back SQLite sequence can be reused. Match the old attempt's own +// event; absence permits the original CAS, not an unrelated event at that slot. +func scanCLISettlementEvent(ctx context.Context, tx *sql.Tx, project, attemptID, eventType, actor string, revision int64, record any, expectedSequence int64) (bool, error) { + var storedActor, storedRevision, body, created any + var count int64 + err := tx.QueryRowContext(ctx, `SELECT actor_id,revision,payload_json,created_at,count(*) OVER () + FROM (SELECT actor_id,revision,payload_json,created_at FROM events + WHERE project_id=? AND resource_id=? AND event_type=? AND (?=0 OR sequence=?) LIMIT 2)`, + project, attemptID, eventType, expectedSequence, expectedSequence).Scan(&storedActor, &storedRevision, &body, &created, &count) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + stamp, ok := created.(string) + if count != 1 || storedActor != actor || storedRevision != revision || body != encoded(record) || !ok || !roundTime(stamp) { + return false, conflict() + } + return true, nil +} + +func (e *Engine) probeUnusedCLISettlementReceipt(ctx context.Context, original Operation, captured, proposed Attempt, expectedSequence int64) (bool, error) { + if original.ProjectID != captured.ProjectID || original.ID != captured.OperationID || original.Channel != "cli" || + captured.State != "preparing" || captured.Revision != 1 || captured.Anchor != nil || captured.Intent != "" || captured.ExternalID != "" { + return false, conflict() + } tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) if err != nil { - return false + return false, err } defer tx.Rollback() + record := unusedCLISettlementRecord{OperationID: original.ID, ClaimRevision: original.Revision + 1} + exists, err := scanCLISettlementEvent(ctx, tx, captured.ProjectID, captured.ID, unusedCLISettlementEvent, original.ActorID, proposed.Revision, record, expectedSequence) + if err != nil || !exists { + return false, err + } a, err := readAttempt(ctx, tx, captured.ProjectID, captured.ID) - if err != nil || a != proposed || a.State != "held" || a.Revision != 2 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { - return false + if err != nil { + return false, err } - record := unusedCLISettlementRecord{OperationID: original.ID, ClaimRevision: original.Revision + 1} - var at any - err = tx.QueryRowContext(ctx, `SELECT created_at FROM events WHERE sequence=? AND project_id=? AND event_type=? AND - resource_id=? AND typeof(revision)='integer' AND revision=? AND actor_id=? AND payload_json=?`, - sequence, captured.ProjectID, unusedCLISettlementEvent, captured.ID, a.Revision, original.ActorID, encoded(record)).Scan(&at) - stamp, native := at.(string) - if err != nil || !native || !roundTime(stamp) { - return false + if a != proposed || a.State != "held" || a.Revision != 2 || a.Anchor != nil || a.Intent != "" || a.ExternalID != "" { + return false, conflict() } var exact bool err = tx.QueryRowContext(ctx, `SELECT @@ -575,7 +593,13 @@ func (e *Engine) readUnusedCLISettlementReceipt(ctx context.Context, original Op AND NOT EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=?) AND NOT EXISTS(SELECT 1 FROM review_cli_preflight WHERE attempt_id=?) AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, a.ID, a.ID, a.ID, a.ID, a.ID, a.ID).Scan(&exact) - return err == nil && exact + if err != nil { + return false, err + } + if !exact { + return false, conflict() + } + return true, nil } // Reconcile only the exact guarded transaction whose acknowledgement was diff --git a/internal/reviewexec/cli_pause_no_start.go b/internal/reviewexec/cli_pause_no_start.go index 6db38cebf..afb0bf2c3 100644 --- a/internal/reviewexec/cli_pause_no_start.go +++ b/internal/reviewexec/cli_pause_no_start.go @@ -165,27 +165,20 @@ func (e *Engine) settleCLIPauseNoStart(ctx context.Context, original Operation, // Acknowledgement is read-only and belongs to the one-use live witness. // A live successor cannot substitute for proof of the original settlement. func (e *Engine) readCLIPauseSettlement(ctx context.Context, w *cliPauseNoStart, sequence int64) (bool, error) { + if sequence <= 0 { + return false, conflict() + } tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) if err != nil { return false, err } defer tx.Rollback() o := w.operation - var exact bool - var recorded any - err = tx.QueryRowContext(ctx, `SELECT project_id=? AND event_type=? AND resource_id=? AND actor_id=? AND typeof(revision)='integer' AND revision=? AND payload_json=?,created_at - FROM events WHERE sequence=?`, o.ProjectID, cliPauseNoStartEvent, w.attempt.ID, o.ActorID, w.attempt.Revision+1, - encoded(cliPauseNoStartRecord{OperationID: o.ID, PauseRevision: w.pauseRevision}), sequence).Scan(&exact, &recorded) - if errors.Is(err, sql.ErrNoRows) { - return false, nil - } - if err != nil { + record := cliPauseNoStartRecord{OperationID: o.ID, PauseRevision: w.pauseRevision} + committed, err := scanCLISettlementEvent(ctx, tx, o.ProjectID, w.attempt.ID, cliPauseNoStartEvent, o.ActorID, w.attempt.Revision+1, record, 0) + if err != nil || !committed { return false, err } - stamp, ok := recorded.(string) - if !exact || !ok || !roundTime(stamp) { - return false, conflict() - } a, err := readAttempt(ctx, tx, o.ProjectID, w.attempt.ID) if err != nil { return false, err diff --git a/internal/reviewexec/cli_prepared_settlement.go b/internal/reviewexec/cli_prepared_settlement.go index 3788fa2cc..30157e37c 100644 --- a/internal/reviewexec/cli_prepared_settlement.go +++ b/internal/reviewexec/cli_prepared_settlement.go @@ -87,23 +87,22 @@ func (e *Engine) retryPreparedCLISettlement(ctx context.Context, p *preparedCLIS if errors.As(err, &binding) { return p.refusal } - if err == nil || schedulingRefused(err) || !errors.As(err, &history) { - if transientPreparedCLISettlement(err) { - return err - } + if schedulingRefused(err) { return p.refusal } + if err != nil && !errors.As(err, &history) { + return err + } case preparedCLIRefusalPolicy: _, _, err = boundPolicy(ctx, tx, o) - if !isStoredUnavailable(err, storedPolicyHistory) { - if transientPreparedCLISettlement(err) { - return err - } - return p.refusal + if err != nil && !isStoredUnavailable(err, storedPolicyHistory) { + return err } default: return conflict() } + // Even if history recovered, retire this exact unused preparation. + // Its original queued request must pass fresh admission. result, err = e.recordPreparedCLISettlement(ctx, tx, p) return err }) @@ -118,7 +117,7 @@ func (e *Engine) retryPreparedCLISettlement(ctx context.Context, p *preparedCLIS return result, err } -// A confirmed missing sequence permits only the original guarded write. Any +// A confirmed missing attempt-local event permits only the original guarded write. Any // unreadable or mismatched evidence fails closed and cannot authorize retry. func (e *Engine) readPreparedCLISettlement(ctx context.Context, p *preparedCLISettlement) (bool, error) { tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) @@ -127,22 +126,12 @@ func (e *Engine) readPreparedCLISettlement(ctx context.Context, p *preparedCLISe } defer tx.Rollback() o, a := p.operation, p.attempt - var exact bool - var at any - err = tx.QueryRowContext(ctx, `SELECT project_id=? AND event_type=? AND resource_id=? AND typeof(revision)='integer' - AND revision=? AND actor_id=? AND payload_json=?, created_at FROM events WHERE sequence=?`, - o.ProjectID, preparedCLISettlementEvent, a.ID, p.result.Revision, o.ActorID, - encoded(unusedCLISettlementRecord{OperationID: o.ID, ClaimRevision: o.Revision}), p.sequence).Scan(&exact, &at) - if errors.Is(err, sql.ErrNoRows) { - return false, nil - } - if err != nil { + record := unusedCLISettlementRecord{OperationID: o.ID, ClaimRevision: o.Revision} + committed, err := scanCLISettlementEvent(ctx, tx, o.ProjectID, a.ID, preparedCLISettlementEvent, o.ActorID, p.result.Revision, record, 0) + if err != nil || !committed { return false, err } - stamp, ok := at.(string) - if !exact || !ok || !roundTime(stamp) { - return false, conflict() - } + var exact bool held, err := readAttempt(ctx, tx, o.ProjectID, a.ID) if err != nil { return false, err diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go index f1cc0ea07..85fb35efa 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -85,6 +85,9 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i if scheduling.Paused { return evaluatedFront{state: "held", reason: "pull_scheduling_paused", plan: plan}, nil } + if plan.Pull.State != "open" { + return evaluatedFront{state: "held", reason: "front_unavailable", plan: plan}, nil + } suppressed, err := e.automaticPullSuppressed(ctx, q, r, plan.Pull.Number) if err != nil { return evaluatedFront{}, err @@ -92,9 +95,6 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i if suppressed { return evaluatedFront{state: "held", reason: "automatic_intent_retained", plan: plan}, nil } - if plan.Pull.State != "open" { - return evaluatedFront{state: "held", reason: "front_unavailable", plan: plan}, nil - } return evaluatedFront{state: "ready", plan: plan}, nil } diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index e12d2c121..5a7474d09 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -108,6 +108,15 @@ func (e *Engine) hostedPriorityBinding(ctx context.Context, tx *sql.Tx, o Operat return false, err } var err error + if o.Channel == "cli" { + var dirty bool + if err := tx.QueryRowContext(ctx, "SELECT "+comparisonDirtyExists, o.ProjectID, o.PullNumber, o.Channel).Scan(&dirty); err != nil { + return false, err + } + if dirty { + return false, nil + } + } if o.Channel == "hosted" { var installed bool if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM metadata WHERE key='schema:reviews')`).Scan(&installed); err != nil { @@ -135,7 +144,8 @@ func (e *Engine) hostedPriorityBinding(ctx context.Context, tx *sql.Tx, o Operat // A proved mismatch removes only this candidate's priority. Its own // admission remains refused, and operational storage errors still return. var binding *operationSelectionBindingStateError - if errors.As(err, &binding) { + var selection *retainedSelectionStateError + if errors.As(err, &binding) || errors.As(err, &selection) { return false, nil } var refusal *core.Error diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 08d23bbb4..e17183367 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -247,28 +247,26 @@ func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configurati WHERE p.project_id=o.project_id AND p.pull_number=o.pull_number AND typeof(p.paused)='integer' AND p.paused=1)))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { return c, 0, "", err } - var unprovedPause bool - if r.Channel == "hosted" { - // The SQL predicate is only a shortlist. A queued operation - // may yield its turn only on a fully validated pull pause. - unprovedPause, err = unprovedQueuedHostedPause(ctx, tx, r.ProjectID) - if err != nil { - return c, 0, "", err - } - busy = busy || unprovedPause + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil { + return c, 0, "", err } - if busy && !unprovedPause { - var automatic bool - if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id=?)`, r.ProjectID, r.ID).Scan(&automatic); err != nil { - return c, 0, "", err - } - if automatic { - // Existing queued requests retain their turn; automatic front - // evaluation considers only the prefix before the earliest one. + if attribution.revision != 0 { + // The prefix planner owns queued candidacy, including exact local + // pause refusals. Executing or uncertain requests fence the lane. + if busy { if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND channel=? AND state IN ('preparing','posting','active','uncertain'))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { return c, 0, "", err } } + } else if r.Channel == "hosted" { + // Explicit Hosted selections require proved pause authority before + // yielding an existing queued operation. + unproved, err := unprovedQueuedHostedPause(ctx, tx, r.ProjectID) + if err != nil { + return c, 0, "", err + } + busy = busy || unproved } if busy { return c, repository, "review_inflight", nil @@ -628,6 +626,14 @@ func quarantineNativeSelection(ctx context.Context, tx *sql.Tx, project, id any, if inconsistent { return false, &unprovedSelectionCustodyError{runUnavailable()} } + direct, err := directOperationConflictsWithSelectionCustody(ctx, tx, pid, op) + if err != nil { + return false, err + } + if direct { + return false, &unprovedSelectionCustodyError{runUnavailable()} + } + // A conflicting retained diagnostic cannot prove this row's custody. // Detect only these known keys before writing, so recovery can isolate // this row without treating a database failure as a local refusal. diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index 79dff8dc0..22a7ef5b4 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -208,6 +208,18 @@ func hasDirectOperationReceipt(ctx context.Context, q EvidenceQuery, o Operation return direct, err } +func directOperationConflictsWithSelectionCustody(ctx context.Context, q EvidenceQuery, project, operation string) (bool, error) { + o, err := readOperationIdentity(ctx, q, project, operation) + if err != nil { + var known *core.Error + if errors.As(err, &known) && known.Code == "not_found" { + return false, nil + } + return false, err + } + return hasDirectOperationReceipt(ctx, q, o) +} + func selectionLocalHoldReason(ctx context.Context, q EvidenceQuery, r Run) (string, error) { event, err := readSelectionRequestedEvent(ctx, q, r) if err != nil && !automaticProjectRefused(err) { @@ -230,9 +242,9 @@ func selectionPredatesAutomation(ctx context.Context, tx *sql.Tx, r Run, accepte if err != nil || projected.Revision > 10000 { return false, err } - rows, err := tx.QueryContext(ctx, `SELECT sequence,revision, + rows, err := tx.QueryContext(ctx, `SELECT sequence,revision,typeof(event_type), CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END - FROM events WHERE project_id=? AND resource_id=? AND event_type='review.scheduling_updated' + FROM events WHERE project_id=? AND resource_id=? AND (event_type='review.scheduling_updated' OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.scheduling_updated')) ORDER BY sequence LIMIT 10001`, r.ProjectID, r.ProjectID) if err != nil { return false, err @@ -242,12 +254,13 @@ func selectionPredatesAutomation(ctx context.Context, tx *sql.Tx, r Run, accepte for rows.Next() { var sequence int64 var revision any + var eventType string var body sql.NullString - if err := rows.Scan(&sequence, &revision, &body); err != nil { + if err := rows.Scan(&sequence, &revision, &eventType, &body); err != nil { return false, err } control, _, _, valid := readSchedulingEventPayload(body, expected) - if revision != expected || !valid { + if revision != expected || eventType != "text" || !valid { return false, nil } enabled := control.Hosted diff --git a/internal/reviewexec/run_selection_schema.go b/internal/reviewexec/run_selection_schema.go index dcf237017..cb8145282 100644 --- a/internal/reviewexec/run_selection_schema.go +++ b/internal/reviewexec/run_selection_schema.go @@ -47,11 +47,10 @@ type localSelectionCustodyConflict struct { func (e *localSelectionCustodyConflict) Unwrap() error { return e.error } -// requireUnquarantinedSelectionLink only denies work. The custody row cannot -// replace active selection attribution or authorize a new provider action. -func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, project, operation string) error { - var proved, hasLive, hasLocalLive bool - err := q.QueryRowContext(ctx, `SELECT COALESCE(s.project_id=d.project_id AND s.state='held' AND +const selectionCustodyProofSQL = `COALESCE(s.project_id=d.project_id AND typeof(d.original_operation_id)='text' AND + length(CAST(d.original_operation_id AS BLOB)) BETWEEN 1 AND 128 AND + length(CAST(d.original_operation_id AS BLOB))=length(d.original_operation_id) AND + d.original_operation_id NOT GLOB '*[^A-Za-z0-9_-]*' AND s.state='held' AND s.reason='linked_selection_quarantined' AND s.operation_id IS NULL AND typeof(d.observed_revision)='integer' AND d.observed_revision>0 AND typeof(s.revision)='integer' AND s.revision=CASE WHEN d.observed_revision=9223372036854775807 @@ -64,11 +63,19 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro (a.project_id<>s.project_id OR a.actor_id<>s.actor_id OR a.worker_id<>s.worker_id OR typeof(a.pull_number)<>'integer' OR a.pull_number<0 OR a.pull_number>2147483647 OR (a.pull_number<>0 AND (o.id IS NULL OR o.pull_number<>a.pull_number)) OR - (a.pull_number=0 AND a.pull_basis_sha256<>''))), 0), + (a.pull_number=0 AND a.pull_basis_sha256<>''))), 0)` + +const selectionCustodyJoinSQL = `FROM review_selection_quarantine d LEFT JOIN review_selections s ON s.id=d.selection_id + LEFT JOIN review_operations o ON o.id=d.original_operation_id` + +// requireUnquarantinedSelectionLink only denies work. The custody row cannot +// replace active selection attribution or authorize a new provider action. +func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, project, operation string) error { + var proved, hasLive, hasLocalLive bool + err := q.QueryRowContext(ctx, `SELECT `+selectionCustodyProofSQL+`, EXISTS(SELECT 1 FROM review_selections live WHERE live.operation_id=d.original_operation_id), EXISTS(SELECT 1 FROM review_selections live WHERE live.operation_id=d.original_operation_id AND live.project_id=d.project_id) - FROM review_selection_quarantine d LEFT JOIN review_selections s ON s.id=d.selection_id - LEFT JOIN review_operations o ON o.id=d.original_operation_id + `+selectionCustodyJoinSQL+` WHERE d.project_id=? AND d.original_operation_id=?`, project, operation).Scan(&proved, &hasLive, &hasLocalLive) if errors.Is(err, sql.ErrNoRows) { // A detached marker without its diagnostic has lost the only @@ -76,16 +83,42 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro // child in that project from the absent link. var unproved bool if err := q.QueryRowContext(ctx, `SELECT EXISTS ( - SELECT 1 FROM review_selections s - WHERE s.project_id=? AND s.reason='linked_selection_quarantined' - AND NOT EXISTS (SELECT 1 FROM review_selection_quarantine d - WHERE d.project_id=s.project_id AND d.selection_id=s.id - AND typeof(d.original_operation_id)='text' - AND length(CAST(d.original_operation_id AS BLOB)) BETWEEN 1 AND 128 - AND length(CAST(d.original_operation_id AS BLOB))=length(d.original_operation_id) - AND d.original_operation_id NOT GLOB '*[^A-Za-z0-9_-]*'))`, project).Scan(&unproved); err != nil { + SELECT 1 FROM review_selections s0 + WHERE s0.project_id=? AND s0.reason='linked_selection_quarantined' + AND NOT EXISTS (SELECT 1 `+selectionCustodyJoinSQL+` + WHERE d.project_id=s0.project_id AND d.selection_id=s0.id AND `+selectionCustodyProofSQL+` + AND NOT EXISTS(SELECT 1 FROM review_selections live WHERE live.operation_id=d.original_operation_id)))`, project).Scan(&unproved); err != nil { return err } + if !unproved { + // A structurally attributable diagnostic still cannot prove a child + // when its receipt says the operation was accepted independently. + rows, err := q.QueryContext(ctx, `SELECT d.original_operation_id FROM review_selection_quarantine d + JOIN review_selections s ON s.id=d.selection_id AND s.project_id=d.project_id + JOIN review_operations o ON o.id=d.original_operation_id AND o.project_id=d.project_id + WHERE d.project_id=? AND s.reason='linked_selection_quarantined'`, project) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var link string + if err := rows.Scan(&link); err != nil { + return err + } + direct, err := directOperationConflictsWithSelectionCustody(ctx, q, project, link) + if err != nil { + return err + } + if direct { + unproved = true + break + } + } + if err := rows.Err(); err != nil { + return err + } + } if unproved { return automaticProjectStateFailure(linkedSelectionCustodyHeld, "A review operation is held for selection custody recovery in this project.", 403) } @@ -98,6 +131,14 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro // An unknown custody row cannot establish ordinary ineligibility. return runUnavailable() } + direct, err := directOperationConflictsWithSelectionCustody(ctx, q, project, operation) + if err != nil { + return err + } + if direct { + return runUnavailable() + } + if hasLive { if hasLocalLive { return &localSelectionCustodyConflict{error: runUnavailable(), project: project, operation: operation} diff --git a/internal/reviewexec/run_selection_snapshot.go b/internal/reviewexec/run_selection_snapshot.go index ae823eaa8..deca6660e 100644 --- a/internal/reviewexec/run_selection_snapshot.go +++ b/internal/reviewexec/run_selection_snapshot.go @@ -280,6 +280,14 @@ func validateSelectionQuarantine(ctx context.Context, q EvidenceQuery) error { state != "held" || reason != "linked_selection_quarantined" || currentLink != nil || project != reportedProject { return runUnavailable() } + direct, err := directOperationConflictsWithSelectionCustody(ctx, q, reportedProject, link) + if err != nil { + return err + } + if direct { + return runUnavailable() + } + } return rows.Err() } diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 5efa2d3e3..456db7f38 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -660,13 +660,17 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target // A rolled-back claim cannot retain a selected pointer or notification. selected, changed = nil, "" return e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if expected == 0 { + // An exhausted native revision cannot be advanced. Keep the + // exact row isolated rather than stopping both selection workers. + var err error + quarantined, err = quarantineNativeSelection(ctx, tx, project, id, "queued", expected) + return err + } r, err := readRun(ctx, tx, project, id) if err != nil { return err } - if r.State == "queued" && expected == 0 { - return runUnavailable() - } if r.State != "queued" || r.Revision != expected { return nil } @@ -821,7 +825,8 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } // An incomplete local front read never evaluated this // basis, even if grant identity matches. Do not mark it served. - settle := !zeroPrefixHold && state != "queued" && reason != "selection_changed" && reason != "local_read_unavailable" + settle := !zeroPrefixHold && state != "queued" && reason != "selection_changed" && reason != "local_read_unavailable" && + !(state == "held" && globalFrontHold(reason)) if settle && choice.automaticQueueLimit != nil && choice.automaticBasisRevision != 0 { var currentBasis int64 currentBasis, resultErr = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) @@ -923,6 +928,17 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return updateRun(ctx, tx, current, "held", "selection_changed", "") } boundPrefix = c.Queue[:limit] + if choice.state == "selected" && choice.automaticBasisRevision != 0 { + routeSequence, err := automaticRouteSequence(ctx, tx, r.ProjectID) + if err != nil { + return err + } + if routeSequence != choice.automaticRouteSequence { + // Do not commit a child whose freshly evaluated basis + // cannot be attributed after a concurrent route edit. + return updateRun(ctx, tx, current, "held", "selection_changed", "") + } + } if current.Channel == "hosted" && current.Revision >= 4 && choice.state == "selected" { initial, err := automaticSourceInitialRead(ctx, tx, current) if err != nil { diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index 7a7ab9222..1130629b9 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -128,7 +128,7 @@ func schedulingBasisRevisions(ctx context.Context, tx *sql.Tx, s schedulingRecor if s.Revision == 0 { return 0, 0, nil } - rows, err := tx.QueryContext(ctx, `SELECT actor_id,CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision=? LIMIT 2`, s.ProjectID, s.ProjectID, s.Revision) + rows, err := tx.QueryContext(ctx, `SELECT actor_id,typeof(event_type),CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND (event_type='review.scheduling_updated' OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.scheduling_updated')) AND resource_id=? AND revision=? LIMIT 2`, s.ProjectID, s.ProjectID, s.Revision) if err != nil { return 0, 0, err } @@ -137,13 +137,14 @@ func schedulingBasisRevisions(ctx context.Context, tx *sql.Tx, s schedulingRecor for rows.Next() { count++ var nativeActor any + var eventType string var payload sql.NullString - if err = rows.Scan(&nativeActor, &payload); err != nil { + if err = rows.Scan(&nativeActor, &eventType, &payload); err != nil { return 0, 0, err } event, eventHosted, eventCLI, valid := readSchedulingEventPayload(payload, s.Revision) actor, textActor := nativeActor.(string) - if count != 1 || !textActor || actor != s.actor || !valid || *event.Hosted != s.AutomaticHosted || event.CLI == nil && s.AutomaticCLI || event.CLI != nil && *event.CLI != s.AutomaticCLI { + if count != 1 || eventType != "text" || !textActor || actor != s.actor || !valid || *event.Hosted != s.AutomaticHosted || event.CLI == nil && s.AutomaticCLI || event.CLI != nil && *event.CLI != s.AutomaticCLI { return 0, 0, schedulingUnavailable() } hosted, cli = eventHosted, eventCLI diff --git a/internal/reviewexec/scheduling_authority.go b/internal/reviewexec/scheduling_authority.go index 0b6edb00c..9f95f2910 100644 --- a/internal/reviewexec/scheduling_authority.go +++ b/internal/reviewexec/scheduling_authority.go @@ -34,7 +34,7 @@ func schedulingAuthorityContinuity(ctx context.Context, tx *sql.Tx, project, act FROM events WHERE project_id=? AND resource_id=? AND (event_type='review.scheduling_updated' OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.scheduling_updated')) AND revision BETWEEN ? AND ? GROUP BY resource_id,revision ) - SELECT w.resource_id,w.actor_id,w.revision,w.sequence, + SELECT w.resource_id,w.actor_id,w.revision,w.sequence,u.sequence, CASE WHEN typeof(w.event_type)='text' AND typeof(w.payload_json)='text' AND length(CAST(w.payload_json AS BLOB))<=4096 THEN w.payload_json END, CASE WHEN u.copies=1 AND typeof(u.actor_id)='text' AND u.actor_id=w.actor_id AND u.sequence last-first || rev != first+seen { + settingsOrd, validSettingsSequence := settingsSequence.(int64) + if resource != project || owner != actor || !validRevision || !validSequence || !validSettingsSequence || settingsOrd <= previousSequence || settingsOrd >= ord || seen > last-first || rev != first+seen { return 0, nil } value, valid := decodeSchedulingAuthorityGeneration(witness, rev) diff --git a/internal/reviewexec/scheduling_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go index 96c1d55b7..eb08298e6 100644 --- a/internal/reviewexec/scheduling_authorization_continuity.go +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -42,7 +42,7 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision return false, err } } - rows, err := tx.QueryContext(ctx, `SELECT revision,actor_id,CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision BETWEEN ? AND ? ORDER BY revision,sequence LIMIT 10002`, r.ProjectID, r.ProjectID, revision, current.Revision) + rows, err := tx.QueryContext(ctx, `SELECT revision,actor_id,typeof(event_type),CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND (event_type='review.scheduling_updated' OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.scheduling_updated')) AND resource_id=? AND revision BETWEEN ? AND ? ORDER BY revision,sequence LIMIT 10002`, r.ProjectID, r.ProjectID, revision, current.Revision) if err != nil { return false, err } @@ -52,13 +52,14 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision for rows.Next() { var retainedRevision any var storedActor any + var eventType string var payload sql.NullString - if err = rows.Scan(&retainedRevision, &storedActor, &payload); err != nil { + if err = rows.Scan(&retainedRevision, &storedActor, &eventType, &payload); err != nil { return false, err } recorded, validRevision := retainedRevision.(int64) actor, nativeText := storedActor.(string) - if !validRevision || !nativeText || !identifier.MatchString(actor) || recorded != expected || + if eventType != "text" || !validRevision || !nativeText || !identifier.MatchString(actor) || recorded != expected || (!selectedChild || recorded == revision) && actor != originalActor || recorded == current.Revision && actor != current.actor { return false, nil diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index fbe075857..1a6a8cae9 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "errors" + "math" "strconv" "strings" @@ -96,7 +97,7 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { if err = scanSchedulingSnapshot(rows, &s.ProjectID, &s.PullNumber, &s.Revision, &s.Paused, &s.Reason, &s.ActorID, &s.UpdatedAt); err != nil { break } - if !identifier.MatchString(s.ProjectID) || s.PullNumber < 1 || s.PullNumber > 2147483647 || s.Revision < 1 || !identifier.MatchString(s.ActorID) || !roundTime(s.UpdatedAt) || !validSchedulingReason(s.Reason) || !s.Paused && s.Reason != "" { + if !identifier.MatchString(s.ProjectID) || s.PullNumber < 1 || s.PullNumber > 2147483647 || s.Revision < 1 || s.Paused && s.Revision == math.MaxInt64 || !identifier.MatchString(s.ActorID) || !roundTime(s.UpdatedAt) || !validSchedulingReason(s.Reason) || !s.Paused && s.Reason != "" { err = schedulingUnavailable() break } @@ -250,20 +251,23 @@ const orphanPullSchedulingSelectSQL = ` // Validate the entire orphan history before selecting its latest resume. // Materializing a control must not hide earlier unreadable event timestamps. -func validateOrphanPullSchedulingTimes(ctx context.Context, tx *sql.Tx, scopeClause string, args ...any) error { +func validateOrphanPullSchedulingHistory(ctx context.Context, tx *sql.Tx, scopeClause string, args ...any) error { rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+scopeClause+`) - SELECT CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END + SELECT o.resource_id,o.payload,CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END FROM orphan_history o JOIN events e ON e.sequence=o.sequence`, args...) if err != nil { return err } defer rows.Close() for rows.Next() { - var at sql.NullString - if err := rows.Scan(&at); err != nil { + var at, payload sql.NullString + var raw any + if err := rows.Scan(&raw, &payload, &at); err != nil { return err } - if !at.Valid || !roundTime(at.String) { + id, native := raw.(string) + pull, parseErr := strconv.ParseInt(id, 10, 32) + if !native || parseErr != nil || pull < 1 || strconv.FormatInt(pull, 10) != id || !at.Valid || !roundTime(at.String) || !pullSchedulingPayloadMatchesPull(payload, pull) { return schedulingUnavailable() } } @@ -274,7 +278,7 @@ func validateOrphanPullSchedulingTimes(ctx context.Context, tx *sql.Tx, scopeCla } func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { - if err := validateOrphanPullSchedulingTimes(ctx, tx, ""); err != nil { + if err := validateOrphanPullSchedulingHistory(ctx, tx, ""); err != nil { return err } rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+orphanPullSchedulingRankSQL+orphanPullSchedulingSelectSQL) @@ -329,20 +333,30 @@ func editablePullScheduling(ctx context.Context, tx *sql.Tx, project string, pul } const scopeClause = ` AND e.project_id=? AND (e.resource_id=? OR (typeof(e.resource_id)='blob' AND CAST(e.resource_id AS TEXT)=?))` pullID := strconv.FormatInt(pull, 10) - if err := validateOrphanPullSchedulingTimes(ctx, tx, scopeClause, project, pullID, pullID); err != nil { + if err := validateOrphanPullSchedulingHistory(ctx, tx, scopeClause, project, pullID, pullID); err != nil { return current, err } - orphan, err := scanOrphanPullResume(tx.QueryRowContext(ctx, orphanPullSchedulingSQL+scopeClause+ - orphanPullSchedulingRankSQL+orphanPullSchedulingSelectSQL, project, pullID, pullID)) - if errors.Is(err, sql.ErrNoRows) { - return current, nil + rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+scopeClause+orphanPullSchedulingRankSQL+orphanPullSchedulingSelectSQL, project, pullID, pullID) + if err != nil { + return current, err + } + defer rows.Close() + if !rows.Next() { + return current, rows.Err() } + orphan, err := scanOrphanPullResume(rows) if err != nil { return current, err } - if orphan.ProjectID != project || orphan.PullNumber != pull { + if orphan.ProjectID != project || orphan.PullNumber != pull || rows.Next() { return current, schedulingUnavailable() } + if err := rows.Err(); err != nil { + return current, err + } + if err := rows.Close(); err != nil { + return current, err + } return orphan, nil } @@ -380,6 +394,13 @@ func RestoreHistoricalPullResumes(ctx context.Context, tx *sql.Tx) error { return err } +func pullSchedulingPayloadMatchesPull(payload sql.NullString, pull int64) bool { + var event struct { + PullNumber int64 `json:"pull_number"` + Paused *bool `json:"paused"` + } + return payload.Valid && strictjson.Decode([]byte(payload.String), &event) == nil && event.PullNumber == pull && event.Paused != nil +} func validPullSchedulingPayload(payload sql.NullString, pull int64, paused bool) bool { var event struct { PullNumber int64 `json:"pull_number"` @@ -434,7 +455,7 @@ func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) return err } revision, integer := nativeRevision.(int64) - if !integer || !createdAt.Valid || !roundTime(createdAt.String) { + if !integer || !createdAt.Valid || !roundTime(createdAt.String) || !pullSchedulingPayloadMatchesPull(payload, pull) { return schedulingUnavailable() } if revision < controlRevision { diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index f92b4456c..15e69a768 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -799,7 +799,7 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return nil } - if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + if automaticProjectRefused(err) || isLinkedSelectionCustodyHeld(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { continue } var refusal *core.Error From 7e0b4056a070e685d6494966c539d389d1d628b3 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 00:34:24 +1300 Subject: [PATCH 29/34] Complete retained CLI settlement and index resource lookups --- internal/backup/inventory.go | 25 +++++++++- internal/backup/operation_list_index_test.go | 50 +++++++++++++++++++ .../reviewexec/cli_prepared_settlement.go | 34 ++++++++++--- .../cli_recorded_publish_settlement_test.go | 50 +++++++++++++++++++ internal/reviewexec/run_selection_origin.go | 2 +- internal/reviewexec/scheduling_snapshot.go | 5 +- internal/reviewexec/schema.go | 9 +++- internal/reviewexec/supervisor.go | 31 ++++++++++++ internal/reviewruntime/cli_driver.go | 7 ++- 9 files changed, 199 insertions(+), 14 deletions(-) create mode 100644 internal/reviewexec/cli_recorded_publish_settlement_test.go diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index 62c6c8d78..9ad91d477 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -233,7 +233,7 @@ type tableVersion struct { // Fixed application schema bounds are intentionally independent of migration // execution. Inspection never opens a Store or installs/rewrites a schema. -var supportedDomains = map[string]int{"review_scheduling": 2, "review_fronts": 1, "project_management": 1, "worker_retirements": 1, "review_selection": 2, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 4, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} +var supportedDomains = map[string]int{"review_event_indexes": 1, "review_scheduling": 2, "review_fronts": 1, "project_management": 1, "worker_retirements": 1, "review_selection": 2, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 4, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} var tables = map[string]tableVersion{ "review_scheduling": {"review_scheduling", 1, "project_id revision automatic_hosted actor_id worker_id credential_id updated_at"}, "review_pull_scheduling": {"review_scheduling", 1, "project_id pull_number revision paused reason actor_id updated_at"}, @@ -647,6 +647,12 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ return nil, err } } + if err = validateReviewEventResourceIndex(ctx, db, versions["review_event_indexes"]); err != nil { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, err + } if versions["review_execution_indexes"] < 4 { var count int if err := db.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_schema WHERE name='review_operations_draft_probe'`).Scan(&count); err != nil || count != 0 { @@ -1726,6 +1732,23 @@ func validateAbsentSchedulingSchema(ctx context.Context, db sqlReader) error { return nil } +func validateReviewEventResourceIndex(ctx context.Context, db sqlReader, version int) error { + if version == 0 { + var exists bool + if err := db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name='review_event_resource' COLLATE NOCASE)`).Scan(&exists); err != nil || exists { + return invalid() + } + return nil + } + var definition string + if err := db.QueryRowContext(ctx, `SELECT CASE WHEN length(CAST(sql AS BLOB))<=16384 THEN sql END FROM sqlite_schema + WHERE type='index' AND name='review_event_resource' AND tbl_name='events'`).Scan(&definition); err != nil || + historyDefinitionSQL(definition) != historyDefinitionSQL(reviewexec.ReviewEventResourceIndexSQL) { + return invalid() + } + return nil +} + func validateSchedulingPhysicalSchema(ctx context.Context, db sqlReader, version int) error { expected := map[string]physicalSchemaObject{} statements := reviewexec.SchedulingSchemaSQL() 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/reviewexec/cli_prepared_settlement.go b/internal/reviewexec/cli_prepared_settlement.go index 30157e37c..f4e2e145d 100644 --- a/internal/reviewexec/cli_prepared_settlement.go +++ b/internal/reviewexec/cli_prepared_settlement.go @@ -10,9 +10,11 @@ import ( ) const ( - preparedCLISettlementEvent = "review.cli_prepared_admission_settlement" - preparedCLIRefusalScheduling = "scheduling" - preparedCLIRefusalPolicy = "policy" + preparedCLISettlementEvent = "review.cli_prepared_admission_settlement" + preparedCLIRefusalScheduling = "scheduling" + preparedCLIRefusalPolicy = "policy" + preparedCLIRefusalPublish = "publish" + recordedCLIPublishSettlementEvent = "review.cli_recorded_publish_settlement" ) // Kept only by the live caller that observed the exact prepared refusal. @@ -20,6 +22,7 @@ type preparedCLISettlement struct { operation Operation attempt Attempt anchor Anchor + positive *CLIAllowanceObservation refusal error kind string result Attempt @@ -31,6 +34,13 @@ func transientPreparedCLISettlement(err error) bool { return errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &failure) && failure.Code == "overloaded") } +func (p *preparedCLISettlement) eventType() string { + if p.kind == preparedCLIRefusalPublish { + return recordedCLIPublishSettlementEvent + } + return preparedCLISettlementEvent +} + func (e *Engine) recordPreparedCLISettlement(ctx context.Context, tx *sql.Tx, p *preparedCLISettlement) (Attempt, error) { result, err := e.settleCLIAdmissionRefusal(ctx, tx, p.operation, p.attempt, p.anchor, p.refusal) if err != nil { @@ -39,7 +49,7 @@ func (e *Engine) recordPreparedCLISettlement(ctx context.Context, tx *sql.Tx, p o := p.operation scope := core.Scope{ProjectID: o.ProjectID, PrincipalID: o.ActorID, WorkerID: o.WorkerID} claim := unusedCLISettlementRecord{OperationID: o.ID, ClaimRevision: o.Revision} - if err := core.AppendEvent(ctx, tx, scope, preparedCLISettlementEvent, p.attempt.ID, result.Revision, claim); err != nil { + if err := core.AppendEvent(ctx, tx, scope, p.eventType(), p.attempt.ID, result.Revision, claim); err != nil { return Attempt{}, err } var sequence int64 @@ -98,6 +108,17 @@ func (e *Engine) retryPreparedCLISettlement(ctx context.Context, p *preparedCLIS if err != nil && !isStoredUnavailable(err, storedPolicyHistory) { return err } + case preparedCLIRefusalPublish: + if p.positive == nil || p.positive.Remaining <= 0 || p.positive.Anchor != p.anchor { + return conflict() + } + record, err := readCLIAllowanceRecord(ctx, tx, o, a) + if err != nil { + return err + } + if record.Observation != *p.positive { + return conflict() + } default: return conflict() } @@ -127,7 +148,7 @@ func (e *Engine) readPreparedCLISettlement(ctx context.Context, p *preparedCLISe defer tx.Rollback() o, a := p.operation, p.attempt record := unusedCLISettlementRecord{OperationID: o.ID, ClaimRevision: o.Revision} - committed, err := scanCLISettlementEvent(ctx, tx, o.ProjectID, a.ID, preparedCLISettlementEvent, o.ActorID, p.result.Revision, record, 0) + committed, err := scanCLISettlementEvent(ctx, tx, o.ProjectID, a.ID, p.eventType(), o.ActorID, p.result.Revision, record, 0) if err != nil || !committed { return false, err } @@ -143,7 +164,8 @@ func (e *Engine) readPreparedCLISettlement(ctx context.Context, p *preparedCLISe if err != nil { return false, err } - if preflight.Observation.Remaining <= 0 || preflight.Observation.Anchor != p.anchor { + if preflight.Observation.Remaining <= 0 || preflight.Observation.Anchor != p.anchor || + p.kind == preparedCLIRefusalPublish && (p.positive == nil || preflight.Observation != *p.positive) { return false, conflict() } err = tx.QueryRowContext(ctx, `SELECT 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/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index 22a7ef5b4..d214ab565 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -24,7 +24,7 @@ type selectionRequestedEvent struct { func readSelectionRequestedEvent(ctx context.Context, q EvidenceQuery, r Run) (selectionRequestedEvent, error) { rows, err := q.QueryContext(ctx, `SELECT sequence,actor_id,typeof(event_type), CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END - FROM events WHERE project_id=? AND (event_type='review.selection_requested' OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.selection_requested')) AND resource_id=? AND revision=1 LIMIT 2`, r.ProjectID, r.ID) + FROM events WHERE project_id=? AND event_type IN ('review.selection_requested',CAST('review.selection_requested' AS BLOB)) AND resource_id=? AND revision=1 LIMIT 2`, r.ProjectID, r.ID) if err != nil { return selectionRequestedEvent{}, err } diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 1a6a8cae9..99a4f81b4 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -224,8 +224,7 @@ const orphanPullSchedulingSQL = `WITH orphan_history AS ( FROM events e LEFT JOIN review_pull_scheduling s ON s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id - WHERE (e.event_type='review.pull_scheduling_updated' - OR (typeof(e.event_type)='blob' AND CAST(e.event_type AS TEXT)='review.pull_scheduling_updated')) + WHERE e.event_type IN ('review.pull_scheduling_updated',CAST('review.pull_scheduling_updated' AS BLOB)) AND s.pull_number IS NULL` const orphanPullSchedulingRankSQL = ` @@ -331,7 +330,7 @@ func editablePullScheduling(ctx context.Context, tx *sql.Tx, project string, pul if err != nil || current.Revision != 0 { return current, err } - const scopeClause = ` AND e.project_id=? AND (e.resource_id=? OR (typeof(e.resource_id)='blob' AND CAST(e.resource_id AS TEXT)=?))` + const scopeClause = ` AND e.project_id=? AND e.resource_id IN (?,CAST(? AS BLOB))` pullID := strconv.FormatInt(pull, 10) if err := validateOrphanPullSchedulingHistory(ctx, tx, scopeClause, project, pullID, pullID); err != nil { return current, err diff --git a/internal/reviewexec/schema.go b/internal/reviewexec/schema.go index 470e546c7..1df046fb0 100644 --- a/internal/reviewexec/schema.go +++ b/internal/reviewexec/schema.go @@ -7,6 +7,10 @@ import ( "github.com/benhook1013/FireController/internal/core" ) +// ReviewEventResourceIndexSQL is the append-only event lookup index owned by +// the review_event_indexes domain. Backup inspection checks its exact shape. +const ReviewEventResourceIndexSQL = `CREATE INDEX review_event_resource ON events(project_id,resource_id,event_type,revision)` + func EnsureSchema(ctx context.Context, store *core.Store) error { if _, err := retainedComparisonSchema(ctx, store.DB()); err != nil { return err @@ -97,7 +101,10 @@ func EnsureSchema(ctx context.Context, store *core.Store) error { if err := EnsureFrontSchema(ctx, store); err != nil { return err } - return EnsureSchedulingSchema(ctx, store) + if err := EnsureSchedulingSchema(ctx, store); err != nil { + return err + } + return store.EnsureSchema(ctx, "review_event_indexes", []string{ReviewEventResourceIndexSQL}) } // Execution migration nine rebuilds attempts independently of the comparison diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 15e69a768..06c129cce 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "log/slog" + "math" "reflect" "strings" "sync" @@ -28,6 +29,7 @@ type Preparation struct { type CLIPreparationHandoff struct { recovery *PreparationRecoveryError source CLIExhaustionRecoverySource + positive *CLIAllowanceObservation release func() } @@ -68,7 +70,36 @@ func RetainedCLIExhaustionHandoff(err error, source CLIExhaustionRecoverySource, return &CLIPreparationHandoff{recovery: &PreparationRecoveryError{Err: err}, source: source, release: release} } +// CLIRecordedPreflightHandoff retires the exact permit of a completed +// preparation that has recorded positive allowance but cannot publish locally. +// A positive allowance is never evidence that a review was started or admitted. +func CLIRecordedPreflightHandoff(err error, observation CLIAllowanceObservation, retire func() bool, release func()) error { + var binding *operationSelectionBindingStateError + if !CLIProjectHistoryRefused(err) || isLinkedSelectionCustodyHeld(err) || errors.As(err, &binding) || + observation.Remaining <= 0 || !validCLIAllowanceObservation(observation) || retire == nil || !retire() { + return &PreparationRecoveryError{Err: err} + } + return &CLIPreparationHandoff{recovery: &PreparationRecoveryError{Err: err}, positive: &observation, release: release} +} + func (e *Engine) settleCLIPreparationHandoff(ctx context.Context, original Operation, a Attempt, h *CLIPreparationHandoff) error { + if h.positive != nil { + if h.source != nil || original.Revision == math.MaxInt64 { + return conflict() + } + claim := original + claim.AttemptID, claim.State, claim.Revision = a.ID, "preparing", original.Revision+1 + pending := &preparedCLISettlement{operation: claim, attempt: a, anchor: h.positive.Anchor, refusal: h.recovery.Err, + kind: preparedCLIRefusalPublish, positive: h.positive} + err := settleOwnedCLIWithinWindows(ctx, func(local context.Context) error { + _, err := e.retryPreparedCLISettlement(local, pending) + return err + }) + if err == nil { + e.notifyOperation(a.OperationID) + } + return err + } if h.source == nil { ack := &unusedCLISettlementAck{} return settleOwnedCLIWithinWindows(ctx, func(local context.Context) error { diff --git a/internal/reviewruntime/cli_driver.go b/internal/reviewruntime/cli_driver.go index 1b945ab90..3f2489053 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -200,14 +200,17 @@ func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, } return preparation, reviewHold("allowance_unavailable") } - if err := d.engine.RecordCLIAllowance(ctx, operation.ProjectID, attempt.ID, attempt.Revision, reviewexec.CLIAllowanceObservation{Anchor: anchor, ObservedAt: time.Now().UTC().Format(time.RFC3339Nano), Remaining: usage.Remaining, Limit: usage.Limit, FullCapacityInMS: usage.FullCapacityInMS, RollingWindowMS: usage.RollingWindowMS, ChangedFiles: changedFiles}); err != nil { + observation := reviewexec.CLIAllowanceObservation{Anchor: anchor, ObservedAt: time.Now().UTC().Format(time.RFC3339Nano), Remaining: usage.Remaining, Limit: usage.Limit, FullCapacityInMS: usage.FullCapacityInMS, RollingWindowMS: usage.RollingWindowMS, ChangedFiles: changedFiles} + if err := d.engine.RecordCLIAllowance(ctx, operation.ProjectID, attempt.ID, attempt.Revision, observation); err != nil { return preparation, reviewexec.CLIPreflightUnusedHandoff(err, func() bool { return d.retireUsage != nil && d.retireUsage(workspace, usage) }, releaseSettlement) } if err := publishPreparedAttempt(ctx, d.engine, operation.ProjectID, attempt.ID, plan); err != nil { if reviewexec.CLIProjectHistoryRefused(err) { - return preparation, &reviewexec.PreparationRecoveryError{Err: err} + return preparation, reviewexec.CLIRecordedPreflightHandoff(err, observation, func() bool { + return d.retireUsage != nil && d.retireUsage(workspace, usage) + }, releaseSettlement) } return preparation, err } From 8e9732fd5b2485ca29a92f6ae8f31e67e17fc40c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 01:11:36 +1300 Subject: [PATCH 30/34] Address current combined Hosted and CLI review findings --- docs/review-execution.md | 2 +- internal/backup/scheduling_test.go | 19 ++++++ internal/reviewexec/cli_pause_no_start.go | 10 ++- .../reviewexec/cli_policy_settlement_test.go | 21 ++++-- .../reviewexec/cli_prepared_settlement.go | 3 + internal/reviewexec/front_evaluator.go | 6 ++ .../hosted_paused_retained_allowance_test.go | 28 ++++++++ internal/reviewexec/hosted_preflight.go | 24 +++++-- internal/reviewexec/hosted_wait_validation.go | 11 ++++ internal/reviewexec/run_selection.go | 54 +++++++++++++++ internal/reviewexec/run_selection_schema.go | 7 ++ internal/reviewexec/run_selection_worker.go | 27 ++++++-- internal/reviewexec/scheduling.go | 15 ++++- internal/reviewexec/scheduling_automatic.go | 16 ++++- .../scheduling_selected_basis_guard_test.go | 6 ++ internal/reviewexec/scheduling_snapshot.go | 66 +++++++++++++++---- .../reviewexec/scheduling_source_retry.go | 20 ++++-- internal/reviewexec/supervisor.go | 13 +++- 18 files changed, 306 insertions(+), 42 deletions(-) create mode 100644 internal/reviewexec/hosted_paused_retained_allowance_test.go diff --git a/docs/review-execution.md b/docs/review-execution.md index 34f17b2b8..1ad54c1b1 100644 --- a/docs/review-execution.md +++ b/docs/review-execution.md @@ -96,7 +96,7 @@ Hosted allowance attribution uses the same [current-source actor policy](provide When native projection is enabled, each journal transition updates its browser attempt in the same transaction. Preparing and held are distinct states; held attempts retain their actual stop time. Interrupted active or posting work becomes uncertain without an invented finish time. A missing current PR observation leaves the transition ledger-only; a trusted fresh observation can establish that first row. Publication preserves current PR facts and imported history, and exact replay creates no new snapshot. Initial metadata is a fallback inside the publication transaction: if another observation creates current PR facts after a missing-row read, those current facts take precedence over the prepared fallback. If retained attempt capacity is already full, the request is durably held before creating an attempt or reservation. If a later administrator observation replaces the snapshot, omits the live native attempt and fills its capacity, automatic transitions remain ledger-only; they neither copy snapshot rows nor block execution or restart recovery. Existing native rows still update at capacity. Explicit publication retains its atomic capacity refusal. Other projection failures roll back the journal transition as well. -Attempt settlement retries only the same guarded local journal transition within a finite budget. It reconciles an already committed transition before retrying and never repeats provider dispatch. For a source-less CLI refusal that the original driver certified before usage, a live supervisor may give the same guarded settlement one additional bounded window after a local timeout or overload. The original ownership marker remains in place, and neither preparation nor dispatch runs again. A completed positive allowance query can use the same guarded settlement only when the allowance writer explicitly refused before its first write and the native driver retires the exact unconsumed review permit. Unknown outcomes are not proof of non-use. If the outcome cannot be recorded, the supervisor reports a failure, cancels its other work and retains reservations for inspection and recovery. +Attempt settlement retries only the same guarded local journal transition within a finite budget. It reconciles an already committed transition before retrying and never repeats provider dispatch. For a source-less CLI refusal that the original driver certified before usage, a live supervisor may give the same guarded settlement one additional bounded window after a local timeout or overload. The original ownership marker remains in place, and neither preparation nor dispatch runs again. After a positive allowance query, the native driver must retire the exact unconsumed review permit before handing off settlement. A qualifying pre-write refusal requires proof that no allowance was retained. A qualifying local publication refusal after a successful positive allowance write instead carries the exact retained observation and verifies it again in the guarded settlement. Both paths preserve the original request and never authorize a review. Unknown outcomes are not proof of non-use. If the outcome cannot be recorded, the supervisor reports a failure, cancels its other work and retains reservations for inspection and recovery. ## Hosted adapter diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index 33e7b9492..08edfd6aa 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -127,6 +127,25 @@ func TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { if !reflect.DeepEqual(sourceControls, restoreRows(t, f.store.DB(), controls)) || !reflect.DeepEqual(immutable, restoreTree(t, bundle.Path)) { t.Fatal("restore mutated source controls or validated bundle") } + // The same valid retained resume supplies the live CAS basis before + // an offline restore materializes its projection. + recovered, err := e.ReadPullScheduling(t.Context(), scope, 4) + if err != nil || recovered.Revision != 2 || recovered.Paused { + t.Fatal("legacy resume did not provide its live CAS revision", recovered, err) + } + if _, err := e.ConfigurePullScheduling(t.Context(), scope, "stale-legacy-pause", 4, + reviewexec.PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused, Reason: "Fixture pause"}); err == nil { + t.Fatal("legacy resume incorrectly allowed a revision-zero overwrite") + } + two := int64(2) + if _, err := e.ConfigurePullScheduling(t.Context(), scope, "next-legacy-pause", 4, + reviewexec.PullSchedulingRequest{ExpectedRevision: &two, Paused: &paused, Reason: "Fixture pause"}); err != nil { + t.Fatal("legacy CAS could not materialize a legitimate pause", err) + } + control, err := e.ReadPullScheduling(t.Context(), scope, 4) + if err != nil || control.Revision != 3 || !control.Paused { + t.Fatal("legacy CAS did not create its next pause", control, err) + } } func TestSchedulingInventoryAcceptsLegacyHostedAndItsActualMigration(t *testing.T) { diff --git a/internal/reviewexec/cli_pause_no_start.go b/internal/reviewexec/cli_pause_no_start.go index afb0bf2c3..5517a82f2 100644 --- a/internal/reviewexec/cli_pause_no_start.go +++ b/internal/reviewexec/cli_pause_no_start.go @@ -114,7 +114,7 @@ func (e *Engine) settleCLIPauseNoStart(ctx context.Context, original Operation, var receipt int64 err := settleOwnedCLIWithinWindows(ctx, func(local context.Context) error { if receipt != 0 { - committed, err := e.readCLIPauseSettlement(local, w, receipt) + committed, err := e.probeCLIPauseSettlement(local, w, 0) if err != nil || committed { return err } @@ -168,6 +168,12 @@ func (e *Engine) readCLIPauseSettlement(ctx context.Context, w *cliPauseNoStart, if sequence <= 0 { return false, conflict() } + return e.probeCLIPauseSettlement(ctx, w, sequence) +} + +// A retry discovers the exact attempt-local event, because an uncommitted +// sequence can be reused. A supplied receipt is verified by its own sequence. +func (e *Engine) probeCLIPauseSettlement(ctx context.Context, w *cliPauseNoStart, sequence int64) (bool, error) { tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) if err != nil { return false, err @@ -175,7 +181,7 @@ func (e *Engine) readCLIPauseSettlement(ctx context.Context, w *cliPauseNoStart, defer tx.Rollback() o := w.operation record := cliPauseNoStartRecord{OperationID: o.ID, PauseRevision: w.pauseRevision} - committed, err := scanCLISettlementEvent(ctx, tx, o.ProjectID, w.attempt.ID, cliPauseNoStartEvent, o.ActorID, w.attempt.Revision+1, record, 0) + committed, err := scanCLISettlementEvent(ctx, tx, o.ProjectID, w.attempt.ID, cliPauseNoStartEvent, o.ActorID, w.attempt.Revision+1, record, sequence) if err != nil || !committed { return false, err } diff --git a/internal/reviewexec/cli_policy_settlement_test.go b/internal/reviewexec/cli_policy_settlement_test.go index 7c361ea98..d89277b70 100644 --- a/internal/reviewexec/cli_policy_settlement_test.go +++ b/internal/reviewexec/cli_policy_settlement_test.go @@ -94,15 +94,23 @@ func TestPreparedCLISettlementDoesNotAdmitAfterPolicyRecovers(t *testing.T) { t.Fatal(err) } o := roundOperation(t, f, a.OperationID) - before := cliAllowanceState(t, f, a) refused := newStoredUnavailable(storedPolicyHistory, "Policy history was not available before retry.") pending := &preparedCLISettlement{operation: o, attempt: a, anchor: input.Anchor, refusal: refused, kind: preparedCLIRefusalPolicy} - if _, err := f.e.retryPreparedCLISettlement(t.Context(), pending); !errors.Is(err, refused) { - t.Fatalf("healthy policy was not left to a fresh admission: %v", err) + held, err := f.e.retryPreparedCLISettlement(t.Context(), pending) + if err != nil || held.ID != a.ID || held.State != "held" || held.Revision != a.Revision+1 { + t.Fatalf("repaired policy did not retire the exact unused preparation: %+v %v", held, err) } - if after := cliAllowanceState(t, f, a); after != before { - t.Fatal("resolving the original refusal changed the retained preparation") + queued := roundOperation(t, f, a.OperationID) + if queued.ID != o.ID || queued.State != "queued" || queued.AttemptID != "" || queued.Revision != o.Revision+1 { + t.Fatal("retry re-admitted or replaced the original request", queued) } + if attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != 0 { + t.Fatal("repaired policy left the unused preparation reserved") + } + if committed, err := f.e.readPreparedCLISettlement(t.Context(), pending); err != nil || !committed { + t.Fatal("the repaired-policy settlement has no exact acknowledgement", err) + } + assertCLIWaitSnapshot(t, f) } func TestCLIPauseSettlementReadsOnlyOriginalReceipt(t *testing.T) { @@ -144,6 +152,9 @@ func TestCLIPauseSettlementReadsOnlyOriginalReceipt(t *testing.T) { if committed, err := f.e.readCLIPauseSettlement(t.Context(), refusal.cliPause, sequence); err != nil || !committed { t.Fatalf("original acknowledgement not confirmed: %v", err) } + if committed, err := f.e.readCLIPauseSettlement(t.Context(), refusal.cliPause, sequence+1); err != nil || committed { + t.Fatalf("a different sequence acknowledged the original settlement: %v", err) + } if err = f.e.settleCLIPauseNoStart(t.Context(), original, admitted, refusal.cliPause); err == nil { t.Fatal("separate invocation reused consumed witness") } diff --git a/internal/reviewexec/cli_prepared_settlement.go b/internal/reviewexec/cli_prepared_settlement.go index f4e2e145d..1108d280f 100644 --- a/internal/reviewexec/cli_prepared_settlement.go +++ b/internal/reviewexec/cli_prepared_settlement.go @@ -89,6 +89,9 @@ func (e *Engine) retryPreparedCLISettlement(ctx context.Context, p *preparedCLIS if a != p.attempt || !sameCLIClaim(p.operation, o, a, p.operation.Revision) || !sameCLIWait(p.operation.Wait, o.Wait) { return conflict() } + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + return err + } switch p.kind { case preparedCLIRefusalScheduling: var history *schedulingHistoryUnavailable diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go index 85fb35efa..8154d73fa 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -90,6 +90,12 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i } suppressed, err := e.automaticPullSuppressed(ctx, q, r, plan.Pull.Number) if err != nil { + var local *automaticPullAdjudicationUnavailable + if errors.As(err, &local) { + // The basis query is scoped to this pull. Keep dependent work + // held but do not deny independently proved candidates. + return evaluatedFront{state: "held", reason: "automatic_scheduling_unavailable", plan: plan, localRefusal: err}, nil + } return evaluatedFront{}, err } if suppressed { diff --git a/internal/reviewexec/hosted_paused_retained_allowance_test.go b/internal/reviewexec/hosted_paused_retained_allowance_test.go new file mode 100644 index 000000000..9e5d7c3aa --- /dev/null +++ b/internal/reviewexec/hosted_paused_retained_allowance_test.go @@ -0,0 +1,28 @@ +package reviewexec + +import "testing" + +func TestHostedPositiveAllowanceReadsAndReplaysAfterPauseDetachesAttempt(t *testing.T) { + f, a, _, input := hostedAllowanceFixture(t) + if err := f.e.RecordHostedAllowance(t.Context(), a.ProjectID, a.ID, a.Revision, input); err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(t.Context(), a.ProjectID, a.ID, a.Revision, "held", "pull_scheduling_paused", ""); err != nil { + t.Fatal(err) + } + before := hostedAllowanceState(t, f, a) + got, err := f.e.ReadHostedAllowance(t.Context(), a.ProjectID, a.ID) + if err != nil || got != input { + t.Fatal("retained positive allowance was not read exactly", got, err) + } + if err := f.e.RecordHostedAllowance(t.Context(), a.ProjectID, a.ID, a.Revision, input); err != nil { + t.Fatal("exact retained allowance was not acknowledged", err) + } + if after := hostedAllowanceState(t, f, a); after != before { + t.Fatal("read or exact replay changed detached preparation") + } + assertCLIWaitSnapshot(t, f) + if err := ValidateAllowanceSnapshot(t.Context(), f.store.DB(), 10); err != nil { + t.Fatal("valid detached Hosted preflight did not survive snapshot validation", err) + } +} diff --git a/internal/reviewexec/hosted_preflight.go b/internal/reviewexec/hosted_preflight.go index 3c35fe890..ad899d9d0 100644 --- a/internal/reviewexec/hosted_preflight.go +++ b/internal/reviewexec/hosted_preflight.go @@ -132,7 +132,7 @@ func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID s if err != nil { return err } - operation, err = historicalCooldownOperation(ctx, tx, operation, attempt) + operation, err = historicalHostedAllowanceOperation(ctx, tx, operation, attempt, retained.Input.Observation.State == "available_observed") if err != nil { return err } @@ -212,7 +212,21 @@ func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID s }) } -func readHostedAllowance(ctx context.Context, tx *sql.Tx, project, attemptID string) (hostedAllowanceRecord, Attempt, Operation, error) { +// Historical positive allowance is an exact read or replay, never live authority. +func historicalHostedAllowanceOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt, positive bool) (Operation, error) { + if positive && o.Channel == "hosted" && o.AttemptID != a.ID { + historical, unused, err := historicalUnusedPreparationOperation(ctx, q, o, a, true) + if err != nil { + return Operation{}, err + } + if unused && historical.Reason == "pull_scheduling_paused" { + return historical, nil + } + } + return historicalCooldownOperation(ctx, q, o, a) +} + +func readHostedAllowance(ctx context.Context, tx *sql.Tx, project, attemptID string, retainedRead bool) (hostedAllowanceRecord, Attempt, Operation, error) { var body string err := tx.QueryRowContext(ctx, `SELECT body_json FROM review_hosted_preflight WHERE project_id=? AND attempt_id=?`, project, attemptID).Scan(&body) if errors.Is(err, sql.ErrNoRows) { @@ -233,7 +247,7 @@ func readHostedAllowance(ctx context.Context, tx *sql.Tx, project, attemptID str if err != nil { return record, attempt, operation, err } - operation, err = historicalCooldownOperation(ctx, tx, operation, attempt) + operation, err = historicalHostedAllowanceOperation(ctx, tx, operation, attempt, retainedRead && record.Input.Observation.State == "available_observed") if err != nil { return record, attempt, operation, err } @@ -255,7 +269,7 @@ func (e *Engine) ReadHostedAllowance(ctx context.Context, project, attemptID str } var input HostedAllowanceInput err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { - record, _, _, err := readHostedAllowance(ctx, tx, project, attemptID) + record, _, _, err := readHostedAllowance(ctx, tx, project, attemptID, true) input = record.Input if err == nil && !validHostedAllowanceInput(input) { return conflict() @@ -280,7 +294,7 @@ func (e *Engine) VerifyHostedAction(ctx context.Context, project, attemptID stri if err := e.verifyAction(ctx, tx, project, attemptID, expectedRevision, predecessors); err != nil { return err } - record, attempt, operation, err := readHostedAllowance(ctx, tx, project, attemptID) + record, attempt, operation, err := readHostedAllowance(ctx, tx, project, attemptID, false) if err != nil { return err } diff --git a/internal/reviewexec/hosted_wait_validation.go b/internal/reviewexec/hosted_wait_validation.go index ec9cb5434..daea27e6a 100644 --- a/internal/reviewexec/hosted_wait_validation.go +++ b/internal/reviewexec/hosted_wait_validation.go @@ -118,6 +118,17 @@ func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) return err } if unused { + if o.Channel == "cli" && a.Revision == 2 && historicalUnused.Reason != cliDraftWait { + // A zero observation proves exhaustion, not an ordinary + // unused scheduling hold. An absent preflight is valid. + record, err := readCLIAllowanceRecord(ctx, tx, historicalUnused, a) + if err != nil && !errors.Is(err, errAllowanceObservationAbsent) { + return waitDependencyError(err) + } + if err == nil && record.Observation.Remaining == 0 { + return waitUnavailable() + } + } foundDetached = true foundDraft = foundDraft || historicalUnused.Reason == cliDraftWait continue diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index e17183367..11d5353a2 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -266,6 +266,12 @@ func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configurati if err != nil { return c, 0, "", err } + if busy && !unproved { + busy, err = e.explicitHostedLaneBusy(ctx, tx, r.ProjectID) + if err != nil { + return c, 0, "", err + } + } busy = busy || unproved } if busy { @@ -516,6 +522,54 @@ func AbandonReviewRuns(ctx context.Context, tx *sql.Tx, at time.Time) (int64, er return int64(len(selected)), nil } +// A definitively unauthorized automatic intent has not acquired this lane +// while it remains queued with no retained attempts. Its own immutable child +// still exists for same-pull duplicate suppression; this only releases the +// unrelated explicit Hosted lane fence. +func (e *Engine) explicitHostedLaneBusy(ctx context.Context, tx *sql.Tx, project string) (bool, error) { + rows, err := tx.QueryContext(ctx, `SELECT o.id,o.state,EXISTS(SELECT 1 FROM review_execution_attempts a WHERE a.operation_id=o.id), + EXISTS(SELECT 1 FROM review_selections s WHERE s.operation_id=o.id AND s.project_id=o.project_id) + FROM review_operations o WHERE o.project_id=? AND o.channel='hosted' AND o.state IN ('queued','preparing','posting','active','uncertain') + AND NOT (o.state='queued' AND EXISTS(SELECT 1 FROM review_pull_scheduling p + WHERE p.project_id=o.project_id AND p.pull_number=o.pull_number AND typeof(p.paused)='integer' AND p.paused=1)) + ORDER BY o.id LIMIT 101`, project) + if err != nil { + return false, err + } + defer rows.Close() + var intents []string + for rows.Next() { + var id, state string + var attempted, linked bool + if err := rows.Scan(&id, &state, &attempted, &linked); err != nil { + return false, err + } + if state != "queued" || attempted || !linked || len(intents) == 100 { + return true, nil + } + intents = append(intents, id) + } + if err := rows.Err(); err != nil { + return false, err + } + if err := rows.Close(); err != nil { + return false, err + } + for _, id := range intents { + o, err := readOperationIdentity(ctx, tx, project, id) + if err != nil { + return false, err + } + err = e.requireAutomaticOperation(ctx, tx, o) + var refusal *core.Error + if errors.As(err, &refusal) && refusal.Code == "automation_authorization_changed" { + continue + } + return err == nil, err + } + return false, nil +} + func unprovedQueuedHostedPause(ctx context.Context, tx *sql.Tx, project string) (bool, error) { rows, err := tx.QueryContext(ctx, `SELECT DISTINCT pull_number FROM review_operations WHERE project_id=? AND channel='hosted' AND state='queued' ORDER BY pull_number LIMIT 101`, project) diff --git a/internal/reviewexec/run_selection_schema.go b/internal/reviewexec/run_selection_schema.go index cb8145282..39e3b1053 100644 --- a/internal/reviewexec/run_selection_schema.go +++ b/internal/reviewexec/run_selection_schema.go @@ -107,6 +107,10 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro return err } direct, err := directOperationConflictsWithSelectionCustody(ctx, q, project, link) + if isRetainedOperationDecodeError(err) { + unproved = true + break + } if err != nil { return err } @@ -132,6 +136,9 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro return runUnavailable() } direct, err := directOperationConflictsWithSelectionCustody(ctx, q, project, operation) + if isRetainedOperationDecodeError(err) { + return automaticProjectStateFailure(linkedSelectionCustodyHeld, "This review operation is held for selection custody recovery.", 403) + } if err != nil { return err } diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 456db7f38..d9b59d2ef 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -167,6 +167,7 @@ type runChoice struct { state, reason string sourceReason string prefix []SourcePlan + sourcePrefixComplete bool number int64 head string automaticQueueLimit *int @@ -439,6 +440,7 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 } } choice.prefix = append(choice.prefix, plan) + choice.sourcePrefixComplete = i == len(queue)-1 var target int64 var reason string bindingHeld := false @@ -543,6 +545,7 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR wg.Go(func() { timer := time.NewTimer(0) defer timer.Stop() + var cursor runCandidateCursor for { select { case <-workerCtx.Done(): @@ -553,7 +556,7 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR if workerCtx.Err() != nil { return } - worked, err := e.runNext(workerCtx, owned) + worked, err := e.runNextInDrain(workerCtx, owned, &cursor) if err != nil { if workerCtx.Err() != nil { return @@ -568,6 +571,7 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR if worked { timer.Reset(0) } else { + cursor = runCandidateCursor{} timer.Reset(500 * time.Millisecond) } } @@ -591,9 +595,12 @@ type runCandidateCursor struct { } func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) (bool, error) { - var cursor runCandidateCursor + return e.runNextInDrain(ctx, readers, &runCandidateCursor{}) +} + +func (e *Engine) runNextInDrain(ctx context.Context, readers map[string]TargetReader, cursor *runCandidateCursor) (bool, error) { for { - worked, err := e.runNextCandidate(ctx, readers, &cursor) + worked, err := e.runNextCandidate(ctx, readers, cursor) if !selectionCustodyUnproved(err) { return worked, err } @@ -929,6 +936,13 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } boundPrefix = c.Queue[:limit] if choice.state == "selected" && choice.automaticBasisRevision != 0 { + grants, err := readAutomaticGrantRevisions(ctx, tx, r.ProjectID, r.Channel, boundPrefix) + if err != nil { + return err + } + if !slices.Equal(grants, choice.automaticGrantRevisions) { + return updateRun(ctx, tx, current, "held", "selection_changed", "") + } routeSequence, err := automaticRouteSequence(ctx, tx, r.ProjectID) if err != nil { return err @@ -985,10 +999,15 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } return updateRun(ctx, tx, current, "held", choice.reason, "") } - front, reason, err := e.runFront(ctx, tx, current, repo, choice.prefix, true) + front, reason, err := e.runFront(ctx, tx, current, repo, choice.prefix, choice.sourcePrefixComplete) if err != nil { return finishFrontReadError(current, err) } + if choice.state == "selected" && front != choice.number && !choice.sourcePrefixComplete && !globalFrontHold(reason) { + // The selected pull ended the first source read early. A + // changed front cannot acknowledge unseen pulls as served. + return updateRun(ctx, tx, current, "held", "selection_changed", "") + } if reason != "" { return updateRun(ctx, tx, current, "held", reason, "") } diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index 1130629b9..eefd7b4d8 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -232,7 +232,20 @@ type pullSchedulingStateError struct { func (e *pullSchedulingStateError) Error() string { return e.err.Error() } func (e *pullSchedulingStateError) Unwrap() error { return e.err } -func readPullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) (s PullScheduling, err error) { +func readPullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) (PullScheduling, error) { + current, err := readPullSchedulingProjection(ctx, tx, project, pull) + if err != nil || current.Revision != 0 { + return current, err + } + orphan, err := retainedOrphanPullScheduling(ctx, tx, current) + var unavailable *schedulingHistoryUnavailable + if errors.As(err, &unavailable) { + return current, &pullSchedulingStateError{err, project, pull} + } + return orphan, err +} + +func readPullSchedulingProjection(ctx context.Context, tx *sql.Tx, project string, pull int64) (s PullScheduling, err error) { s.ProjectID = project s.PullNumber = pull var revision, paused, reason, actor, updated any diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 3478dfa86..841be64d0 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -493,12 +493,12 @@ func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project st basis, err := automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) if err != nil { var unreadable *automaticPullAdjudicationUnavailable - if !p.Paused || !errors.As(err, &unreadable) { + if !errors.As(err, &unreadable) { return "", false, err } // This is not a per-pull eligibility basis and it is never used - // for a selected pull. Keep the paused row and its revision in - // the degraded queue identity without pretending its hash exists. + // for a selected pull. Keep the row position and observed + // revision without pretending its digest or readiness exists. values = append(values, []any{pull, nil, p.Revision}) degraded = true continue @@ -697,6 +697,16 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) } return 0, err } + o, err := readOperationIdentity(ctx, tx, project, operation) + if err != nil { + if isRetainedOperationDecodeError(err) { + continue + } + return 0, err + } + if r.OperationID != o.ID || r.ActorID != o.ActorID || r.WorkerID != o.WorkerID || r.Channel != o.Channel { + continue + } if err = e.requireAutomaticRun(ctx, tx, r); err != nil { var failure *core.Error if errors.As(err, &failure) && failure.Code == "automation_authorization_changed" { diff --git a/internal/reviewexec/scheduling_selected_basis_guard_test.go b/internal/reviewexec/scheduling_selected_basis_guard_test.go index 172523221..1307e4165 100644 --- a/internal/reviewexec/scheduling_selected_basis_guard_test.go +++ b/internal/reviewexec/scheduling_selected_basis_guard_test.go @@ -102,6 +102,12 @@ func TestSelectedChildDoesNotSettleRearmedLaneBasis(t *testing.T) { t.Fatal(err) } if drift { + if got.OperationID != "" { + child, err := f.e.ReadOperation(t.Context(), scope, got.OperationID) + if err != nil || child.PullNumber != 2 || child.HeadSHA != strings.Repeat("a", 40) { + t.Fatalf("retained child must bind the originally read source: child=%+v err=%v", child, err) + } + } if !advanced { t.Fatal("fixture did not publish current head during source acquisition") } diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 99a4f81b4..0d8d40af5 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -83,6 +83,9 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { if ahead { return schedulingUnavailable() } + if err = validateRetainedSchedulingSettingsPayloads(ctx, tx); err != nil { + return err + } if err = validateSchedulingAuthoritySnapshot(ctx, tx); err != nil { return err } @@ -164,7 +167,7 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { if err = scanSchedulingSnapshot(rows, &selection, &project, &revision, &basis, &settled, &pull, &pullBasis, &actor, &worker, &credential); err != nil { return err } - if !validRunID(selection) || !identifier.MatchString(project) || revision < 1 || !hash.MatchString(basis) || settled != "" && !hash.MatchString(settled) || pull < 0 || pull > 2147483647 || pull > 0 && !hash.MatchString(pullBasis) || !identifier.MatchString(actor) || !identifier.MatchString(worker) || !identifier.MatchString(credential) { + if !validRunID(selection) || !identifier.MatchString(project) || revision < 1 || !hash.MatchString(basis) || settled != "" && !hash.MatchString(settled) || pull < 0 || pull > 2147483647 || pull > 0 && (!hash.MatchString(pullBasis) || settled == "") || !identifier.MatchString(actor) || !identifier.MatchString(worker) || !identifier.MatchString(credential) { return core.Fail("storage_unavailable", "Stored automatic review attribution is unavailable.", 503) } } @@ -174,6 +177,33 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { return rows.Close() } +// Witnesses are optional for legacy settings, but every retained body must +// be decodable under its own native revision. +func validateRetainedSchedulingSettingsPayloads(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, `SELECT revision,CASE WHEN typeof(payload_json)='text' + AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events + WHERE event_type='review.scheduling_updated'`) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var raw any + var body sql.NullString + if err := rows.Scan(&raw, &body); err != nil { + return err + } + revision, ok := raw.(int64) + if !ok || revision < 1 { + return schedulingUnavailable() + } + if _, _, _, valid := readSchedulingEventPayload(body, revision); !valid { + return schedulingUnavailable() + } + } + return rows.Err() +} + // Preserve SQLite storage types before checking control and attribution values. // database/sql otherwise accepts conversions (notably BLOB to string) that the // live control readers deliberately reject. Genuine scan/query errors propagate. @@ -252,7 +282,7 @@ const orphanPullSchedulingSelectSQL = ` // Materializing a control must not hide earlier unreadable event timestamps. func validateOrphanPullSchedulingHistory(ctx context.Context, tx *sql.Tx, scopeClause string, args ...any) error { rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+scopeClause+`) - SELECT o.resource_id,o.payload,CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END + SELECT o.resource_id,e.actor_id,o.payload,CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END FROM orphan_history o JOIN events e ON e.sequence=o.sequence`, args...) if err != nil { return err @@ -260,12 +290,15 @@ func validateOrphanPullSchedulingHistory(ctx context.Context, tx *sql.Tx, scopeC defer rows.Close() for rows.Next() { var at, payload sql.NullString - var raw any - if err := rows.Scan(&raw, &payload, &at); err != nil { + var raw, rawActor any + if err := rows.Scan(&raw, &rawActor, &payload, &at); err != nil { return err } id, native := raw.(string) pull, parseErr := strconv.ParseInt(id, 10, 32) + if _, textActor := rawActor.(string); !textActor { + return schedulingUnavailable() + } if !native || parseErr != nil || pull < 1 || strconv.FormatInt(pull, 10) != id || !at.Valid || !roundTime(at.String) || !pullSchedulingPayloadMatchesPull(payload, pull) { return schedulingUnavailable() } @@ -322,16 +355,27 @@ func scanOrphanPullResume(row interface{ Scan(...any) error }) (PullScheduling, return PullScheduling{ProjectID: project.String, PullNumber: pull, Revision: nativeRevision, ActorID: actor.String, UpdatedAt: createdAt.String}, nil } -// Read/mutate controls must honor the retained CAS position even where an -// older runtime discarded an unpaused projection. Ordinary admission reads -// the current pause bit only and need not re-scan historical events. +// Read/mutate controls must honor retained CAS even where an older runtime +// discarded an unpaused projection. Admission uses the same legacy proof. func editablePullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) (PullScheduling, error) { - current, err := readPullScheduling(ctx, tx, project, pull) + current, err := readPullSchedulingProjection(ctx, tx, project, pull) if err != nil || current.Revision != 0 { return current, err } + return retainedOrphanPullScheduling(ctx, tx, current) +} + +func retainedOrphanPullScheduling(ctx context.Context, tx *sql.Tx, current PullScheduling) (PullScheduling, error) { + project, pull := current.ProjectID, current.PullNumber const scopeClause = ` AND e.project_id=? AND e.resource_id IN (?,CAST(? AS BLOB))` pullID := strconv.FormatInt(pull, 10) + // The ordinary no-control/no-history path is a single indexed lookup. + var exists bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events e + WHERE e.event_type IN ('review.pull_scheduling_updated',CAST('review.pull_scheduling_updated' AS BLOB))`+scopeClause+`)`, + project, pullID, pullID).Scan(&exists); err != nil || !exists { + return current, err + } if err := validateOrphanPullSchedulingHistory(ctx, tx, scopeClause, project, pullID, pullID); err != nil { return current, err } @@ -454,14 +498,14 @@ func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) return err } revision, integer := nativeRevision.(int64) - if !integer || !createdAt.Valid || !roundTime(createdAt.String) || !pullSchedulingPayloadMatchesPull(payload, pull) { + eventActor, textActor := nativeEventActor.(string) + if !textActor || !integer || !createdAt.Valid || !roundTime(createdAt.String) || !pullSchedulingPayloadMatchesPull(payload, pull) { return schedulingUnavailable() } if revision < controlRevision { continue } - eventActor, textActor := nativeEventActor.(string) - if (project == lastProject && pull == lastPull) || !textActor || revision != controlRevision || eventActor != actor || !validPullSchedulingPayload(payload, pull, paused == 1) { + if (project == lastProject && pull == lastPull) || revision != controlRevision || eventActor != actor || !validPullSchedulingPayload(payload, pull, paused == 1) { return schedulingUnavailable() } count++ diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index bcea5b603..8dbfb6807 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "errors" + "time" ) // Recheck recovery fences during every admission snapshot, including after @@ -32,7 +33,7 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin if err != nil { return "", err } - if current.Revision == 0 { + if current.Revision == 0 || accepted > current.Revision { return "automation_authorization_changed", nil } initial, err := automaticSourceInitialRead(ctx, tx, r) @@ -123,14 +124,19 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er // For rows with no acceptance event, millisecond ties conservatively fence. // Event sequence is the durable acceptance order even if the wall clock // moves backwards. Missing acceptance evidence is not permission to retry. - var accepted int64 - err := tx.QueryRowContext(ctx, `SELECT sequence FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_requested' AND revision=1 ORDER BY sequence DESC LIMIT 1`, r.ProjectID, r.ID).Scan(&accepted) - if errors.Is(err, sql.ErrNoRows) { - return true, nil - } + acceptance, err := readSelectionRequestedEvent(ctx, tx, r) if err != nil { return false, err } + if acceptance.sequence == 0 { + return true, nil + } + acceptedAt, err := time.Parse(time.RFC3339Nano, r.CreatedAt) + if err != nil || acceptedAt.IsZero() { + return true, nil + } + comparedAt := acceptedAt.UTC().Format(time.RFC3339Nano) + accepted := acceptance.sequence var superseded bool err = tx.QueryRowContext(ctx, `SELECT EXISTS( SELECT 1 FROM review_selections s WHERE s.project_id=? AND s.channel=? AND s.id<>? @@ -167,6 +173,6 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er AND (SELECT count(*) FROM events witness WHERE witness.project_id=parent.project_id AND witness.resource_id=parent.id AND witness.event_type='review.selection_requested' AND witness.revision=1)=1 ) -)`, r.ProjectID, r.Channel, r.ID, r.CreatedAt, r.ProjectID, r.Channel, r.CreatedAt, r.ProjectID, accepted, r.Channel, r.ProjectID, accepted, r.Channel).Scan(&superseded) +)`, r.ProjectID, r.Channel, r.ID, comparedAt, r.ProjectID, r.Channel, comparedAt, r.ProjectID, accepted, r.Channel, r.ProjectID, accepted, r.Channel).Scan(&superseded) return superseded, err } diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 06c129cce..aec6da6e8 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -349,6 +349,13 @@ func (e *Engine) scanPendingForWorker(ctx context.Context, probeDrafts bool, bat return e.scanPendingInLane(ctx, probeDrafts, batchLimit, worker, nil) } +// A custody conflict can isolate only the exact refused operation. +func pendingSelectionCustodyRefused(o Operation, err error) bool { + var conflict *localSelectionCustodyConflict + return isLinkedSelectionCustodyHeld(err) || + errors.As(err, &conflict) && conflict.project == o.ProjectID && conflict.operation == o.ID +} + func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchLimit, worker int, receipt *pendingExhaustion) (operations []Operation, resultErr error) { // SQL may report ErrTxDone after the scan deadline rolls back its transaction. defer func() { @@ -402,7 +409,7 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL return Operation{}, nil } if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { - if automaticProjectRefused(err) { + if automaticProjectRefused(err) || pendingSelectionCustodyRefused(o, err) { return Operation{}, nil } return Operation{}, err @@ -830,7 +837,7 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return nil } - if automaticProjectRefused(err) || isLinkedSelectionCustodyHeld(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + if automaticProjectRefused(err) || pendingSelectionCustodyRefused(o, err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { continue } var refusal *core.Error @@ -852,7 +859,7 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return nil } - if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + if automaticProjectRefused(err) || pendingSelectionCustodyRefused(o, err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { continue } var failure *core.Error From 98e882fb78c48f501b856061b1c92d45ea813b14 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 01:28:57 +1300 Subject: [PATCH 31/34] Move further retained review regressions into qualification PR --- internal/backup/operation_list_index_test.go | 50 --- internal/backup/physical_schema_test.go | 56 ---- internal/backup/review_fronts_test.go | 34 -- .../cli_recorded_publish_settlement_test.go | 50 --- .../live_cli_preparation_settlement_test.go | 206 ------------ .../scheduling_admission0030_test.go | 121 -------- .../scheduling_quarantine0030_test.go | 109 ------- .../scheduling_recovery_regression_test.go | 292 ------------------ .../scheduling_source_hold_basis_test.go | 67 ---- .../supervisor_classification_test.go | 40 --- 10 files changed, 1025 deletions(-) delete mode 100644 internal/reviewexec/cli_recorded_publish_settlement_test.go delete mode 100644 internal/reviewexec/live_cli_preparation_settlement_test.go delete mode 100644 internal/reviewexec/scheduling_admission0030_test.go delete mode 100644 internal/reviewexec/scheduling_quarantine0030_test.go delete mode 100644 internal/reviewexec/scheduling_recovery_regression_test.go delete mode 100644 internal/reviewexec/scheduling_source_hold_basis_test.go delete mode 100644 internal/reviewexec/supervisor_classification_test.go diff --git a/internal/backup/operation_list_index_test.go b/internal/backup/operation_list_index_test.go index abba28cb5..d2ca46b9d 100644 --- a/internal/backup/operation_list_index_test.go +++ b/internal/backup/operation_list_index_test.go @@ -116,53 +116,3 @@ 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 07b72dd76..c72d5cb55 100644 --- a/internal/backup/physical_schema_test.go +++ b/internal/backup/physical_schema_test.go @@ -2,12 +2,8 @@ package backup import ( "database/sql" - "fmt" "path/filepath" - "strings" "testing" - - "github.com/benhook1013/FireController/internal/reviewexec" ) func TestDomainPhysicalSchemaExactInventory(t *testing.T) { @@ -52,58 +48,6 @@ 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 e90af049d..7995e641b 100644 --- a/internal/backup/review_fronts_test.go +++ b/internal/backup/review_fronts_test.go @@ -94,37 +94,3 @@ 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/cli_recorded_publish_settlement_test.go b/internal/reviewexec/cli_recorded_publish_settlement_test.go deleted file mode 100644 index 1b39901ff..000000000 --- a/internal/reviewexec/cli_recorded_publish_settlement_test.go +++ /dev/null @@ -1,50 +0,0 @@ -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/live_cli_preparation_settlement_test.go b/internal/reviewexec/live_cli_preparation_settlement_test.go deleted file mode 100644 index 5a0ec54ba..000000000 --- a/internal/reviewexec/live_cli_preparation_settlement_test.go +++ /dev/null @@ -1,206 +0,0 @@ -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/scheduling_admission0030_test.go b/internal/reviewexec/scheduling_admission0030_test.go deleted file mode 100644 index cc781210d..000000000 --- a/internal/reviewexec/scheduling_admission0030_test.go +++ /dev/null @@ -1,121 +0,0 @@ -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_quarantine0030_test.go b/internal/reviewexec/scheduling_quarantine0030_test.go deleted file mode 100644 index 430adb7f3..000000000 --- a/internal/reviewexec/scheduling_quarantine0030_test.go +++ /dev/null @@ -1,109 +0,0 @@ -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 deleted file mode 100644 index 69e5112fe..000000000 --- a/internal/reviewexec/scheduling_recovery_regression_test.go +++ /dev/null @@ -1,292 +0,0 @@ -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_source_hold_basis_test.go b/internal/reviewexec/scheduling_source_hold_basis_test.go deleted file mode 100644 index 72f0498e3..000000000 --- a/internal/reviewexec/scheduling_source_hold_basis_test.go +++ /dev/null @@ -1,67 +0,0 @@ -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/supervisor_classification_test.go b/internal/reviewexec/supervisor_classification_test.go deleted file mode 100644 index 1efa0eda6..000000000 --- a/internal/reviewexec/supervisor_classification_test.go +++ /dev/null @@ -1,40 +0,0 @@ -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()) - } - }) - } -} From 7f72accf419c602235cb1a1f3a9a21362266315f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 03:36:13 +1300 Subject: [PATCH 32/34] Address retained scheduling and recovery review findings --- internal/backup/scheduling_test.go | 23 +++++++ .../reviewexec/allowance_observation_test.go | 21 ++++++ internal/reviewexec/cli_pause_no_start.go | 36 +++++++++- internal/reviewexec/policy_admission.go | 9 ++- internal/reviewexec/run_selection_test.go | 24 +++++++ internal/reviewexec/run_selection_worker.go | 69 ++++++++++++------- internal/reviewexec/scheduling_automatic.go | 35 +++++++--- .../reviewexec/scheduling_source_retry.go | 2 +- internal/reviewprocess/process.go | 11 +++ internal/reviewprocess/process_test.go | 25 +++++++ internal/reviewruntime/cli_driver.go | 22 +++++- internal/reviewruntime/cli_driver_test.go | 19 +++-- .../cli_preparation_reason_test.go | 5 +- 13 files changed, 252 insertions(+), 49 deletions(-) diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index 08edfd6aa..4269f00c8 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -70,6 +70,15 @@ func TestSchedulingBackupRetainsCanonicalProjectRow(t *testing.T) { } func TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { + for _, version := range []string{"1", "2"} { + t.Run("schema-v"+version, func(t *testing.T) { + testSchedulingRestorePreservesHistoricalPullResumeRevision(t, version) + }) + } +} + +func testSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T, version string) { + t.Helper() f := newRestoreFixture(t) e := selectionInventoryEngine(t, f.store) scope := routePolicyInventoryScope(t, f) @@ -103,6 +112,12 @@ func TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { if len(sourceControls) != 1 { t.Fatalf("expected one untouched control, got %v", sourceControls) } + if version == "1" { + if _, err := f.store.DB().Exec(`DROP TABLE review_scheduling; + UPDATE metadata SET value='1' WHERE key='schema:review_scheduling';` + reviewexec.SchedulingSchemaSQL()[0]); err != nil { + t.Fatal(err) + } + } bundle := restoreBundle(t, f) immutable := restoreTree(t, bundle.Path) if _, err := Inspect(t.Context(), bundle.Path); err != nil { @@ -117,6 +132,14 @@ func TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { t.Fatal(err) } defer dst.Close() + var marker string + var cliColumns int + if err := dst.QueryRow(`SELECT value FROM metadata WHERE key='schema:review_scheduling'`).Scan(&marker); err != nil || marker != version { + t.Fatalf("restore changed scheduling schema marker: got %q, want %q: %v", marker, version, err) + } + if err := dst.QueryRow(`SELECT count(*) FROM pragma_table_info('review_scheduling') WHERE name='automatic_cli'`).Scan(&cliColumns); err != nil || (cliColumns == 1) != (version == "2") { + t.Fatalf("restore changed physical scheduling schema v%s: columns=%d: %v", version, cliColumns, err) + } want := [][]any{sourceControls[0], event[0]} if got := restoreRows(t, dst, controls); !reflect.DeepEqual(want, got) { t.Fatalf("restored controls lost canonical revision or attribution: got %v, want %v", got, want) diff --git a/internal/reviewexec/allowance_observation_test.go b/internal/reviewexec/allowance_observation_test.go index f07f0dbac..5be0f9c8b 100644 --- a/internal/reviewexec/allowance_observation_test.go +++ b/internal/reviewexec/allowance_observation_test.go @@ -37,6 +37,27 @@ func cooldownObservationFixture(t *testing.T) (*attemptFixture, Attempt, HostedA return f, a, in } +func TestHostedPauseRetainsExactNegativeCooldownWithoutAdmission(t *testing.T) { + f, attempt, input := cooldownObservationFixture(t) + zero, paused := int64(0), true + if _, err := f.e.ConfigurePullScheduling(t.Context(), f.scope(t, attemptProject, f.writer, false), "pause-live-cooldown", input.Anchor.PullNumber, PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused}); err != nil { + t.Fatal(err) + } + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, attempt.ID, attempt.Revision, input); err != nil { + t.Fatal("retaining the original negative observation while paused:", err) + } + if _, err := f.e.ExecutionContext(t.Context(), attemptProject, attempt.OperationID); err == nil { + t.Fatal("retention removed the ordinary pause check") + } + if _, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, attempt.ID, attempt.Revision); err != nil { + t.Fatal("scheduling the retained cooldown:", err) + } + got, err := f.e.ReadOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), attempt.OperationID) + if err != nil || got.State != "queued" || got.Wait == nil { + t.Fatal("original request did not keep its cooldown", got, err) + } +} + func TestHeldAllowanceSQLReadHTTPReplayAndValidation(t *testing.T) { for _, channel := range []string{"cli", "hosted"} { t.Run(channel, func(t *testing.T) { diff --git a/internal/reviewexec/cli_pause_no_start.go b/internal/reviewexec/cli_pause_no_start.go index 5517a82f2..9fb9fdde5 100644 --- a/internal/reviewexec/cli_pause_no_start.go +++ b/internal/reviewexec/cli_pause_no_start.go @@ -5,6 +5,7 @@ import ( "database/sql" "encoding/json" "errors" + "strconv" "sync/atomic" "time" @@ -207,11 +208,11 @@ func (e *Engine) probeCLIPauseSettlement(ctx context.Context, w *cliPauseNoStart func validateCLIPauseNoStartRecord(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) error { var body sql.NullString - var actor, revision, eventType any + var actor, revision, eventType, sequence any var count int64 err := q.QueryRowContext(ctx, `SELECT CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END, - actor_id,revision,event_type,count(*) OVER() FROM events WHERE project_id=? AND resource_id=? AND - (event_type=? OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)=?))`, o.ProjectID, a.ID, cliPauseNoStartEvent, cliPauseNoStartEvent).Scan(&body, &actor, &revision, &eventType, &count) + actor_id,revision,event_type,sequence,count(*) OVER() FROM events WHERE project_id=? AND resource_id=? AND + (event_type=? OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)=?))`, o.ProjectID, a.ID, cliPauseNoStartEvent, cliPauseNoStartEvent).Scan(&body, &actor, &revision, &eventType, &sequence, &count) if errors.Is(err, sql.ErrNoRows) { return waitUnavailable() } @@ -224,6 +225,35 @@ func validateCLIPauseNoStartRecord(ctx context.Context, q EvidenceQuery, o Opera proof.OperationID != o.ID || proof.PauseRevision < 1 { return waitUnavailable() } + witness, ok := sequence.(int64) + if !ok || witness < 1 { + return waitUnavailable() + } + pull := strconv.FormatInt(o.PullNumber, 10) + pauseRev := strconv.FormatInt(proof.PauseRevision, 10) + var kind, resource, pauseRevision, pauseActor, pauseSequence any + var pauseBody sql.NullString + var pauseCount int64 + err = q.QueryRowContext(ctx, `SELECT event_type,resource_id,revision,actor_id,sequence, + CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END,count(*) OVER() + FROM events WHERE project_id=? + AND event_type IN ('review.pull_scheduling_updated',CAST('review.pull_scheduling_updated' AS BLOB)) + AND resource_id IN (?,CAST(? AS BLOB)) + AND (revision=? OR (typeof(revision)='blob' AND CAST(revision AS TEXT)=?))`, + o.ProjectID, pull, pull, proof.PauseRevision, pauseRev).Scan(&kind, &resource, &pauseRevision, &pauseActor, &pauseSequence, &pauseBody, &pauseCount) + if errors.Is(err, sql.ErrNoRows) { + return waitUnavailable() + } + if err != nil { + return err + } + at, seqOK := pauseSequence.(int64) + pa, actorOK := pauseActor.(string) + if pauseCount != 1 || kind != "review.pull_scheduling_updated" || resource != pull || + pauseRevision != proof.PauseRevision || !seqOK || at < 1 || at >= witness || + !actorOK || !identifier.MatchString(pa) || !validPullSchedulingPayload(pauseBody, o.PullNumber, true) { + return waitUnavailable() + } return nil } diff --git a/internal/reviewexec/policy_admission.go b/internal/reviewexec/policy_admission.go index 74dbea265..725f01a9d 100644 --- a/internal/reviewexec/policy_admission.go +++ b/internal/reviewexec/policy_admission.go @@ -49,12 +49,15 @@ func (e *Engine) currentExecutionContext(ctx context.Context, tx *sql.Tx, operat return e.executionContext(ctx, tx, operation, false) } -// A cooldown is retained negative evidence, not admission. Project pause may -// delay its retry without discarding it; all other authority checks still apply. +// A cooldown is retained negative evidence, not admission. Project or pull +// pause may delay its retry without discarding it; other authority checks still apply. func (e *Engine) executionContext(ctx context.Context, tx *sql.Tx, operation Operation, retainCooldown bool) (ExecutionContext, error) { result := ExecutionContext{Operation: operation} if err := requirePullScheduling(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil { - return ExecutionContext{}, err + var pause *core.Error + if !retainCooldown || operation.Channel != "hosted" || !errors.As(err, &pause) || pause.Code != "pull_scheduling_paused" { + return ExecutionContext{}, err + } } if err := e.requireAutomaticOperation(ctx, tx, operation); err != nil { return ExecutionContext{}, err diff --git a/internal/reviewexec/run_selection_test.go b/internal/reviewexec/run_selection_test.go index 89ccd386a..3475ce6cc 100644 --- a/internal/reviewexec/run_selection_test.go +++ b/internal/reviewexec/run_selection_test.go @@ -87,6 +87,30 @@ func selectionCounts(t *testing.T, f *attemptFixture) string { } return fmt.Sprint(values) } +func TestRunSelectionDrainDefersNewWorkToAnotherPass(t *testing.T) { + f := selectionFixture(t) + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}} + first, _ := selectionEnqueue(t, f, "first-sweep-cli", "cli", nil) + var cursor runCandidateCursor + if worked, err := f.e.runNextInDrain(t.Context(), readers, &cursor); err != nil || !worked { + t.Fatalf("first accepted selection did not run: %t %v", worked, err) + } + if got := selectionRead(t, f, first.ID); got.State != "selected" { + t.Fatalf("first selection did not create its child: %s", got.State) + } + next, _ := selectionEnqueue(t, f, "next-sweep-hosted", "hosted", nil) + if worked, err := f.e.runNextInDrain(t.Context(), readers, &cursor); err != nil || worked { + t.Fatalf("later acceptance joined a pass already in progress: %t %v", worked, err) + } + cursor = runCandidateCursor{} + if worked, err := f.e.runNextInDrain(t.Context(), readers, &cursor); err != nil || !worked { + t.Fatalf("later acceptance did not enter the next pass: %t %v", worked, err) + } + if got := selectionRead(t, f, next.ID); got.State != "selected" { + t.Fatalf("next pass did not create its child: %s", got.State) + } +} + func TestRunSelectionOneChildReplayRestartAndOriginalBinding(t *testing.T) { f := selectionFixture(t) reader := &refreshTestReader{} diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index d9b59d2ef..7152b6b68 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -590,8 +590,10 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR } type runCandidateCursor struct { - createdAt any - id any + createdAt any + id any + throughSequence int64 + hasHorizon bool } func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) (bool, error) { @@ -627,6 +629,14 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target project, id, expected = "", "", 0 nativeProject, nativeID, nativeCreatedAt = nil, nil, nil return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + // A drain pass covers the selections already accepted at its start. + // Later accepted work is eligible on the next pass. + if !cursor.hasHorizon { + if err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(sequence),0) FROM events`).Scan(&cursor.throughSequence); err != nil { + return err + } + cursor.hasHorizon = true + } // Request capacity is a scheduling constraint, not a terminal hold. // Skip saturated projects before source work so they cannot occupy // both selection workers or repeatedly reacquire provider facts. @@ -635,10 +645,12 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target err := tx.QueryRowContext(ctx, `SELECT s.project_id,s.id,`+selectionClaimRevision+`,s.created_at FROM review_selections s WHERE s.state='queued' AND (? IS NULL OR (s.created_at,s.id)>(?,?)) + AND NOT EXISTS (SELECT 1 FROM events later WHERE later.project_id=s.project_id AND later.resource_id=s.id + AND later.event_type='review.selection_requested' AND later.revision=1 AND later.sequence>?) AND (s.operation_id IS NULL OR (typeof(s.project_id)='text' AND typeof(s.id)='text')) AND (SELECT count(*) FROM review_operations WHERE state IN ('queued','preparing','posting','active','uncertain')) 0 && choice.automaticQueueLimit != nil { + // An automatic result may acknowledge only source plans it evaluated. + if settle && choice.automaticQueueLimit != nil { index := slices.IndexFunc(choice.prefix, func(plan SourcePlan) bool { return plan.Pull.Number == pull }) - settle = index >= 0 && choice.prefix[index].Pull.HeadSHA == choice.head - if settle { - evaluated := choice.prefix[index].Pull - retained, err := currentReviewPull(ctx, tx, r.ProjectID, pull) + settle = pull == 0 || (index >= 0 && choice.prefix[index].Pull.HeadSHA == choice.head) + for _, plan := range choice.prefix { + if !settle { + break + } + evaluated := plan.Pull + retained, err := currentReviewPull(ctx, tx, r.ProjectID, evaluated.Number) switch { case missingCurrentPull(err): - // A new queue entry may not have a workspace projection yet. - // Disappearance of a previously pinned entry is a drift. - _, pinned := metadataPins[pull] + // An entry without a pinned projection may be new. + _, pinned := metadataPins[evaluated.Number] settle = !pinned case err != nil: resultErr, settle = err, false @@ -879,10 +897,11 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } } } - // A source hold did not evaluate the live workspace facts - // that settlement would hash. Keep its accepted basis. + // A source hold did not evaluate the live workspace facts. if settle && !(pull == 0 && choice.sourceReason != "") { - resultErr = e.settleAutomaticBasis(ctx, tx, r, pull) + complete := choice.automaticQueueLimit == nil || + (choice.sourcePrefixComplete && len(choice.prefix) == len(boundPrefix)) + resultErr = e.settleAutomaticBasis(ctx, tx, r, pull, complete) } } if automaticProjectRefused(resultErr) { @@ -953,10 +972,14 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return updateRun(ctx, tx, current, "held", "selection_changed", "") } } - if current.Channel == "hosted" && current.Revision >= 4 && choice.state == "selected" { - initial, err := automaticSourceInitialRead(ctx, tx, current) - if err != nil { - return err + if current.Channel == "hosted" && choice.state == "selected" { + initial := false + if current.Revision >= 4 { + var err error + initial, err = automaticSourceInitialRead(ctx, tx, current) + if err != nil { + return err + } } if !initial { revisions, err := readAutomaticPullSchedulingRevisionsBound(ctx, tx, r.ProjectID, boundPrefix, true, choice.automaticPullScheduling) diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 841be64d0..976ecc69f 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -265,6 +265,7 @@ func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channe return err } count := 0 + unavailable := false for rows.Next() { count++ if count > 10000 { @@ -284,7 +285,8 @@ func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channe } } if adjudication && values[0] == nil { - return &automaticPullAdjudicationUnavailable{schedulingUnavailable()} + unavailable = true + continue } // Keep the original query label and JSON framing. Only the // channel's semantic revision differs after a relevant write. @@ -301,7 +303,13 @@ func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channe if err = rows.Err(); err != nil { return err } - return rows.Close() + if err = rows.Close(); err != nil { + return err + } + if unavailable { + return &automaticPullAdjudicationUnavailable{schedulingUnavailable()} + } + return nil } } @@ -773,18 +781,13 @@ func (e *Engine) automaticPullSuppressed(ctx context.Context, tx *sql.Tx, r Run, err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id<>? AND pull_number=? AND pull_basis_sha256=?)`, r.ProjectID, r.ID, pull, basis).Scan(&seen) return seen, err } -func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64) error { +func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64, complete bool) error { attribution, err := automaticSelectionBinding(ctx, tx, r) if err != nil || attribution.revision == 0 { return err } - c, _, err := readConfiguration(ctx, tx, r.ProjectID) - if err != nil { - return err - } - basis, _, err := e.automaticPlanningBasisChannel(ctx, tx, r.ProjectID, c, r.ID, r.Channel) - if err != nil { - return err + if !complete && pull == 0 { + return nil } pullBasis := "" if pull > 0 { @@ -793,6 +796,18 @@ func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pu return err } } + if !complete { + _, err = tx.ExecContext(ctx, `UPDATE review_automatic_selections SET pull_number=?,pull_basis_sha256=? WHERE selection_id=? AND project_id=?`, pull, pullBasis, r.ID, r.ProjectID) + return err + } + c, _, err := readConfiguration(ctx, tx, r.ProjectID) + if err != nil { + return err + } + basis, _, err := e.automaticPlanningBasisChannel(ctx, tx, r.ProjectID, c, r.ID, r.Channel) + if err != nil { + return err + } _, err = tx.ExecContext(ctx, `UPDATE review_automatic_selections SET settled_basis_sha256=?,pull_number=?,pull_basis_sha256=? WHERE selection_id=? AND project_id=?`, basis, pull, pullBasis, r.ID, r.ProjectID) return err } diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index 8dbfb6807..bef048328 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -147,7 +147,7 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er AND NOT EXISTS(SELECT 1 FROM events e WHERE e.project_id=o.project_id AND e.resource_id=o.id AND e.event_type='review.requested' AND e.revision=1) ) OR EXISTS( SELECT 1 FROM events e JOIN review_selections s ON s.project_id=e.project_id AND s.id=e.resource_id - WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.selection_requested' AND e.revision=1 AND s.channel=? + WHERE e.project_id=? AND e.sequence>? AND e.event_type IN ('review.selection_requested',CAST('review.selection_requested' AS BLOB)) AND s.channel=? ) OR EXISTS( SELECT 1 FROM events e JOIN review_operations o ON o.project_id=e.project_id AND o.id=e.resource_id WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.requested' AND e.revision=1 AND o.channel=? diff --git a/internal/reviewprocess/process.go b/internal/reviewprocess/process.go index b3ffe2b09..f2f07322c 100644 --- a/internal/reviewprocess/process.go +++ b/internal/reviewprocess/process.go @@ -193,6 +193,12 @@ func (r *Runner) RetireUsagePermit(workspace reviewworkspace.Workspace, usage Us // A returned capture is raw evidence for a caller-owned private journal; this // package does not classify success from exit status or inspect provider data. func (r *Runner) Review(ctx context.Context, workspace reviewworkspace.Workspace) (Capture, error) { + return r.ReviewWithStartGuard(ctx, workspace, nil) +} + +// ReviewWithStartGuard runs the caller's last authorization check after +// workspace verification and before handing off to the local process runner. +func (r *Runner) ReviewWithStartGuard(ctx context.Context, workspace reviewworkspace.Workspace, guard func(context.Context) error) (Capture, error) { if ctx == nil || ctx.Err() != nil { return Capture{}, processError("process_failed", false) } @@ -217,6 +223,11 @@ func (r *Runner) Review(ctx context.Context, workspace reviewworkspace.Workspace if commandCtx.Err() != nil { return Capture{}, processError("process_failed", false) } + if guard != nil { + if err := guard(commandCtx); err != nil { + return Capture{}, err + } + } result := r.run(commandCtx, workspace.Directory, []string{"review", "--agent", "--committed", "--base", workspace.ComparisonRef}, maxReviewOutput, maxErrorOutput) if err := r.manager.Verify(ctx, workspace); err != nil { if ctx.Err() != nil { diff --git a/internal/reviewprocess/process_test.go b/internal/reviewprocess/process_test.go index de1925c2b..46c0ec91c 100644 --- a/internal/reviewprocess/process_test.go +++ b/internal/reviewprocess/process_test.go @@ -133,6 +133,31 @@ func usageJSON(repository, organization string, remaining, limit, full, rolling return fmt.Sprintf(`{"type":"status","phase":"usage","status":"complete","organization":%q,"includedReviews":{"state":"available","repository":%q,"remaining":%d,"limit":%d,"fullCapacityInMs":%d,"rollingWindowMs":%d},"billingPeriod":{"state":"available","usageBillingStatus":"inactive"}}`, organization, repository, remaining, limit, full, rolling) } +func TestReviewStartGuardRefusesBeforeProcess(t *testing.T) { + f := newProcessFixture(t) + log := filepath.Join(f.dir, "started.log") + script := fmt.Sprintf(`if [ "$1" = usage ]; then printf '%%s' %q; else echo started > %q; fi`, usageJSON("owner/repo", "owner", 4, 5, 12000, 3600000), log) + r := f.runner(t, script) + if _, err := r.Usage(t.Context(), f.workspace, "owner/repo", "owner"); err != nil { + t.Fatal(err) + } + refused := fmt.Errorf("start refused by final check") + checks := 0 + capture, err := r.ReviewWithStartGuard(t.Context(), f.workspace, func(context.Context) error { + checks++ + return refused + }) + if err != refused || capture.Started || checks != 1 { + t.Fatalf("final check did not refuse before start: checks=%d started=%t err=%v", checks, capture.Started, err) + } + if _, err := os.Stat(log); !os.IsNotExist(err) { + t.Fatalf("unexpected process marker: %v", err) + } + if _, err := r.Review(t.Context(), f.workspace); !errorCode(err, "permit_required") { + t.Fatalf("refused launch reused its permit: %v", err) + } +} + func TestUsageAndReviewUseExactCommandsAndClosedEnvironment(t *testing.T) { f := newProcessFixture(t) log := filepath.Join(f.dir, "invocations.log") diff --git a/internal/reviewruntime/cli_driver.go b/internal/reviewruntime/cli_driver.go index 3f2489053..8f8242689 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -29,7 +29,7 @@ type CLIDriver struct { verify func(context.Context, reviewworkspace.Workspace) error retireUsage func(reviewworkspace.Workspace, reviewprocess.Usage) bool usage func(context.Context, reviewworkspace.Workspace, string, string) (reviewprocess.Usage, error) - review func(context.Context, reviewworkspace.Workspace) (reviewprocess.Capture, error) + review func(context.Context, reviewworkspace.Workspace, func(context.Context) error) (reviewprocess.Capture, error) mu sync.Mutex prepared map[string]*cliPrepared settling map[string]struct{} @@ -80,7 +80,7 @@ func NewCLIDriver(store *core.Store, engine *reviewexec.Engine, capability Opera if err != nil { return nil, err } - return &CLIDriver{store: store, engine: engine, capability: capability, manager: manager, captures: captures, exhaustions: exhaustions, reader: reader, fetch: manager.Fetch, verify: manager.Verify, usage: runner.Usage, retireUsage: runner.RetireUsagePermit, review: runner.Review, prepared: map[string]*cliPrepared{}, settling: map[string]struct{}{}}, nil + return &CLIDriver{store: store, engine: engine, capability: capability, manager: manager, captures: captures, exhaustions: exhaustions, reader: reader, fetch: manager.Fetch, verify: manager.Verify, usage: runner.Usage, retireUsage: runner.RetireUsagePermit, review: runner.ReviewWithStartGuard, prepared: map[string]*cliPrepared{}, settling: map[string]struct{}{}}, nil } // A successful preflight can be held by admission before Dispatch. Expire only @@ -256,7 +256,23 @@ func (d *CLIDriver) Dispatch(ctx context.Context, operation reviewexec.Operation return refusal, nil } started := time.Now().UTC() - capture, executionErr := d.review(ctx, prepared.workspace) + var guardedRefusal reviewexec.Result + var guardFailed bool + capture, executionErr := d.review(ctx, prepared.workspace, func(local context.Context) error { + var err error + guardedRefusal, err = d.engine.VerifyCLIAction(local, operation.ProjectID, attempt.ID, attempt.Revision, predecessors...) + guardFailed = err != nil + if guardedRefusal.HasCLIStartRefusal() { + return reviewHold("pull_scheduling_paused") + } + return err + }) + if guardedRefusal.HasCLIStartRefusal() { + return guardedRefusal, nil + } + if guardFailed { + return failed("admission_changed") + } finished := time.Now().UTC() possibleStart := capture.Started var processFailure *reviewprocess.Error diff --git a/internal/reviewruntime/cli_driver_test.go b/internal/reviewruntime/cli_driver_test.go index fcb66af2b..f7f1b11db 100644 --- a/internal/reviewruntime/cli_driver_test.go +++ b/internal/reviewruntime/cli_driver_test.go @@ -444,7 +444,10 @@ func TestCLIDriverFinalGuardsPreventProcessStart(t *testing.T) { f := newCLIDriverFixture(t) op, a := f.prepareAdmit(t, 2, 1, "guarded-driver") var runs atomic.Int64 - f.driver.review = func(context.Context, reviewworkspace.Workspace) (reviewprocess.Capture, error) { + f.driver.review = func(ctx context.Context, _ reviewworkspace.Workspace, guard func(context.Context) error) (reviewprocess.Capture, error) { + if err := guard(ctx); err != nil { + return reviewprocess.Capture{}, err + } runs.Add(1) return reviewprocess.Capture{}, nil } @@ -683,7 +686,10 @@ func TestCLIDriverCancelledAndPartialExecutionRetainsHonestEvidence(t *testing.T op, a := f.prepareAdmit(t, 2, 1, "retained-driver") var runs atomic.Int64 entered := make(chan struct{}) - f.driver.review = func(ctx context.Context, w reviewworkspace.Workspace) (reviewprocess.Capture, error) { + f.driver.review = func(ctx context.Context, w reviewworkspace.Workspace, guard func(context.Context) error) (reviewprocess.Capture, error) { + if err := guard(ctx); err != nil { + return reviewprocess.Capture{}, err + } runs.Add(1) close(entered) if mode == "no-start" { @@ -908,7 +914,10 @@ func TestCLIDriverPredecessorCorrectionAfterGitVerificationStopsReview(t *testin } return nil } - f.driver.review = func(context.Context, reviewworkspace.Workspace) (reviewprocess.Capture, error) { + f.driver.review = func(ctx context.Context, _ reviewworkspace.Workspace, guard func(context.Context) error) (reviewprocess.Capture, error) { + if err := guard(ctx); err != nil { + return reviewprocess.Capture{}, err + } reviews.Add(1) return reviewprocess.Capture{ExitCode: -1}, &reviewprocess.Error{Code: "process_failed"} } @@ -949,8 +958,8 @@ func TestCLIDriverRetainedEvidenceSurvivesMissingCurrentProjection(t *testing.T) f := newCLIDriverFixture(t) review := f.driver.review hookResult := make(chan error, 1) - f.driver.review = func(ctx context.Context, w reviewworkspace.Workspace) (reviewprocess.Capture, error) { - capture, err := review(ctx, w) + f.driver.review = func(ctx context.Context, w reviewworkspace.Workspace, guard func(context.Context) error) (reviewprocess.Capture, error) { + capture, err := review(ctx, w, guard) if err != nil { return capture, err } diff --git a/internal/reviewruntime/cli_preparation_reason_test.go b/internal/reviewruntime/cli_preparation_reason_test.go index 9bc7fc6f6..a5fdea235 100644 --- a/internal/reviewruntime/cli_preparation_reason_test.go +++ b/internal/reviewruntime/cli_preparation_reason_test.go @@ -113,7 +113,10 @@ func TestCLIDriverRealUsageHoldSettlesSupervisorWithoutReview(t *testing.T) { } } var reviews atomic.Int64 - f.driver.review = func(context.Context, reviewworkspace.Workspace) (reviewprocess.Capture, error) { + f.driver.review = func(ctx context.Context, _ reviewworkspace.Workspace, guard func(context.Context) error) (reviewprocess.Capture, error) { + if err := guard(ctx); err != nil { + return reviewprocess.Capture{}, err + } reviews.Add(1) return reviewprocess.Capture{}, errors.New("review must not execute") } From cdb2d6da05823b738e76a43a5dbd07423ca2c182 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 03:44:35 +1300 Subject: [PATCH 33/34] Stop repeated CLI preparation for a held predecessor --- internal/reviewexec/attempts.go | 30 ++++++++++++++++++++------ internal/reviewexec/supervisor.go | 9 +++++++- internal/reviewexec/supervisor_test.go | 21 ++++++++++++++++++ 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 56b8fb453..f30015bfa 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -455,8 +455,15 @@ func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operat } func (e *Engine) settleUnusedCLIPreparationWithAck(ctx context.Context, original Operation, captured Attempt, ack *unusedCLISettlementAck) error { + return e.settleUnusedCLIPreparationWithReason(ctx, original, captured, ack, "automatic_scheduling_unavailable") +} + +func (e *Engine) settleUnusedCLIPreparationWithReason(ctx context.Context, original Operation, captured Attempt, ack *unusedCLISettlementAck, reason string) error { + if reason != "automatic_scheduling_unavailable" && reason != "preparation_failed" { + return conflict() + } if ack.sequence != 0 { - committed, err := e.probeUnusedCLISettlementReceipt(ctx, original, captured, ack.attempt, 0) + committed, err := e.probeUnusedCLISettlementReceipt(ctx, original, captured, ack.attempt, 0, reason) if err != nil { return err } @@ -494,7 +501,7 @@ func (e *Engine) settleUnusedCLIPreparationWithAck(ctx context.Context, original if !errors.Is(err, errAllowanceObservationAbsent) { return err } - candidate, err := e.advanceAttempt(ctx, tx, o, a, "held", "automatic_scheduling_unavailable", "") + candidate, err := e.advanceAttempt(ctx, tx, o, a, "held", reason, "") if err != nil { return err } @@ -519,7 +526,12 @@ func (e *Engine) settleUnusedCLIPreparationWithAck(ctx context.Context, original // The settlement window may have expired after commit. Give // this exact read-only acknowledgement check its own short window. readCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) - committed := e.readUnusedCLISettlementReceipt(readCtx, original, captured, ack.attempt, ack.sequence) + var committed bool + if reason == "automatic_scheduling_unavailable" { + committed = e.readUnusedCLISettlementReceipt(readCtx, original, captured, ack.attempt, ack.sequence) + } else { + committed = e.readUnusedCLISettlementReceiptWithReason(readCtx, original, captured, ack.attempt, ack.sequence, reason) + } cancel() if committed { err = nil @@ -534,10 +546,14 @@ func (e *Engine) settleUnusedCLIPreparationWithAck(ctx context.Context, original // Reconcile the exact attempt-local settlement receipt without consulting the // successor. This is acknowledgement only; it cannot grant new work. func (e *Engine) readUnusedCLISettlementReceipt(ctx context.Context, original Operation, captured, proposed Attempt, sequence int64) bool { + return e.readUnusedCLISettlementReceiptWithReason(ctx, original, captured, proposed, sequence, "automatic_scheduling_unavailable") +} + +func (e *Engine) readUnusedCLISettlementReceiptWithReason(ctx context.Context, original Operation, captured, proposed Attempt, sequence int64, reason string) bool { if sequence <= 0 { return false } - committed, _ := e.probeUnusedCLISettlementReceipt(ctx, original, captured, proposed, sequence) + committed, _ := e.probeUnusedCLISettlementReceipt(ctx, original, captured, proposed, sequence, reason) return committed } @@ -563,7 +579,7 @@ func scanCLISettlementEvent(ctx context.Context, tx *sql.Tx, project, attemptID, return true, nil } -func (e *Engine) probeUnusedCLISettlementReceipt(ctx context.Context, original Operation, captured, proposed Attempt, expectedSequence int64) (bool, error) { +func (e *Engine) probeUnusedCLISettlementReceipt(ctx context.Context, original Operation, captured, proposed Attempt, expectedSequence int64, reason string) (bool, error) { if original.ProjectID != captured.ProjectID || original.ID != captured.OperationID || original.Channel != "cli" || captured.State != "preparing" || captured.Revision != 1 || captured.Anchor != nil || captured.Intent != "" || captured.ExternalID != "" { return false, conflict() @@ -589,10 +605,10 @@ func (e *Engine) probeUnusedCLISettlementReceipt(ctx context.Context, original O err = tx.QueryRowContext(ctx, `SELECT (SELECT count(*) FROM review_execution_transitions WHERE attempt_id=?)=2 AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=1 AND state='preparing' AND reason='preparing' AND external_id='') - AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=2 AND state='held' AND reason='automatic_scheduling_unavailable' AND external_id='') + AND EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=? AND revision=2 AND state='held' AND reason=? AND external_id='') AND NOT EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=?) AND NOT EXISTS(SELECT 1 FROM review_cli_preflight WHERE attempt_id=?) - AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, a.ID, a.ID, a.ID, a.ID, a.ID, a.ID).Scan(&exact) + AND NOT EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=?)`, a.ID, a.ID, a.ID, reason, a.ID, a.ID, a.ID).Scan(&exact) if err != nil { return false, err } diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index aec6da6e8..d2142b40e 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -102,8 +102,15 @@ func (e *Engine) settleCLIPreparationHandoff(ctx context.Context, original Opera } if h.source == nil { ack := &unusedCLISettlementAck{} + reason := "automatic_scheduling_unavailable" + var dirty *dirtyComparisonProofError + if errors.As(h.recovery.Err, &dirty) { + // The existing parent proof did not qualify. Do not spin up another + // preparation with the same predecessor, or grant provider work. + reason = "preparation_failed" + } return settleOwnedCLIWithinWindows(ctx, func(local context.Context) error { - return e.settleUnusedCLIPreparationWithAck(local, original, a, ack) + return e.settleUnusedCLIPreparationWithReason(local, original, a, ack, reason) }) } local, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) diff --git a/internal/reviewexec/supervisor_test.go b/internal/reviewexec/supervisor_test.go index c8baf8dba..d5cb863ba 100644 --- a/internal/reviewexec/supervisor_test.go +++ b/internal/reviewexec/supervisor_test.go @@ -1523,6 +1523,27 @@ func TestSupervisorCLICooldownDatabaseFailureRemainsFatal(t *testing.T) { } } +func TestCLIPreparationKeepsKnownPredecessorRefusalHeld(t *testing.T) { + f := supervisorFixture(t) + released := 0 + driver := &controlledDriver{prepare: func(context.Context, Operation, Configuration, Attempt) (Preparation, error) { + refusal := &dirtyComparisonProofError{&automaticProjectStateError{adjudicationStorageError()}} + return Preparation{}, CLIRefusalBeforeUsage(refusal, func() { released++ }) + }} + r := f.enqueue(t, attemptProject, "cli-local-proof-refusal", "cli", 2, 1) + drivers := map[string]Driver{"test-capability": driver} + for pass := 0; pass < 2; pass++ { + if err := f.e.processNext(t.Context(), drivers); err != nil { + t.Fatal(err) + } + } + got := cliWaitRead(t, f, r.ID) + if got.State != "held" || got.Reason != "preparation_failed" || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || released != 1 || + attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatalf("the known predecessor refusal was not held: %+v release=%d", got, released) + } +} + func TestHostedPreparationSettlesTypedComparisonRefusal(t *testing.T) { f := supervisorFixture(t) driver := &controlledDriver{prepare: func(context.Context, Operation, Configuration, Attempt) (Preparation, error) { From 602b5d7ba5fb8cb7234fc436de126ffd58b7cf34 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 04:08:05 +1300 Subject: [PATCH 34/34] Batch exact retained custody receipt reads --- internal/reviewexec/requests.go | 10 +- internal/reviewexec/run_selection_origin.go | 16 ++-- .../reviewexec/run_selection_receipt_batch.go | 94 +++++++++++++++++++ .../run_selection_receipt_batch_test.go | 63 +++++++++++++ internal/reviewexec/run_selection_schema.go | 51 +++++----- 5 files changed, 206 insertions(+), 28 deletions(-) create mode 100644 internal/reviewexec/run_selection_receipt_batch.go create mode 100644 internal/reviewexec/run_selection_receipt_batch_test.go diff --git a/internal/reviewexec/requests.go b/internal/reviewexec/requests.go index 7a0ce89eb..bf50e2770 100644 --- a/internal/reviewexec/requests.go +++ b/internal/reviewexec/requests.go @@ -285,13 +285,21 @@ func readOperationIdentity(ctx context.Context, tx EvidenceQuery, project, id st if err != nil { return o, err } - err = tx.QueryRowContext(ctx, `SELECT id,project_id,actor_id,worker_id,configuration_revision,policy_revision,capability_fingerprint,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,`+orderColumn+`,`+limitColumn+` FROM review_operations WHERE project_id=? AND id=?`, project, id).Scan(operationValue(&o.ID), operationValue(&o.ProjectID), operationValue(&o.ActorID), operationValue(&o.WorkerID), operationValue(&o.ConfigurationRevision), operationValue(&o.PolicyRevision), operationValue(&o.CapabilityFingerprint), operationValue(&o.PullNumber), operationValue(&o.Channel), operationValue(&o.HeadSHA), operationValue(&o.State), operationValue(&o.Revision), operationValue(&o.Reason), operationValue(&o.AttemptID), operationValue(&o.CreatedAt), operationValue(&o.UpdatedAt), operationValue(&o.AllowOutOfOrder), operationValue(&o.OverrideFileLimit)) + o, err = scanOperationIdentity(tx.QueryRowContext(ctx, `SELECT `+operationIdentityColumns+orderColumn+`,`+limitColumn+` FROM review_operations WHERE project_id=? AND id=?`, project, id)) if errors.Is(err, sql.ErrNoRows) { return o, core.Fail("not_found", "The review operation is unavailable in this project.", 404) } return o, err } +const operationIdentityColumns = `id,project_id,actor_id,worker_id,configuration_revision,policy_revision,capability_fingerprint,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,` + +func scanOperationIdentity(row interface{ Scan(...any) error }) (Operation, error) { + var o Operation + err := row.Scan(operationValue(&o.ID), operationValue(&o.ProjectID), operationValue(&o.ActorID), operationValue(&o.WorkerID), operationValue(&o.ConfigurationRevision), operationValue(&o.PolicyRevision), operationValue(&o.CapabilityFingerprint), operationValue(&o.PullNumber), operationValue(&o.Channel), operationValue(&o.HeadSHA), operationValue(&o.State), operationValue(&o.Revision), operationValue(&o.Reason), operationValue(&o.AttemptID), operationValue(&o.CreatedAt), operationValue(&o.UpdatedAt), operationValue(&o.AllowOutOfOrder), operationValue(&o.OverrideFileLimit)) + return o, err +} + // Older retained snapshots supply false only for flags introduced after their // declared version. Missing or malformed current columns fail the operation read. func operationFlagColumns(ctx context.Context, q EvidenceQuery) (string, string, error) { diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go index d214ab565..fb41e5906 100644 --- a/internal/reviewexec/run_selection_origin.go +++ b/internal/reviewexec/run_selection_origin.go @@ -190,12 +190,7 @@ func hasDirectOperationReceipt(ctx context.Context, q EvidenceQuery, o Operation if err := q.QueryRowContext(ctx, `SELECT configuration_revision FROM review_operations WHERE project_id=? AND id=?`, o.ProjectID, o.ID).Scan(operationValue(&acceptedRevision)); err != nil { return false, err } - fp, err := core.MutationRequestFingerprint(Request{ - ExpectedConfigurationRevision: acceptedRevision, - PullNumber: o.PullNumber, - Channel: o.Channel, - HeadSHA: o.HeadSHA, - }, o.WorkerID) + fp, err := directOperationReceiptFingerprint(o, acceptedRevision) if err != nil { return false, err } @@ -208,6 +203,15 @@ func hasDirectOperationReceipt(ctx context.Context, q EvidenceQuery, o Operation return direct, err } +func directOperationReceiptFingerprint(o Operation, acceptedRevision int64) (string, error) { + return core.MutationRequestFingerprint(Request{ + ExpectedConfigurationRevision: acceptedRevision, + PullNumber: o.PullNumber, + Channel: o.Channel, + HeadSHA: o.HeadSHA, + }, o.WorkerID) +} + func directOperationConflictsWithSelectionCustody(ctx context.Context, q EvidenceQuery, project, operation string) (bool, error) { o, err := readOperationIdentity(ctx, q, project, operation) if err != nil { diff --git a/internal/reviewexec/run_selection_receipt_batch.go b/internal/reviewexec/run_selection_receipt_batch.go new file mode 100644 index 000000000..90d57d71f --- /dev/null +++ b/internal/reviewexec/run_selection_receipt_batch.go @@ -0,0 +1,94 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "strings" +) + +const selectionCustodyReceiptPageSize = 64 + +// All pages and matching receipts must be read in the caller's transaction. +// A receipt is negative custody evidence only, never permission to admit work. +func projectCustodyConflictsWithDirectReceipt(ctx context.Context, tx *sql.Tx, project string) (bool, error) { + const candidates = `SELECT d.original_operation_id FROM review_selection_quarantine d + JOIN review_selections s ON s.id=d.selection_id AND s.project_id=d.project_id + JOIN review_operations o ON o.id=d.original_operation_id AND o.project_id=d.project_id + WHERE d.project_id=? AND s.reason='linked_selection_quarantined' AND d.original_operation_id>? + ORDER BY d.original_operation_id LIMIT ?` + var first string + if err := tx.QueryRowContext(ctx, candidates, project, "", 1).Scan(&first); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + return false, err + } + order, limit, err := operationFlagColumns(ctx, tx) + if err != nil { + return false, err + } + var origins string + after := "" + for { + rows, err := tx.QueryContext(ctx, `SELECT `+operationIdentityColumns+order+`,`+limit+ + ` FROM review_operations WHERE project_id=? AND id IN (`+candidates+`) ORDER BY id`, + project, project, after, selectionCustodyReceiptPageSize) + if err != nil { + return false, err + } + batch := make([]Operation, 0, selectionCustodyReceiptPageSize) + var decodeErr error + for rows.Next() { + var o Operation + o, decodeErr = scanOperationIdentity(rows) + if decodeErr != nil { + break + } + batch = append(batch, o) + } + rowErr := errors.Join(rows.Err(), rows.Close()) + if len(batch) > 0 { + if origins == "" { + origins, err = operationReceiptOrigins(ctx, tx) + if err != nil { + return false, err + } + } + if conflict, err := matchesDirectCustodyReceiptPage(ctx, tx, project, origins, batch); err != nil || conflict { + return conflict, err + } + } + if err := errors.Join(decodeErr, rowErr); err != nil { + return false, err + } + if len(batch) < selectionCustodyReceiptPageSize { + return false, nil + } + after = batch[len(batch)-1].ID + } +} + +// The bounded tuple join retains the exact actor, accepted input fingerprint +// and canonical queued receipt from the single-operation check. +func matchesDirectCustodyReceiptPage(ctx context.Context, tx *sql.Tx, project, origins string, batch []Operation) (bool, error) { + if len(batch) == 0 { + return false, nil + } + args := make([]any, 0, 1+3*len(batch)) + for _, o := range batch { + fingerprint, err := directOperationReceiptFingerprint(o, o.ConfigurationRevision) + if err != nil { + return false, err + } + args = append(args, o.ActorID, fingerprint, encoded(Receipt{ID: o.ID, State: "queued", Revision: 1})) + } + args = append(args, project) + var conflict bool + err := tx.QueryRowContext(ctx, `WITH wanted(actor_id,fingerprint,response_json) AS (VALUES (?,?,?)`+ + strings.Repeat(",(?,?,?)", len(batch)-1)+`) + SELECT EXISTS(SELECT 1 FROM receipts r JOIN wanted w ON + r.principal_id=w.actor_id AND r.fingerprint=w.fingerprint AND r.response_json=w.response_json + WHERE r.instance_id IN (`+origins+`) AND r.project_id=? AND r.operation='reviews.request' AND r.target='requests')`, args...).Scan(&conflict) + return conflict, err +} diff --git a/internal/reviewexec/run_selection_receipt_batch_test.go b/internal/reviewexec/run_selection_receipt_batch_test.go new file mode 100644 index 000000000..0298b952a --- /dev/null +++ b/internal/reviewexec/run_selection_receipt_batch_test.go @@ -0,0 +1,63 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" +) + +func TestSelectionCustodyReceiptBatchMatchesDirectCheck(t *testing.T) { + f := selectionFixture(t) + selected, _ := selectionEnqueue(t, f, "selection-for-receipt-batch", "hosted", nil) + selectionNext(t, f, &refreshTestReader{}) + childID := selectionRead(t, f, selected.ID).OperationID + direct := f.enqueue(t, attemptProject, "direct-for-receipt-batch", "cli", 4, 1) + scope := f.scope(t, attemptProject, f.writer, false) + err := f.store.Read(t.Context(), scope, func(ctx context.Context, tx *sql.Tx) error { + child, err := readOperationIdentity(ctx, tx, attemptProject, childID) + if err != nil { + return err + } + independent, err := readOperationIdentity(ctx, tx, attemptProject, direct.ID) + if err != nil { + return err + } + origins, err := operationReceiptOrigins(ctx, tx) + if err != nil { + return err + } + batch := make([]Operation, selectionCustodyReceiptPageSize) + for i := range batch { + batch[i] = child + } + for _, test := range []struct { + name string + last Operation + want bool + }{ + {"selection child", child, false}, + {"independent request at page tail", independent, true}, + } { + batch[len(batch)-1] = test.last + single, err := directOperationConflictsWithSelectionCustody(ctx, tx, attemptProject, test.last.ID) + if err != nil { + return err + } + got, err := matchesDirectCustodyReceiptPage(ctx, tx, attemptProject, origins, batch) + if err != nil { + return err + } + if got != test.want || got != single { + t.Errorf("%s: batched=%t, single=%t, want=%t", test.name, got, single, test.want) + } + } + got, err := projectCustodyConflictsWithDirectReceipt(ctx, tx, attemptProject) + if got { + t.Errorf("project had no detached candidates") + } + return err + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/reviewexec/run_selection_schema.go b/internal/reviewexec/run_selection_schema.go index 39e3b1053..f888d0cf1 100644 --- a/internal/reviewexec/run_selection_schema.go +++ b/internal/reviewexec/run_selection_schema.go @@ -93,34 +93,43 @@ func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, pro if !unproved { // A structurally attributable diagnostic still cannot prove a child // when its receipt says the operation was accepted independently. - rows, err := q.QueryContext(ctx, `SELECT d.original_operation_id FROM review_selection_quarantine d - JOIN review_selections s ON s.id=d.selection_id AND s.project_id=d.project_id - JOIN review_operations o ON o.id=d.original_operation_id AND o.project_id=d.project_id - WHERE d.project_id=? AND s.reason='linked_selection_quarantined'`, project) - if err != nil { - return err - } - defer rows.Close() - for rows.Next() { - var link string - if err := rows.Scan(&link); err != nil { - return err - } - direct, err := directOperationConflictsWithSelectionCustody(ctx, q, project, link) + if tx, ok := q.(*sql.Tx); ok { + unproved, err = projectCustodyConflictsWithDirectReceipt(ctx, tx, project) if isRetainedOperationDecodeError(err) { unproved = true - break + } else if err != nil { + return err } + } else { + rows, err := q.QueryContext(ctx, `SELECT d.original_operation_id FROM review_selection_quarantine d + JOIN review_selections s ON s.id=d.selection_id AND s.project_id=d.project_id + JOIN review_operations o ON o.id=d.original_operation_id AND o.project_id=d.project_id + WHERE d.project_id=? AND s.reason='linked_selection_quarantined'`, project) if err != nil { return err } - if direct { - unproved = true - break + defer rows.Close() + for rows.Next() { + var link string + if err := rows.Scan(&link); err != nil { + return err + } + direct, err := directOperationConflictsWithSelectionCustody(ctx, q, project, link) + if isRetainedOperationDecodeError(err) { + unproved = true + break + } + if err != nil { + return err + } + if direct { + unproved = true + break + } + } + if err := rows.Err(); err != nil { + return err } - } - if err := rows.Err(); err != nil { - return err } } if unproved {