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-execution.md b/docs/review-execution.md index 3091d65d3..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. 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/docs/review-scheduling.md b/docs/review-scheduling.md new file mode 100644 index 000000000..0482ea3e8 --- /dev/null +++ b/docs/review-scheduling.md @@ -0,0 +1,33 @@ +# 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. + +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. + +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 + +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. + +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. 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/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..9ad91d477 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_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"}, + "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,23 @@ 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 + } + } 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 { @@ -626,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 { @@ -688,6 +715,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 +1105,26 @@ 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','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 { + 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 +1331,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 +1713,59 @@ 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 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() + 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/restore.go b/internal/backup/restore.go index ce5d2af9d..2f83ba97f 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 historicalResumeRestoreError{public: invalid(), cause: err} + } + return historicalResumeRestoreError{public: unavailable(), cause: err} + } if err = tx.Commit(); err != nil { return unavailable() } @@ -317,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/review_selection_test.go b/internal/backup/review_selection_test.go index e40284af6..fb81a2582 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. -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 { +// 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 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) 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"} { @@ -257,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 { @@ -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,164 @@ 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) +} + +// 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/backup/scheduling_test.go b/internal/backup/scheduling_test.go new file mode 100644 index 000000000..4269f00c8 --- /dev/null +++ b/internal/backup/scheduling_test.go @@ -0,0 +1,211 @@ +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) + 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 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) + 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) { + 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) + 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) + } + 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 { + 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) + } + 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 { + 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() + 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) + } + 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") + } + // 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) { + 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 85e19c693..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 { @@ -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..ba8f3f6f7 --- /dev/null +++ b/internal/core/project_automation.go @@ -0,0 +1,49 @@ +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, automationCredential: credential, instanceID: s.instanceID, admin: true, activeWorkerRequired: true} + if err := s.authorize(ctx, tx, scope, "admin"); 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..6a621a133 100644 --- a/internal/core/types.go +++ b/internal/core/types.go @@ -11,17 +11,19 @@ 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 + automationCredential 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..84a25474a 100644 --- a/internal/reviewexec/adoption_holds_integration_test.go +++ b/internal/reviewexec/adoption_holds_integration_test.go @@ -631,12 +631,46 @@ 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) + 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 { + t.Fatal("corrupt source starved healthy project", err, other.calls.Load()) } return } @@ -658,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 { @@ -669,3 +706,42 @@ 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) + first := f.enqueue(t, attemptProject, "first-corrupt", channel, 2, 1) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + 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 { + 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..f86d6a1c6 100644 --- a/internal/reviewexec/allowance_observation.go +++ b/internal/reviewexec/allowance_observation.go @@ -27,6 +27,8 @@ const ( storedReviewAdmission storedConfigurationHistory storedOperationIdentity + storedRoundHistory + storedPolicyHistory ) type storedUnavailableError struct { @@ -78,7 +80,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 +109,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 +128,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 +309,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/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/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..f30015bfa 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 @@ -159,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 } @@ -220,11 +243,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 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 { @@ -240,6 +272,27 @@ 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 { + // 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} + } + var schedulingHistory *schedulingHistoryUnavailable + if settlePreparedCLI && o.Channel == "cli" && intent == "" && !schedulingRefused(err) && errors.As(err, &schedulingHistory) { + settlement = &preparedCLISettlement{operation: o, attempt: a, anchor: anchor, refusal: err, kind: preparedCLIRefusalScheduling} + result, err = e.recordPreparedCLISettlement(ctx, tx, settlement) + } + return err + } if err := requireSourceObligationsClear(ctx, tx, project, o.PullNumber); err != nil { return err } @@ -271,6 +324,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) { + settlement = &preparedCLISettlement{operation: o, attempt: a, anchor: anchor, refusal: err, kind: preparedCLIRefusalPolicy} + result, err = e.recordPreparedCLISettlement(ctx, tx, settlement) + } return err } if reason != "" { @@ -313,10 +370,331 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision }) if err == nil { e.notifyOperation(result.OperationID) + } 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 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 { + 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} } 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 + } + unused, err := untouchedCLIReservation(ctx, tx, o, a, anchor.RepositoryID) + if err != nil { + return Attempt{}, err + } + if !unused { + return Attempt{}, refusal + } + 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 +} + +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. +type unusedCLISettlementAck struct { + attempt Attempt + sequence int64 +} + +func (e *Engine) settleUnusedCLIPreparation(ctx context.Context, original Operation, captured Attempt) error { + return e.settleUnusedCLIPreparationWithAck(ctx, original, captured, &unusedCLISettlementAck{}) +} + +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, reason) + if err != nil { + return err + } + if committed { + e.notifyOperation(captured.OperationID) + return nil + } + *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 { + 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 + } + candidate, err := e.advanceAttempt(ctx, tx, o, a, "held", reason, "") + 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 + } + var receiptSequence int64 + if err := tx.QueryRowContext(ctx, `SELECT last_insert_rowid()`).Scan(&receiptSequence); err != nil { + return err + } + if receiptSequence <= 0 { + return conflict() + } + *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 && 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) + 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 + } + } + if err == nil { + e.notifyOperation(captured.OperationID) + } + 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 { + 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, reason) + 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, 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() + } + tx, err := e.store.DB().BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + 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 { + return false, err + } + 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 + (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=? 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, reason, a.ID, a.ID, a.ID).Scan(&exact) + if err != nil { + return false, err + } + if !exact { + return false, conflict() + } + return true, nil +} + +// 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 || !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, expectedRevision) { + 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 && + 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 @@ -359,49 +737,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 - if o.Channel == "cli" && reason == cliDraftWait && 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) @@ -409,6 +746,62 @@ 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) { + 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 + } + 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 + 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 == "" { + 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/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/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..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{}, adjudicationStorageError() + return ComparisonState{}, &dirtyComparisonProofError{&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..3eb01dcc9 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,28 @@ 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 { + 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 reason != cliDraftWait { + 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 } - 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 +259,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/cli_draft_wait_test.go b/internal/reviewexec/cli_draft_wait_test.go index 3d1459add..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() @@ -768,14 +769,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 +789,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 +809,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) } diff --git a/internal/reviewexec/cli_pause_no_start.go b/internal/reviewexec/cli_pause_no_start.go new file mode 100644 index 000000000..9fb9fdde5 --- /dev/null +++ b/internal/reviewexec/cli_pause_no_start.go @@ -0,0 +1,321 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "strconv" + "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() + } + var receipt int64 + err := settleOwnedCLIWithinWindows(ctx, func(local context.Context) error { + if receipt != 0 { + committed, err := e.probeCLIPauseSettlement(local, w, 0) + if err != nil || committed { + return err + } + receipt = 0 + } + 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) { + 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 + } + 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, sequence) + if err != nil || !committed { + return false, err + } + 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, 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,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() + } + 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() + } + 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 +} + +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/cli_policy_settlement_test.go b/internal/reviewexec/cli_policy_settlement_test.go new file mode 100644 index 000000000..d89277b70 --- /dev/null +++ b/internal/reviewexec/cli_policy_settlement_test.go @@ -0,0 +1,165 @@ +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 + 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 + } + 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) + } + 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) + } + 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" || + 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) + }) + } +} + +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) + refused := newStoredUnavailable(storedPolicyHistory, "Policy history was not available before retry.") + pending := &preparedCLISettlement{operation: o, attempt: a, anchor: input.Anchor, refusal: refused, kind: preparedCLIRefusalPolicy} + 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) + } + 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) { + 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 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") + } + 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_preflight.go b/internal/reviewexec/cli_preflight.go index c6479b2b4..c8131fd50 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] @@ -183,6 +210,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 } @@ -230,19 +261,34 @@ 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() } - 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/cli_preflight_test.go b/internal/reviewexec/cli_preflight_test.go index 2d6269fa2..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" @@ -226,7 +227,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"}, @@ -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/reviewexec/cli_prepared_settlement.go b/internal/reviewexec/cli_prepared_settlement.go new file mode 100644 index 000000000..1108d280f --- /dev/null +++ b/internal/reviewexec/cli_prepared_settlement.go @@ -0,0 +1,187 @@ +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" + preparedCLIRefusalPublish = "publish" + recordedCLIPublishSettlementEvent = "review.cli_recorded_publish_settlement" +) + +// Kept only by the live caller that observed the exact prepared refusal. +type preparedCLISettlement struct { + operation Operation + attempt Attempt + anchor Anchor + positive *CLIAllowanceObservation + 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 (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 { + 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, p.eventType(), 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() + } + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + return err + } + 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 schedulingRefused(err) { + return p.refusal + } + if err != nil && !errors.As(err, &history) { + return err + } + case preparedCLIRefusalPolicy: + _, _, err = boundPolicy(ctx, tx, o) + 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() + } + // 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 + }) + }) + 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 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}) + if err != nil { + return false, err + } + 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, p.eventType(), o.ActorID, p.result.Revision, record, 0) + if err != nil || !committed { + return false, err + } + var exact bool + 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 || + p.kind == preparedCLIRefusalPublish && (p.positive == nil || preflight.Observation != *p.positive) { + 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/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/front_evaluator.go b/internal/reviewexec/front_evaluator.go index 329342623..8154d73fa 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) { @@ -73,9 +74,33 @@ 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 { + 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, localRefusal: err}, nil + } + return evaluatedFront{}, err + } + 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 { + 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 { + return evaluatedFront{state: "held", reason: "automatic_intent_retained", plan: plan}, nil + } return evaluatedFront{state: "ready", plan: plan}, nil } @@ -144,7 +169,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 @@ -155,6 +180,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/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_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/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 4d893ccc7..5a7474d09 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 { @@ -92,7 +99,24 @@ 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 == "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 { @@ -117,6 +141,13 @@ 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 + var selection *retainedSelectionStateError + if errors.As(err, &binding) || errors.As(err, &selection) { + 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/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..daea27e6a 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,20 @@ 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') - ORDER BY 2`, cliDraftWait, cliDraftWait) + 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='') + ) + 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 } @@ -76,7 +91,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 +110,27 @@ 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 { + 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 } if !hasBaseline { @@ -173,7 +200,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/operation_direct_receipt_test.go b/internal/reviewexec/operation_direct_receipt_test.go new file mode 100644 index 000000000..aae444b82 --- /dev/null +++ b/internal/reviewexec/operation_direct_receipt_test.go @@ -0,0 +1,112 @@ +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) + } + }) + } +} + +// 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})) +} + +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/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/policy.go b/internal/reviewexec/policy.go index 7bdf8cce1..8e9995779 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{}, &automaticProjectStateError{newStoredUnavailable(storedPolicyHistory, "Stored project review policy is unavailable.")} } return record, nil } diff --git a/internal/reviewexec/policy_admission.go b/internal/reviewexec/policy_admission.go index 5424631f2..725f01a9d 100644 --- a/internal/reviewexec/policy_admission.go +++ b/internal/reviewexec/policy_admission.go @@ -49,10 +49,19 @@ 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 { + 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 + } if err := requireSourceObligationsClear(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil { return ExecutionContext{}, err } diff --git a/internal/reviewexec/queued_diagnostic.go b/internal/reviewexec/queued_diagnostic.go index 55a9a87e6..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" { @@ -60,6 +77,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 +108,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 @@ -198,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/requests.go b/internal/reviewexec/requests.go index dcb4ab352..bf50e2770 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 @@ -282,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/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/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..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,6 +169,7 @@ func (e *Engine) enqueueRunHTTP(w http.ResponseWriter, r *http.Request) { return } if terminal { + e.queuedRunResponseHeader(w, r, scope, state, responseDeadline) core.WriteJSON(w, http.StatusOK, runStateForResponse(state, r.Header.Get(operationWaitHeader))) return } @@ -196,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 } @@ -206,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) diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 4a073bd10..11d5353a2 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) @@ -60,17 +61,26 @@ 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 := 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{}, &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) @@ -85,7 +95,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 @@ -114,6 +124,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 +137,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 +195,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 @@ -220,9 +241,39 @@ func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configurati return c, 0, "repository_changed", nil } var busy bool - 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 { + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations o + WHERE o.project_id=? AND o.channel=? AND o.state IN ('queued','preparing','posting','active','uncertain') + AND NOT (o.channel='hosted' AND 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)))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { + return c, 0, "", err + } + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil { return c, 0, "", err } + 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 + } + if busy && !unproved { + busy, err = e.explicitHostedLaneBusy(ctx, tx, r.ProjectID) + if err != nil { + return c, 0, "", err + } + } + busy = busy || unproved + } if busy { return c, repository, "review_inflight", nil } @@ -263,15 +314,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 +340,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 +478,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 +521,202 @@ 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) + 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 { + _, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + var invalid *pullSchedulingStateError + if errors.As(err, &invalid) { + return true, nil + } + return false, err + } + } + 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` + +// 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 + } + 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} + 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()} + } + 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. + 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 + (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_origin.go b/internal/reviewexec/run_selection_origin.go new file mode 100644 index 000000000..fb41e5906 --- /dev/null +++ b/internal/reviewexec/run_selection_origin.go @@ -0,0 +1,281 @@ +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,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 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 + } + defer rows.Close() + if !rows.Next() { + return selectionRequestedEvent{}, rows.Err() + } + var actor any + var sequence int64 + var eventType string + var body sql.NullString + if err = rows.Scan(&sequence, &actor, &eventType, &body); err != nil { + return selectionRequestedEvent{}, err + } + var event selectionRequestedEvent + 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 { + 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 + } + 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 + } + hasAttribution := err == nil + if hasAttribution && event.sequence == 0 { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + 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) { + origins, err := operationReceiptOrigins(ctx, q) + if err != nil { + return false, err + } + 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 +} + +// 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 + } + // 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 := directOperationReceiptFingerprint(o, acceptedRevision) + 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 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 { + 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) { + 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,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' 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 + } + defer rows.Close() + var expected int64 = 1 + for rows.Next() { + var sequence int64 + var revision any + var eventType string + var body sql.NullString + if err := rows.Scan(&sequence, &revision, &eventType, &body); err != nil { + return false, err + } + control, _, _, valid := readSchedulingEventPayload(body, expected) + if revision != expected || eventType != "text" || !valid { + 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_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 a96fef207..f888d0cf1 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,146 @@ 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" + +// 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 } + +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 + 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)` + +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) + `+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 + // 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 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. + if tx, ok := q.(*sql.Tx); ok { + unproved, err = projectCustodyConflictsWithDirectReceipt(ctx, tx, project) + if isRetainedOperationDecodeError(err) { + unproved = true + } 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 + } + 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 unproved { + return automaticProjectStateFailure(linkedSelectionCustodyHeld, "A review operation is held for selection custody recovery in this project.", 403) + } + return nil + } + if err != nil { + return err + } + if !proved { + // An unknown custody row cannot establish ordinary ineligibility. + 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 + } + if direct { + 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) +} + +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..deca6660e 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,25 @@ func ValidateSelectionSnapshot(ctx context.Context, q EvidenceQuery) error { if err != nil { return err } + + event, err := readSelectionRequestedEvent(ctx, q, r) + if err != nil { + return err + } + attributed := false + if hasScheduling { + _, err := readAutomaticSelectionAttribution(ctx, q, r) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + attributed = err == nil + } + // A legacy empty-origin event may still have a real acceptance sequence. + if event.sequence == 0 && (attributed || r.ExpectedPullNumber != 0) || + event.Origin != "" && (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 +182,124 @@ 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() + } + // 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`) + 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() + } + direct, err := directOperationConflictsWithSelectionCustody(ctx, q, reportedProject, link) + if err != nil { + return err + } + if direct { + 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_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 593d0947b..7152b6b68 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,19 @@ 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 + sourcePrefixComplete bool + number int64 + head string + automaticQueueLimit *int + automaticGrantBlocked bool + claimAutomaticQueueLimit *int + automaticBasisRevision int64 + automaticPullScheduling []int64 + automaticGrantRevisions []int64 + automaticRouteSequence int64 } // retryRunSelectionLocal retains completed source reads while only retrying @@ -179,7 +189,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) @@ -211,18 +221,156 @@ 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 i, pull := range pulls { + current, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + var local *pullSchedulingStateError + 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) + continue + } + revisions = append(revisions, current.Revision) + } + return revisions, nil +} + +// 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 { + revision, readable, err := automaticGrantRevision(ctx, tx, project, channel, pull) + if err != nil { + return nil, err + } + if !readable { + return nil, schedulingUnavailable() + } + revisions = append(revisions, revision) + } + 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. +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) } -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 grantBlocked bool + + var basisRevision, routeSequence int64 + var pullScheduling, grantRevisions []int64 + defer func() { + result.automaticQueueLimit = automaticQueueLimit + result.automaticGrantBlocked = grantBlocked + result.automaticBasisRevision = basisRevision + 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. + 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 + grantBlocked = false + 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 { + return err + } + automatic = attribution.revision != 0 + if !automatic { + return nil + } + limit, grantBlocked, err = e.automaticQueuedPrefixBounds(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) + if err != nil { + 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]) + if err != nil { + return err + } + routeSequence, err = automaticRouteSequence(ctx, tx, r.ProjectID) + 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 +392,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 +400,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 +414,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 { @@ -284,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 @@ -310,7 +467,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 }) }) @@ -388,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(): @@ -398,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 @@ -413,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) } } @@ -429,38 +588,104 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR }() return done, nil } + +type runCandidateCursor struct { + createdAt any + id any + throughSequence int64 + hasHorizon bool +} + func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) (bool, error) { + 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) + if !selectionCustodyUnproved(err) { + return worked, err + } + // Keep the refused linked row intact. The query advances strictly beyond + // this row for this scan; unrelated rows must not lose their workers. + if ctx.Err() != nil { + return false, ctx.Err() + } + } +} + +func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]TargetReader, cursor *runCandidateCursor) (bool, error) { 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 + var nativeProject, nativeID, nativeCreatedAt any + var quarantined bool var expected int64 err := retryRunSelectionLocal(ctx, func() error { 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. - 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+`,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) || + (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) error { + return e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) (resultErr error) { current, err := readRun(ctx, tx, r.ProjectID, r.ID) if err != nil { return err @@ -523,6 +832,100 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat if current.State != r.State || current.Revision != r.Revision { return conflict() } + if _, err = tx.ExecContext(ctx, `SAVEPOINT review_selection_finish`); err != nil { + return err + } + bindingValidated := false + zeroPrefixHold := false + var boundPrefix []int64 + defer func() { + if resultErr == nil && bindingValidated { + var pull int64 + var state, reason string + if err := tx.QueryRowContext(ctx, `SELECT COALESCE(o.pull_number,0),s.state,s.reason FROM review_selections s LEFT JOIN review_operations o ON o.id=s.operation_id WHERE s.id=? AND s.project_id=?`, r.ID, r.ProjectID).Scan(&pull, &state, &reason); err != nil { + resultErr = err + return + } + // 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" && + !(state == "held" && globalFrontHold(reason)) + 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 { + 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 { + grants, err := readAutomaticGrantRevisions(ctx, tx, r.ProjectID, r.Channel, boundPrefix) + resultErr = err + settle = err == nil && slices.Equal(grants, choice.automaticGrantRevisions) + } + } + } + // 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 = 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): + // An entry without a pinned projection may be new. + _, pinned := metadataPins[evaluated.Number] + 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. + if settle && !(pull == 0 && choice.sourceReason != "") { + complete := choice.automaticQueueLimit == nil || + (choice.sourcePrefixComplete && len(choice.prefix) == len(boundPrefix)) + resultErr = e.settleAutomaticBasis(ctx, tx, r, pull, complete) + } + } + if automaticProjectRefused(resultErr) { + reason, err := selectionLocalHoldReason(ctx, tx, current) + if err != nil { + resultErr = err + return + } + if reason != "automatic_scheduling_unavailable" { + return // Explicit selections retain their original error and rollback. + } + // Settlement is part of atomic selection. Discard any source, + // child and event writes before retaining a local hold. The + // accepted basis stays intact for tick/restart suppression. + if _, err := tx.ExecContext(ctx, `ROLLBACK TO review_selection_finish`); err != nil { + resultErr = err + return + } + resultErr = updateRun(ctx, tx, current, "held", reason, "") + } + if resultErr == nil { + _, resultErr = tx.ExecContext(ctx, `RELEASE review_selection_finish`) + } + }() c, nowRepo, reason, err := e.runBinding(ctx, tx, current) if err != nil { return err @@ -533,11 +936,74 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat if reason != "" { return updateRun(ctx, tx, current, "held", reason, "") } + bindingValidated = true + if choice.automaticQueueLimit != nil { + // 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, 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", "") + } + 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 + } + 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" && 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) + 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 } - if err = writeFrontFrame(ctx, tx, current, repo, c, choice); err != nil { - return err + 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 + } } 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" { @@ -546,9 +1012,9 @@ 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 + return finishFrontReadError(current, err) } if reason != choice.reason { return updateRun(ctx, tx, current, "held", "selection_changed", "") @@ -556,9 +1022,14 @@ 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, choice.sourcePrefixComplete) if err != nil { - return err + 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 new file mode 100644 index 000000000..eefd7b4d8 --- /dev/null +++ b/internal/reviewexec/scheduling.go @@ -0,0 +1,338 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "math" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/strictjson" +) + +type Scheduling struct { + PausedPulls []PullScheduling `json:"paused_pulls"` + ProjectID string `json:"project_id"` + Revision int64 `json:"revision"` + AutomaticCLI bool `json:"automatic_cli"` + AutomaticHosted bool `json:"automatic_hosted"` + AuthorizingWorkerID string `json:"authorizing_worker_id,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` + Reason string `json:"reason,omitempty"` +} + +type PullScheduling struct { + ProjectID string `json:"project_id"` + PullNumber int64 `json:"pull_number"` + Revision int64 `json:"revision"` + Paused bool `json:"paused"` + Reason string `json:"reason"` + ActorID string `json:"actor_id,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` +} +type PullSchedulingRequest struct { + ExpectedRevision *int64 `json:"expected_revision"` + Paused *bool `json:"paused"` + Reason string `json:"reason,omitempty"` +} +type schedulingRecord struct { + Scheduling + actor, credential string +} + +// Distinguish invalid stored scheduling records from project-local history +// failures without changing public errors or outer project isolation. +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 &automaticProjectStateError{&schedulingHistoryUnavailable{core.Fail("storage_unavailable", "Stored review scheduling is unavailable.", 503)}} +} + +func schedulingRecordUnavailable() error { + return &schedulingStateError{schedulingUnavailable()} +} + +func schedulingRefused(err error) bool { + var scheduling *schedulingStateError + return errors.As(err, &scheduling) +} + +func readScheduling(ctx context.Context, tx *sql.Tx, project string) (s schedulingRecord, err error) { + s.ProjectID = project + var revision, hosted, cli, actor, worker, credential, updated any + err = tx.QueryRowContext(ctx, `SELECT revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at FROM review_scheduling WHERE project_id=?`, project).Scan(&revision, &hosted, &cli, &actor, &worker, &credential, &updated) + if errors.Is(err, sql.ErrNoRows) { + return s, nil + } + if err != nil { + return s, err + } + // Scan into unconverted values so malformed SQLite column types can be + // classified as retained data without disguising an actual database error. + var revisionOK, actorOK, workerOK, credentialOK, updatedOK bool + s.Revision, revisionOK = revision.(int64) + hostedValue, hostedOK := hosted.(int64) + cliValue, cliOK := cli.(int64) + s.actor, actorOK = actor.(string) + s.AuthorizingWorkerID, workerOK = worker.(string) + s.credential, credentialOK = credential.(string) + s.UpdatedAt, updatedOK = updated.(string) + if !revisionOK || !hostedOK || !cliOK || !actorOK || !workerOK || !credentialOK || !updatedOK || hostedValue < 0 || hostedValue > 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"` +} + +// 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. +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,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 + } + defer rows.Close() + count := 0 + for rows.Next() { + count++ + var nativeActor any + var eventType string + var payload sql.NullString + 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 || 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 + } + 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) (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 + 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 = editablePullScheduling(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 := editablePullScheduling(ctx, tx, scope.ProjectID, pull) + if err != nil { + return nil, err + } + if old.Revision != *input.ExpectedRevision || (*input.Paused && old.Revision == math.MaxInt64-1) { + 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_authority.go b/internal/reviewexec/scheduling_authority.go new file mode 100644 index 000000000..9f95f2910 --- /dev/null +++ b/internal/reviewexec/scheduling_authority.go @@ -0,0 +1,123 @@ +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(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,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= ord || seen > 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' 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= 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 + } + if _, _, err := schedulingBasisRevisions(ctx, tx, current); err != nil { + return false, err + } + selectedChild := r.State == "selected" && r.OperationID != "" + if !selectedChild && r.Channel == "hosted" { + generation, err := schedulingAuthorityContinuity(ctx, tx, r.ProjectID, originalActor, revision, current.Revision, false) + if err != nil || generation == 0 { + return false, err + } + } + 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 + } + defer rows.Close() + expected := revision + var acceptedCLIBasis int64 + for rows.Next() { + var retainedRevision any + var storedActor any + var eventType string + var payload sql.NullString + if err = rows.Scan(&retainedRevision, &storedActor, &eventType, &payload); err != nil { + return false, err + } + recorded, validRevision := retainedRevision.(int64) + actor, nativeText := storedActor.(string) + if eventType != "text" || !validRevision || !nativeText || !identifier.MatchString(actor) || recorded != expected || + (!selectedChild || recorded == revision) && actor != originalActor || + recorded == current.Revision && actor != current.actor { + return false, nil + } + 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 + } + 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..976ecc69f --- /dev/null +++ b/internal/reviewexec/scheduling_automatic.go @@ -0,0 +1,813 @@ +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 +} + +// 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 + } + 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 { + return err + } + id, validID := selection.(string) + if project != o.ProjectID || !validID || !validRunID(id) { + 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 &operationSelectionBindingStateError{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 + parentFacts map[int64][]any + frontByNumber map[int64]frontPull +} + +// 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() + if out.hasFrame { + out.parentFacts = make(map[int64][]any) + out.frontByNumber = frontPullIndex(out.frame) + } + 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` +} + +// 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" { + 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 + unavailable := false + 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 { + unavailable = true + continue + } + // 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 + } + if err = rows.Close(); err != nil { + return err + } + if unavailable { + return &automaticPullAdjudicationUnavailable{schedulingUnavailable()} + } + return nil + } +} + +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}}, + } + var unavailable error + for _, q := range queries { + if err := appendRows(q.sql, false, q.args...); err != nil { + var local *automaticPullAdjudicationUnavailable + if !errors.As(err, &local) { + return "", err + } + unavailable = 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, shared.frontByNumber, shared.parentFacts) + if err != nil { + return "", err + } + if unavailable != nil { + return "", unavailable + } + 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, 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, 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 + } + if byNumber == nil { + byNumber = frontPullIndex(frame) + } + 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 + } + // 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 + } + facts, err := read(p) + if err != nil { + return nil, err + } + if parentFacts != nil { + parentFacts[parent] = facts + } + out = append(out, facts) + parent = p.ParentPullNumber + } + 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. +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{} + degraded := false + for _, pull := range queue { + p, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + 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 { + var unreadable *automaticPullAdjudicationUnavailable + 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 row position and observed + // revision without pretending its digest or readiness exists. + values = append(values, []any{pull, nil, p.Revision}) + degraded = true + continue + } + values = append(values, []any{pull, basis}) + 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) + } + } + var digestInput any = []any{values, remaining} + if degraded { + // 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))) + 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 +// 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) { + limit, _, err := e.automaticQueuedPrefixBounds(ctx, tx, project, c, channel) + return limit, err +} + +// Only a readable strictly earlier prefix can establish automatic coverage. +// Keep normal operation ordering; an unreadable grant is an additional boundary. +func (e *Engine) automaticQueuedPrefixBounds(ctx context.Context, tx *sql.Tx, project string, c Configuration, channel string) (int, bool, error) { + limit, err := e.automaticQueuedOperationPrefixChannel(ctx, tx, project, c, channel) + if err != nil { + return 0, false, err + } + if limit < 0 || limit > 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 + } + 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' +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 pull int64 + var selection, selectionProject any + var operation string + var custodyPresent bool + if err := rows.Scan(&position, &pull, &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 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 { + continue + } + return 0, err + } + return position, nil + } + id, validID := selection.(string) + 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 + var selectionState *retainedSelectionStateError + if errors.As(err, &bindingState) || errors.As(err, &selectionState) { + continue + } + 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" { + // Only the cross-PR fence changes. The immutable bound + // child is still pending for duplicate suppression. + continue + } + 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 { + 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, complete bool) error { + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil || attribution.revision == 0 { + return err + } + if !complete && pull == 0 { + return nil + } + pullBasis := "" + if pull > 0 { + pullBasis, err = automaticPullBasisChannel(ctx, tx, r.ProjectID, pull, r.Channel) + if err != nil { + 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_boundary_compatibility_test.go b/internal/reviewexec/scheduling_boundary_compatibility_test.go new file mode 100644 index 000000000..b3d86d1eb --- /dev/null +++ b/internal/reviewexec/scheduling_boundary_compatibility_test.go @@ -0,0 +1,154 @@ +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 + newGeneration bool + }{ + {"unchanged-owner", "test-actor", false, true, false}, + {"new-selection-requires-continuity", "alternate-authorizer", false, false, true}, + {"retained-child-keeps-continuity-rule", "alternate-authorizer", true, true, true}, + {"same-actor-new-generation-pending", "test-actor", false, false, true}, + {"same-actor-new-generation-selected", "test-actor", true, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + 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.newGeneration { + 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 err := validateSchedulingAuthoritySnapshot(t.Context(), tx); err != nil { + t.Fatal("canonical scheduling events and witnesses did not qualify", err) + } + if !tc.newGeneration { + 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"} + 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"} + 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) + } + 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) + 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) + } +} + +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) + } + }) + } +} + +func TestOrdinaryQueuedHostedLeavesEarlierPrefixReadable(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4}) + f.enqueue(t, attemptProject, "ordinary-later-hosted", "hosted", 4, 1) + cfg := Configuration{Queue: []int64{2, 4}} + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + unknown, err := unprovedQueuedHostedPause(ctx, tx, attemptProject) + if err != nil || unknown { + t.Fatalf("ordinary queued Hosted request did not have readable pause state: %v %v", unknown, err) + } + prefix, blocked, err := f.e.automaticQueuedPrefixBounds(ctx, tx, attemptProject, cfg, "hosted") + if err != nil || blocked || prefix != 1 { + t.Fatalf("ordinary later request blocked earlier work or did not bound it: %d %v %v", prefix, blocked, err) + } + return nil + }); err != nil { + t.Fatal(err) + } +} 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_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_selected_basis_guard_test.go b/internal/reviewexec/scheduling_selected_basis_guard_test.go new file mode 100644 index 000000000..1307e4165 --- /dev/null +++ b/internal/reviewexec/scheduling_selected_basis_guard_test.go @@ -0,0 +1,136 @@ +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 _, 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") + 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 + } + if err := core.AppendEvent(ctx, tx, scope, schedulingAuthorityBoundEvent, scope.ProjectID, 1, schedulingAuthorityPayload{Generation: 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) + } + 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 { + return err + } + if err := 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}); err != nil { + return err + } + return core.AppendEvent(ctx, tx, scope, schedulingAuthorityBoundEvent, scope.ProjectID, 2, schedulingAuthorityPayload{Generation: 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 || (!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 + 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 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") + } + 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 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") + } + 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 new file mode 100644 index 000000000..0d8d40af5 --- /dev/null +++ b/internal/reviewexec/scheduling_snapshot.go @@ -0,0 +1,521 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "math" + "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. 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, `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 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 + } + if ahead { + return schedulingUnavailable() + } + if err = validateRetainedSchedulingSettingsPayloads(ctx, tx); err != nil { + return err + } + if err = validateSchedulingAuthoritySnapshot(ctx, tx); err != nil { + return err + } + + 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 || s.Paused && s.Revision == math.MaxInt64 || !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' 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 + } + 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) || settled == "") || !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() +} + +// 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. +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_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 IN ('review.pull_scheduling_updated',CAST('review.pull_scheduling_updated' AS BLOB)) + AND s.pull_number IS NULL` + +const orphanPullSchedulingRankSQL = ` + ), 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 + WHERE o.newest=1` + +const orphanPullSchedulingSelectSQL = ` + SELECT CASE WHEN typeof(o.project_id)='text' THEN o.project_id END,o.resource_id, + 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 + +// Validate the entire orphan history before selecting its latest resume. +// 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,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 + } + defer rows.Close() + for rows.Next() { + var at, payload sql.NullString + 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() + } + } + if err := rows.Err(); err != nil { + return err + } + return rows.Close() +} + +func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { + if err := validateOrphanPullSchedulingHistory(ctx, tx, ""); err != nil { + return err + } + rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+orphanPullSchedulingRankSQL+orphanPullSchedulingSelectSQL) + 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 { + _, err := scanOrphanPullResume(row) + return err +} + +func scanOrphanPullResume(row interface{ Scan(...any) error }) (PullScheduling, 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 PullScheduling{}, err + } + resource, ok := storedResource.(string) + if !ok || len(resource) > 10 { + 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 PullScheduling{}, schedulingUnavailable() + } + return PullScheduling{ProjectID: project.String, PullNumber: pull, Revision: nativeRevision, ActorID: actor.String, UpdatedAt: createdAt.String}, nil +} + +// 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 := 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 + } + 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 || 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 +} + +// 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+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 +} + +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"` + 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 = `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 + 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 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 + ORDER BY project_id,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 string + var pull, controlRevision, paused int64 + var nativeRevision, nativeEventActor any + 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 !textActor || !integer || !createdAt.Valid || !roundTime(createdAt.String) || !pullSchedulingPayloadMatchesPull(payload, pull) { + return schedulingUnavailable() + } + if revision < controlRevision { + continue + } + if (project == lastProject && pull == lastPull) || 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_snapshot_event_integrity_test.go b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go new file mode 100644 index 000000000..d400fddf2 --- /dev/null +++ b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go @@ -0,0 +1,246 @@ +package reviewexec + +import ( + "context" + "database/sql" + "slices" + "strings" + "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) + 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',?)`, at); 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) + 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',?)`, 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,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 { + 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) + } +} + +// 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") +} + +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_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_retry.go b/internal/reviewexec/scheduling_source_retry.go new file mode 100644 index 000000000..bef048328 --- /dev/null +++ b/internal/reviewexec/scheduling_source_retry.go @@ -0,0 +1,178 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "time" +) + +// 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 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 + } + 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 || accepted > current.Revision { + return "automation_authorization_changed", nil + } + initial, err := automaticSourceInitialRead(ctx, tx, r) + if err != nil { + return "", err + } + if initial { + proved, err := verifiedInitialAutomaticSourceAcceptance(ctx, tx, r) + if err != nil { + return "", err + } + if !proved { + return "selection_superseded", nil + } + } else if accepted != current.Revision { + 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 { + return "", err + } + if superseded { + return "selection_superseded", nil + } + 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 +// 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 ( + 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(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 + 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 { + 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. + // 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 + // moves backwards. Missing acceptance evidence is not permission to retry. + 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<>? + 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 (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 + 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=? + 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 typeof(accept.sequence)='integer' + AND accept.sequence>0 AND accept.sequence'' 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 +407,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 +415,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) || pendingSelectionCustodyRefused(o, 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 +468,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 +675,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 +816,18 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr return e.processPendingBatch(ctx, drivers, releaseProbe, worker, operations, receipt) } +// 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) || isStoredUnavailable(err, storedRoundHistory) { + return true, e.finishPreparation(a, "held", "automatic_scheduling_unavailable") + } + return automaticProjectRefused(err), 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 +844,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) || pendingSelectionCustodyRefused(o, err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { continue } var refusal *core.Error @@ -711,7 +866,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) || pendingSelectionCustodyRefused(o, err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { continue } var failure *core.Error @@ -745,13 +900,44 @@ 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) { + 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 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 { + 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 + } + continue + } + if handled, settleErr := e.classifyUnavailablePreparation(ctx, o, a, err); handled { + if settleErr != nil { + return settleErr + } + continue + } } state := "held" reason := preparationReason(err) @@ -782,17 +968,40 @@ 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") } - // 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" { @@ -804,6 +1013,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 { @@ -829,6 +1041,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/supervisor_test.go b/internal/reviewexec/supervisor_test.go index 13dbe9700..d5cb863ba 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. @@ -86,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 { @@ -205,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() } @@ -1515,3 +1522,40 @@ func TestSupervisorCLICooldownDatabaseFailureRemainsFatal(t *testing.T) { t.Fatal("database failure became a hold or lost guarded preparation") } } + +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) { + 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) + } +} diff --git a/internal/reviewexec/wait_deadline.go b/internal/reviewexec/wait_deadline.go index 72d23e361..597eb1480 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 @@ -150,10 +150,17 @@ 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() } - 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 +180,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() } diff --git a/internal/reviewprocess/process.go b/internal/reviewprocess/process.go index b879f0dd4..f2f07322c 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,14 +172,33 @@ 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, usage Usage) bool { + r.mu.Lock() + defer r.mu.Unlock() + if r.permit == nil || r.permit != usage.permit || 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. 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) } @@ -203,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 66dda5d80..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") @@ -709,3 +734,24 @@ func TestZeroUsageRejectsWorkspaceChangedByCommand(t *testing.T) { t.Fatalf("changed workspace authorized review: %v", err) } } + +func TestRetireUsagePermitOnlyRemovesExactWorkspace(t *testing.T) { + 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" + if r.RetireUsagePermit(f.workspace, original) || r.RetireUsagePermit(other, current) { + t.Fatal("an unrelated allowance or workspace retired the current permit") + } + 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 732c45589..8f8242689 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -27,10 +27,12 @@ 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, 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{} } func (*CLIDriver) String() string { return "CLIDriver{private}" } @@ -78,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{}}, 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 @@ -93,33 +95,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 +159,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 +184,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") @@ -177,10 +200,18 @@ 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 + 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.CLIRecordedPreflightHandoff(err, observation, func() bool { + return d.retireUsage != nil && d.retireUsage(workspace, usage) + }, releaseSettlement) + } return preparation, err } d.mu.Lock() @@ -217,11 +248,31 @@ 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) + 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 ba10c8c95..f7f1b11db 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,13 +340,114 @@ 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) { 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 } @@ -584,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" { @@ -809,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"} } @@ -850,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") }