From 8b5b70316c13b22e82f07fb8499c6ce078f07ca9 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 15:11:56 +1300 Subject: [PATCH 01/41] Carry scheduling controls with qualified administration and cancellation repairs --- docs/README.md | 1 + docs/mcp.md | 6 +- docs/review-scheduling.md | 79 + internal/adoptionholds/read.go | 53 +- internal/adoptionholds/read_errors_test.go | 46 +- internal/adoptionholds/retarget.go | 16 +- internal/backup/inventory.go | 57 +- internal/backup/physical_schema_test.go | 56 + internal/backup/review_fronts_test.go | 88 + internal/backup/review_selection_test.go | 49 +- internal/backup/scheduling_test.go | 311 ++++ internal/cli/cli.go | 24 +- internal/cli/operation_help.go | 3 + internal/cli/review_operation_control_test.go | 77 + internal/cli/review_scheduling.go | 107 ++ internal/cli/review_scheduling_help.go | 43 + internal/cli/review_scheduling_test.go | 144 ++ internal/cli/reviews.go | 8 + internal/client/client.go | 5 +- internal/client/review_agent_output.go | 23 + internal/client/review_agent_output_test.go | 3 + internal/client/review_scheduling.go | 184 +++ .../client/review_scheduling_diagnostic.go | 13 + .../review_scheduling_diagnostic_test.go | 105 ++ internal/client/review_scheduling_test.go | 434 +++++ internal/core/project_automation.go | 52 + internal/core/project_automation_test.go | 205 +++ internal/mcpadapter/adapter_test.go | 5 +- internal/mcpadapter/arguments.go | 3 + internal/mcpadapter/review_scheduling.go | 108 ++ .../review_scheduling_arguments_test.go | 53 + internal/mcpadapter/review_scheduling_test.go | 120 ++ internal/mcpadapter/tools.go | 21 +- internal/reviewexec/attempt_projection.go | 2 +- internal/reviewexec/attempts.go | 32 +- internal/reviewexec/carried_obligations.go | 3 + internal/reviewexec/cli_coverage.go | 2 +- internal/reviewexec/cli_draft_wait.go | 17 +- internal/reviewexec/cli_wait_test.go | 108 +- internal/reviewexec/front_evaluator.go | 14 + internal/reviewexec/front_frame.go | 154 ++ internal/reviewexec/front_schema.go | 23 + internal/reviewexec/front_snapshot.go | 110 ++ internal/reviewexec/hosted_priority_test.go | 96 +- internal/reviewexec/hosted_wait.go | 21 +- internal/reviewexec/hosted_wait_validation.go | 3 +- internal/reviewexec/http.go | 41 +- internal/reviewexec/operation_status.go | 6 +- internal/reviewexec/policy.go | 10 +- internal/reviewexec/policy_admission.go | 6 + internal/reviewexec/queued_diagnostic.go | 199 +++ internal/reviewexec/requests.go | 43 +- internal/reviewexec/round_controls.go | 47 +- internal/reviewexec/round_progress.go | 28 +- internal/reviewexec/round_progress_http.go | 2 +- internal/reviewexec/routes.go | 4 +- internal/reviewexec/run_http.go | 4 + internal/reviewexec/run_http_test.go | 69 +- internal/reviewexec/run_selection.go | 68 +- internal/reviewexec/run_selection_worker.go | 125 +- internal/reviewexec/scheduling.go | 370 +++++ .../scheduling_admission0030_test.go | 126 ++ .../scheduling_authorization_continuity.go | 72 + ...cheduling_authorization_continuity_test.go | 277 ++++ internal/reviewexec/scheduling_automatic.go | 691 ++++++++ internal/reviewexec/scheduling_cli.go | 41 + .../reviewexec/scheduling_cli_priority.go | 164 ++ .../scheduling_cli_priority0030_test.go | 177 ++ internal/reviewexec/scheduling_cli_test.go | 575 +++++++ internal/reviewexec/scheduling_http.go | 110 ++ .../scheduling_quarantine0030_test.go | 120 ++ .../scheduling_recovery0030_test.go | 157 ++ .../scheduling_recovery_regression_test.go | 989 ++++++++++++ .../scheduling_revision_validation_test.go | 74 + internal/reviewexec/scheduling_schema.go | 32 + internal/reviewexec/scheduling_snapshot.go | 159 ++ .../scheduling_snapshot0030_test.go | 56 + .../reviewexec/scheduling_source_retry.go | 158 ++ .../scheduling_source_retry_test.go | 379 +++++ internal/reviewexec/scheduling_test.go | 1427 +++++++++++++++++ internal/reviewexec/schema.go | 8 +- internal/reviewexec/supervisor.go | 20 +- internal/reviewexec/types.go | 4 + .../packagedsmoke/project_management_test.go | 37 + tools/packagedsmoke/run_selection_test.go | 50 +- 85 files changed, 9841 insertions(+), 171 deletions(-) create mode 100644 docs/review-scheduling.md create mode 100644 internal/backup/review_fronts_test.go create mode 100644 internal/backup/scheduling_test.go create mode 100644 internal/cli/review_scheduling.go create mode 100644 internal/cli/review_scheduling_help.go create mode 100644 internal/cli/review_scheduling_test.go create mode 100644 internal/client/review_scheduling.go create mode 100644 internal/client/review_scheduling_diagnostic.go create mode 100644 internal/client/review_scheduling_diagnostic_test.go create mode 100644 internal/client/review_scheduling_test.go create mode 100644 internal/core/project_automation.go create mode 100644 internal/core/project_automation_test.go create mode 100644 internal/mcpadapter/review_scheduling.go create mode 100644 internal/mcpadapter/review_scheduling_arguments_test.go create mode 100644 internal/mcpadapter/review_scheduling_test.go create mode 100644 internal/reviewexec/front_frame.go create mode 100644 internal/reviewexec/front_schema.go create mode 100644 internal/reviewexec/front_snapshot.go create mode 100644 internal/reviewexec/queued_diagnostic.go create mode 100644 internal/reviewexec/scheduling.go create mode 100644 internal/reviewexec/scheduling_admission0030_test.go create mode 100644 internal/reviewexec/scheduling_authorization_continuity.go create mode 100644 internal/reviewexec/scheduling_authorization_continuity_test.go create mode 100644 internal/reviewexec/scheduling_automatic.go create mode 100644 internal/reviewexec/scheduling_cli.go create mode 100644 internal/reviewexec/scheduling_cli_priority.go create mode 100644 internal/reviewexec/scheduling_cli_priority0030_test.go create mode 100644 internal/reviewexec/scheduling_cli_test.go create mode 100644 internal/reviewexec/scheduling_http.go create mode 100644 internal/reviewexec/scheduling_quarantine0030_test.go create mode 100644 internal/reviewexec/scheduling_recovery0030_test.go create mode 100644 internal/reviewexec/scheduling_recovery_regression_test.go create mode 100644 internal/reviewexec/scheduling_revision_validation_test.go create mode 100644 internal/reviewexec/scheduling_schema.go create mode 100644 internal/reviewexec/scheduling_snapshot.go create mode 100644 internal/reviewexec/scheduling_snapshot0030_test.go create mode 100644 internal/reviewexec/scheduling_source_retry.go create mode 100644 internal/reviewexec/scheduling_source_retry_test.go create mode 100644 internal/reviewexec/scheduling_test.go diff --git a/docs/README.md b/docs/README.md index e794c7122..212d9efaf 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. +- [Automatic review scheduling](review-scheduling.md): explicit default-off channel automation, scoped authorizers and durable PR pauses. - [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/mcp.md b/docs/mcp.md index 979f64f6c..88ebcbd27 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -93,6 +93,10 @@ Startup validates configuration without opening the credential or contacting the | `inbox_events` | Required event cursor; optional limit and wait_ms 0–4000; one bounded incoming-event page. | | `wait_for_messages` | Required event cursor; optional limit 1–100 and wait_seconds 1–50, default 20/25. One new-message event page or quiet timeout over a call-owned persistent stream. | | `review_execution_read` | No fields; stored execution configuration and revision, without provider work. | +| `review_scheduling_read` | No fields; stored project scheduling settings, revision and paused queued PRs, without provider work. | +| `review_scheduling_configure` | Required idempotency_key/expected_revision/automatic_hosted; optional automatic_cli preserves its existing value when omitted. Project management capability configures [default-off automatic scheduling](review-scheduling.md), including authorization for later provider work within existing review limits. | +| `review_pull_scheduling_read` | Required pull_number; reads the per-PR pause for new and undispatched explicit and automatic reviews, and its revision. | +| `review_pull_scheduling_update` | Required idempotency_key/pull_number/expected_revision/paused; optional reason is accepted only when pausing. Changes the scheduling pause while preserving review limits and retained request controls. | | `review_operations_list` | Optional pull_number/channel/status/limit/cursor; one bounded page of retained operations, default five pending. No provider work or automatic continuation. | | `review_operation_read` | Required operation_id; optional wait_seconds (0–50/default 0) and diagnostics (default false). Compact retained status and original Hosted observer freshness, or explicit full detail, without provider polling. | | `review_operation_control` | Required operation_id/expected_revision/action/idempotency_key; action pause, resume or cancel applies guarded [retained request controls](retained-review-quota-controls.md#reading-state), preserving original authorization and attempt history. | @@ -144,7 +148,7 @@ Review queue/run/attempt lists default to five entries; other limits use the API [Job progress](job-progress.md) owns update/checklist content limits, independent revisions, explicit archives and integration proof. Checklist replacement can remove or replace effective items and is annotated destructive; its immutable history remains available. Job updates and checklist operations perform no provider work. -Mutations require the caller to retain an explicit key and request; the adapter never generates a replacement key or automatically retries. Job edits require the current expected revision; empty brief or worker clears that field. A dispatched write with a lost, canceled or invalid response returns `outcome_unknown` when a tool result can be delivered. Host cancellation may suppress that result, so absence of a reply is never proof of rollback. Recover using the original request, key and binding. The [MCP annotations](https://modelcontextprotocol.io/specification/2025-11-25/schema#toolannotations) distinguish reads from writes. Repeating identical arguments retains the same explicit key and has no additional effect; job edits and review decision/fix corrections can replace effective fields while retained history remains; creation/checkpoint/send/receipt transitions add records or handling state. Job, message and evidence controls operate within the configured service. `review_start`, `review_request`, `review_source_refresh`, `review_checkpoint_publish` and `review_checkpoint_recover` are annotated open-world because they authorize external provider work; a queued receipt does not establish started or completed execution. The [CLI recovery rules](development.md#explicit-agent-mutations) also apply. +Mutations require the caller to retain an explicit key and request; the adapter never generates a replacement key or automatically retries. Job edits require the current expected revision; empty brief or worker clears that field. A dispatched write with a lost, canceled or invalid response returns `outcome_unknown` when a tool result can be delivered. Host cancellation may suppress that result, so absence of a reply is never proof of rollback. Recover using the original request, key and binding. The [MCP annotations](https://modelcontextprotocol.io/specification/2025-11-25/schema#toolannotations) distinguish reads from writes. Repeating identical arguments retains the same explicit key and has no additional effect; job edits and review decision/fix corrections can replace effective fields while retained history remains; creation/checkpoint/send/receipt transitions add records or handling state. Job, message and evidence controls operate within the configured service. `review_scheduling_configure`, `review_start`, `review_request`, `review_source_refresh`, `review_checkpoint_publish` and `review_checkpoint_recover` are annotated open-world because they authorize external provider work; a queued receipt does not establish started or completed execution. The [CLI recovery rules](development.md#explicit-agent-mutations) also apply. Explicit message, review-result, source-refresh and checkpoint waits are capped at 50 seconds in both discovery and argument validation. With the five-second service budget, these calls leave at least five seconds below a 60-second host tool deadline. Hosts with shorter configured limits need shorter requested waits. This MCP cap does not narrow CLI or typed-client limits. `wait_for_ci` accepts 0–900 seconds and is exempt from this 50-second cap. For waits over two seconds, its call budget is the selected wait plus fifteen seconds; shorter waits use fifteen seconds. Both are subject to an earlier host deadline. Configure the host tool deadline to cover that budget; the adapter shortens the forwarded wait to leave response time within any earlier deadline. See [CI waits](ci-wait.md) for reconnect and pinned-comparison behavior. diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md new file mode 100644 index 000000000..67297f033 --- /dev/null +++ b/docs/review-scheduling.md @@ -0,0 +1,79 @@ +# Review scheduling + +## Source-slice boundary + +This slice includes the scheduling engine, retained-state guards, HTTP API and CLI/MCP controls. The current-review-progress browser consumer, its scoped live-event additions, generated assets and browser smoke workload are delivered in the dependent browser slice. Browser behavior and historical validation described below apply to that combined stack, not this intermediate scheduling tree. + +Projects can independently opt in to automatic new Hosted or CLI requests. Both default to off. Explicit CLI requests continue to work without enabling automatic selection; a proven quota refusal retains any accepted request through [durable CLI waiting](retained-review-quota-controls.md), without replacing that operation. Automatic GitHub observation and automatic retry of an already authorized timer-backed request are independent of this setting; see [observation](github-observation.md) and [timer-backed waiting](retained-review-quota-controls.md). + +## Automatic Hosted requests + +A project manager enables scheduling through CLI or MCP. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. The HTTP contract also permits an authorized browser manager to explicitly select the authorizing worker while retaining the human session identity. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. Across an authorizer change, only an already selected operation can continue, and both authorizers must remain valid. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. + +The scheduler uses the existing configured queue and ordinary durable selection/operation path. It checks eligible work at most once per five-second coordinator interval; this is not a promised start time or another GitHub polling loop. Source, dependency, publication, findings, routes, imported obligations, round limits, taper and provider guards still apply. Independent PRs can proceed while another awaits fixes; real dependencies retain predecessor guards. Retained scheduling validation failures prevent planning for the affected project; malformed shared scheduling state or unavailable shared authorization can affect both channels. Channel-front and source-retry selection validation failures, a retained parent cycle, or a planning basis above its row limit remain local to the affected project and channel. Independent projects continue, and channel-specific failures do not block the other channel. The execution supervisor skips these typed project-local refusals, and a damaged competing priority candidate cannot block a healthy project’s account claim. A deterministic basis refusal during selection settlement rolls back source and child writes and holds the original selection as `automatic_scheduling_unavailable`; it is not transient contention and does not enter the writer retry loop. The accepted basis remains available for duplicate suppression across ticks and restart. Startup validates the shared front-cache table definition without scanning optional cache rows. Damaged rows remain isolated by project/channel readers; backup and restore still validate the complete retained snapshot. Shared storage and transaction failures remain errors rather than being suppressed; arbitrary SQL failures are not classified as project-local corruption. Automatic requests never inherit out-of-order or file-limit overrides. Each project first plans in a bounded read-only snapshot. Only a candidate for a new intent or a due retained source retry enters the writer, which repeats authorization, configuration, policy, pause, busy and basis checks before ordinary atomic acceptance or retry. A changed plan waits for a later pass. + +Meaningful source, review or control changes can create another automatic intent. A waiting later PR does not prevent reconsideration of an earlier PR that becomes eligible; the earlier request can take priority while the later request retains its identity and cooldown. Existing queued work on a PR prevents a duplicate intent for that PR, and active provider work is not interrupted. Timer-backed requests retain their original operation and retry deadline. Ticks, restarts, observation timestamps and failed/cancelled operation transitions cannot recreate the same request. A clean CLI completion alone cannot restart a cancelled Hosted request. A dependent PR can become eligible when its actual predecessor completes at the same head. Cancellation stops that intent; use a PR pause to hold new reviews persistently. A setting change affecting only the other channel preserves this channel’s intent basis. Changing this channel’s setting or the authorizing principal, worker or credential changes its basis. Explicitly reasserting unchanged settings rearms only the supplied channels; an omitted CLI setting preserves its basis. The current scheduling event retains each channel’s basis revision independently of the shared authorization revision. Older events use their existing shared revision without rewriting any stored digests, so an upgrade alone cannot recreate cancelled work. + +A pre-child automatic Hosted or CLI selection held only by `source_budget_exhausted`, `source_fetch_timeout` or `source_provider_unavailable` can retry its source selection after at least thirty seconds. It reuses the original selection and accepted configuration, policy, capability and authorizer, with the exact scheduling revision still current. At most two such delayed retries are permitted by a conservative durable transition budget; interrupted-selection recovery consumes that budget rather than resetting it. Existing recovery of an interrupted read remains separate from this bound on completed source holds. Restart and backup restore retain the budget and last-transition time. Restore/provider holds still prevent work. + +A later selection or direct operation in the same channel fences off this recovery, including a cancelled, failed or uncertain request. Explicit held selections, linked children, exhausted budgets, refusals, rate limits and invalid source responses are never reopened by it. The retry performs ordinary fresh source selection and normal admission; success may link at most one ordinary child operation under the original authority. It neither grants rounds nor bypasses any dispatch guard. A meaningful source or control change can still authorize a new automatic intent through the normal scheduler. + +Results still require normal adjudication, finalization and fix evidence. Automation does not infer fixes or grant more reviews. Enabling it can spend existing authorized Hosted allowance; it is a deliberate project control, not a prerequisite for routine review use. + +## Automatic CLI requests + +A project manager can explicitly enable `automatic_cli` through CLI, MCP or the project scheduling API. A future browser editor must preserve the CLI setting when editing Hosted configuration. Both settings use the retained manager credential and active worker, with the same authorization rechecks before selection and dispatch. Changing either setting uses the shared scheduling revision. Older Hosted-only writes omit `automatic_cli` and preserve its current value; explicit `false` disables new CLI automation. + +Automatic CLI uses the ordinary durable channel-front selection and execution path, without out-of-order or file-limit overrides. Existing grants, maxima, taper, channel closure, exact current-head checks, source-owned predecessor dependencies, publication and adjudication requirements remain in force. No setting increases grants or adjudicates findings. A meaningful completed result or source/control change can authorize another selection; ticks, restart, failed attempts and cancellation alone cannot. CLI and Hosted results have separate intent digests, so a clean completion in the other channel does not recreate a cancelled request. + +The current server policy fixes one repository preference in code; it is not a per-project setting. For competing CLI work on the same installed provider account, the repository `benhook1013/FireMUD` takes priority over other projects. The repository identity is case-insensitive; a project display name does not grant priority. Selection considers that repository first, and the serialized attempt claim also yields to its eligible queued requests. Paused, invalid, draft-waiting or not-yet-due requests do not reserve the account. Other accounts remain independent and active reviews are never preempted. This preference does not relax dependencies or change retained quota deadlines. It has no fairness or maximum-deferral guarantee: other projects on that account may wait indefinitely while the preferred repository continues to have eligible work. + +An already queued explicit or automatic CLI operation prevents a duplicate request for its PR. Proven quota exhaustion keeps that operation and its original comparison through the existing shared-account backoff. Disable automatic CLI to stop new automatic selection and authorization of its undispatched children; explicit pending requests retain their original authorization. Use an operation cancellation or PR pause when the intent itself must stop. Results and merge decisions remain operator work. + +## Pause a PR + +An ordinary project writer can pause new reviews for a PR, even before its first review intent. CLI, MCP and the project scheduling API expose pause and resume. Browser queue controls are a separate consumer. The pause covers undispatched work in both channels, preserves queued identities and cooldown deadlines, and permits collection of an already issued review. An optional short reason explains the pause; resume clears it. + +Draft PRs are separately ineligible for dispatch. [Explicit CLI requests can wait for readiness](retained-review-quota-controls.md). A PR pause does not change GitHub Draft state, round settings, earned taper, channel closure, worker coordination pause, project execution pause or an individual operation's pause. Resuming a PR does not resume an explicitly paused operation or reopen a closed channel. See [operation controls](retained-review-quota-controls.md) and [round controls](review-round-controls.md). + +## Accepted queue priority + +Current queued diagnostics explain an earlier accepted Hosted request before the later request's independent cooldown. A row with remaining work but no accepted request does not reserve a turn. Paused, cancelled or invalid earlier requests do not retain priority. These are bounded local reads, not source scans or provider polling. CLI shared-account quota diagnostics retain `cli_quota_wait` across response versions only while the current configuration and capability still match the accepted operation. Paused or revoked work reports its own hold first. An expired or incompatible quota binding leaves the ordinary scheduling diagnostic; these headers do not invent retained wait or allowance facts. + +Version `5` of `X-FC-Operation-Wait` extends version `3` with optional `queue_ahead_pull_number` in the staged round-progress read. Older supported versions omit it and retained deadlines remain unchanged. The browser uses this hint for **Behind #PR**, without a visible or hidden timer; only the next accepted request shows its own countdown. This projection does not promise dispatch or change review accounting. + +The existing queue and PR detail views show current round allowance, closure or taper, separate execution/adjudication counts and retained waits. Queue pages use one bounded local progress read for only their visible PRs; detail views read only the selected PR. Existing scoped project events invalidate the current read. The countdown updates text locally and creates no API requests. Historical run snapshots stay immutable and separate from explicitly current round progress. Automatic-setting and PR-pause browser editors remain outside this slice. + +## CLI and MCP + +Read the current scheduling revision before changing settings. Keep the exact request and key after an uncertain mutation outcome; replaying the same key cannot enable or pause twice. + +```sh +fc reviews scheduling +fc reviews scheduling configure --automatic-hosted true --automatic-cli true --expect-revision 0 --key retained-enable-key +fc reviews scheduling read --pr 123 +fc reviews scheduling pause --pr 123 --reason 'Preparing fixes' --expect-revision 0 --key retained-pause-key +fc reviews scheduling resume --pr 123 --expect-revision 1 --key retained-resume-key +``` + +Use the explicit scheduling read to inspect its independent revision, automatic settings and authorizing worker alongside execution configuration. The authorizer is permission attribution, not lane ownership. Scheduling does not manufacture inbox messages for its coordinator ticks. + +MCP equivalents are `review_scheduling_read`, `review_scheduling_configure`, `review_pull_scheduling_read` and `review_pull_scheduling_update`. The update takes explicit PR number, `paused`, expected revision and idempotency key; project configuration takes explicit `automatic_hosted`, optional `automatic_cli`, expected revision and key. Use tools advertised by the running client. Neither read starts work. Project reads include only currently queued paused PRs; explicit PR reads can inspect pauses outside the queue. + +## HTTP and retention + +`GET`/`POST /api/v1/projects/{project_id}/reviews/scheduling` read/configure project scheduling. The write body is `{expected_revision, automatic_hosted, automatic_cli?}` and requires project management. `GET`/`POST /api/v1/projects/{project_id}/reviews/pulls/{number}/scheduling` read/update a PR pause. The write body is `{expected_revision, paused, reason?}` and requires project write access. Writes require the normal explicit idempotency key. Unconfigured records read as revision zero and off/unpaused; writes return a new revision. Project reads report unavailable authorization or provider holds without exposing credential identifiers or tokens. + +Backups retain scheduling, PR pauses and automatic-intent attribution. Older bundles without this optional domain remain off; version-one Hosted-only records migrate with automatic CLI off. Restore remains inactive with provider execution held. Historical authorizers remain valid historical evidence after revocation or retirement. + +## Validation + +The extracted source compiles across the repository. Focused tests pass for default-off behavior, exact authorizer withdrawal and continuity, writer/manager boundaries, pause before intent and dispatch, retained timer identity, cancellation suppression, independent progression, same-head dependency release, ordinary supervisor dispatch, bounded source retry, typed CLI/MCP help and diagnostics, exact-key recovery and backup/inactive restore. The focused execution group passed in 17.070 seconds with controlled providers and no live review allowance. + +Rebuilt CGO-free `fc`, `fcd` and `fcmcp` passed the actual packaged administration workload extended with scheduling controls. Starting from a genuine predecessor fixture, native CLI configuration and exact-key replay, official-SDK MCP pause/read/resume and restarted CLI reads retained both control revisions. Scheduling stayed off and no external HTTP or provider work occurred. This is administrative integration proof, not live scheduler throughput, browser interaction or installed-deployment proof. + +The full affected Go packages passed, including the final execution and backup suites after integration fixes. Focused scheduling race checks, vet, whole-repository compilation and formatting passed. The current-progress browser consumer passes TypeScript and all 352 browser tests using the pinned lockfile dependencies, including strict response validation, scoped event invalidation, closed-channel presentation, accepted queue order and hidden-timer suppression. Regenerated embedded assets build successfully. The packaged browser workload exercises actual round grant/close events. Its local-host run exposed a native round-event resource shape mismatch, which is covered by a red/green decoder and scoped-invalidation regression. That correction preserves strict validation for other resource types. The corrected packaged browser workload then passed on a local Linux host with the documented installed Chromium 156 override and pinned Playwright 1.65.0. It verified native grant/close refreshes in 3.53 seconds, zero daemon/page external HTTP and no surviving owned processes. This is not installed-deployment or pinned-default-browser proof. Automatic-setting and PR-pause browser editors are not included. + +Hosted review follow-through adds per-project parent-cycle isolation, bounded automatic CLI source recovery, strict scheduling schema versions, server-compatible timestamp validation, and progress refresh for native operation events. Full review execution, backup, core, client and MCP packages, focused recovery race tests, schema compatibility, all 352 browser tests, TypeScript, compilation, vet and docs pass. The current packaged Chromium and keyboard checks could not start because the execution environment rejected the browser singleton socket. No browser interaction ran in those checks, so the earlier successful packaged-browser proof above is historical rather than proof of this revised executable. + +Focused coordinator regressions cover idle planning behind an occupied writer, serialized candidate revalidation and duplicate prevention, project-local scheduling/front/selection, policy, parent proof/round/route/adoption and basis-cap refusals, shared-storage failure propagation and attribution rollback, claim/choose/finish worker continuation, explicit local-read versus automatic scheduling hold attribution, and same-authorizer channel continuity for queued, selecting and selected intents. These synthetic tests do not establish production scheduler throughput or universal classification of malformed data in other review domains. 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 8f0489a9d..80fee7c6b 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -222,8 +222,12 @@ 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{"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": 3, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} +var supportedDomains = map[string]int{"review_scheduling": 2, "review_fronts": 1, "project_management": 1, "worker_retirements": 1, "review_selection": 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": 3, "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_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"}, @@ -606,6 +610,17 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ return nil, invalid() } } + if versions["review_scheduling"] > 0 { + if versions["review_selection"] == 0 || versions["review_execution"] == 0 { + return nil, invalid() + } + if err = validateSchedulingPhysicalSchema(ctx, db, versions["review_scheduling"]); err != nil { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, err + } + } if versions["worker_retirements"] > 0 { if err := validatePhysicalSchemaObjects(ctx, db, map[string]physicalSchemaObject{"worker_retirements": {"table", `CREATE TABLE worker_retirements(project_id TEXT NOT NULL REFERENCES projects(id),worker_id TEXT NOT NULL,retired_at TEXT NOT NULL,actor_id TEXT NOT NULL,PRIMARY KEY(project_id,worker_id),FOREIGN KEY(project_id,worker_id) REFERENCES workers(project_id,id))`}}, []string{"worker_retirements"}); err != nil { if contextErr := checkContext(ctx); contextErr != nil { @@ -654,6 +669,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" } @@ -1030,6 +1048,22 @@ func validateSnapshotContent(ctx context.Context, dataDir string, m Manifest, al 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 { + return unavailable() + } + return invalid() + } + } if versions["review_selection"] > 0 { if err = reviewexec.ValidateSelectionSnapshot(ctx, tx); err != nil { if checkContext(ctx) != nil { @@ -1228,6 +1262,10 @@ 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_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")}, @@ -1605,6 +1643,23 @@ func validateExternalHostedEvidenceIndexes(ctx context.Context, db sqlReader, ve return nil } +func validateSchedulingPhysicalSchema(ctx context.Context, db sqlReader, version int) error { + expected := map[string]physicalSchemaObject{} + statements := reviewexec.SchedulingSchemaSQL() + if version >= 2 { + statements = reviewexec.SchedulingSchemaV2SQL() + } + for _, statement := range statements { + fields := strings.Fields(statement) + if len(fields) < 4 || fields[0] != "CREATE" || fields[1] != "TABLE" && fields[1] != "INDEX" { + return invalid() + } + name, _, _ := strings.Cut(fields[2], "(") + expected[name] = physicalSchemaObject{strings.ToLower(fields[1]), historyDefinitionSQL(statement)} + } + return validatePhysicalSchemaObjects(ctx, db, expected, []string{"review_scheduling", "review_pull_scheduling", "review_automatic_selections"}) +} + func validateAdministrationContent(ctx context.Context, db sqlReader, versions map[string]int) error { if versions["project_management"] > 0 { var bad int diff --git a/internal/backup/physical_schema_test.go b/internal/backup/physical_schema_test.go index c72d5cb55..07b72dd76 100644 --- a/internal/backup/physical_schema_test.go +++ b/internal/backup/physical_schema_test.go @@ -2,8 +2,12 @@ package backup import ( "database/sql" + "fmt" "path/filepath" + "strings" "testing" + + "github.com/benhook1013/FireController/internal/reviewexec" ) func TestDomainPhysicalSchemaExactInventory(t *testing.T) { @@ -48,6 +52,58 @@ func TestDomainPhysicalSchemaExactInventory(t *testing.T) { } } +func TestSchedulingPhysicalSchemaExactInventory(t *testing.T) { + for _, version := range []int{1, 2} { + t.Run(fmt.Sprintf("v%d", version), func(t *testing.T) { + canonical := reviewexec.SchedulingSchemaSQL() + if version == 2 { + canonical = reviewexec.SchedulingSchemaV2SQL() + } + for _, tc := range []struct { + name, mutation string + valid bool + }{ + {"canonical", "", true}, + {"unrelated objects", `CREATE TABLE unrelated (id INTEGER); CREATE INDEX unrelated_id ON unrelated(id);`, true}, + {"missing table", `DROP TABLE review_pull_scheduling;`, false}, + {"missing index", `DROP INDEX review_automatic_selections_pull;`, false}, + {"changed index", `DROP INDEX review_automatic_selections_pull; CREATE INDEX review_automatic_selections_pull ON review_automatic_selections(project_id);`, false}, + {"weakened table", `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'revision>0','revision>=0') WHERE name='review_scheduling'; PRAGMA writable_schema=OFF;`, false}, + {"extra index", `CREATE INDEX scheduling_extra ON review_scheduling(revision);`, false}, + {"oversized name", `CREATE INDEX ` + strings.Repeat("x", 129) + ` ON review_scheduling(revision);`, false}, + {"oversized definition", `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=sql||' /*` + strings.Repeat("x", 16384) + `*/' WHERE name='review_scheduling'; PRAGMA writable_schema=OFF;`, false}, + } { + t.Run(tc.name, func(t *testing.T) { + db, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "schema.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + for _, statement := range canonical { + if _, err := db.ExecContext(t.Context(), statement); err != nil { + t.Fatal(err) + } + } + if tc.mutation != "" { + if _, err := db.ExecContext(t.Context(), tc.mutation); err != nil { + t.Fatal(err) + } + } + err = validateSchedulingPhysicalSchema(t.Context(), db, version) + if tc.valid { + if err != nil { + t.Fatal("canonical scheduling schema rejected", err) + } + backupCode(t, validateSchedulingPhysicalSchema(t.Context(), db, 3-version), "backup_invalid") + } else { + backupCode(t, err, "backup_invalid") + } + }) + } + }) + } +} + func TestDomainPhysicalSchemaRejectsInvalidCanonicalInputs(t *testing.T) { const table = `CREATE TABLE owned (id INTEGER);` for _, tc := range []struct { diff --git a/internal/backup/review_fronts_test.go b/internal/backup/review_fronts_test.go new file mode 100644 index 000000000..f0a1d45e4 --- /dev/null +++ b/internal/backup/review_fronts_test.go @@ -0,0 +1,88 @@ +package backup + +import ( + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/reviewexec" +) + +func TestFrontInventoryRealSelectionBackupAndInactiveRestore(t *testing.T) { + for _, state := range []string{"selected", "held", "empty"} { + t.Run(state, func(t *testing.T) { + f, _ := selectionInventoryFixture(t, state) + if err := reviewexec.ValidateFrontSnapshot(t.Context(), f.store.DB()); err != nil { + t.Fatal(err) + } + var n int + if err := f.store.DB().QueryRow(`SELECT count(*) FROM review_front_frames`).Scan(&n); err != nil || n != 1 { + t.Fatal(n, err) + } + before := backupRows(t, f.store.DB()) + bundle := restoreBundle(t, f) + tree := restoreTree(t, bundle.Path) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal(err) + } + destination := filepath.Join(t.TempDir(), "inactive-fronts") + 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() + if err = reviewexec.ValidateFrontSnapshot(t.Context(), db); err != nil { + t.Fatal(err) + } + after := backupRows(t, db) + if before["review_front_frames"] != after["review_front_frames"] { + t.Fatal("restore changed cached source") + } + if !reflect.DeepEqual(before, backupRows(t, f.store.DB())) || !reflect.DeepEqual(tree, restoreTree(t, bundle.Path)) { + t.Fatal("read/restore changed source or bundle") + } + }) + } +} +func TestFrontInventoryRejectsResealedCorruptionAndSupportsPredecessor(t *testing.T) { + for _, query := range []string{ + `UPDATE review_front_frames SET prefix_json='null'`, + `UPDATE review_front_frames SET prefix_json=replace(replace(prefix_json,',"visible_at_acquisition":true',''),',"visible_at_acquisition":false','')`, + `UPDATE review_front_frames SET prefix_json=replace(replace(prefix_json,'"visible_at_acquisition":true','"visible_at_acquisition":"yes"'),'"visible_at_acquisition":false','"visible_at_acquisition":"yes"')`, + `UPDATE review_front_frames SET prefix_json=' []'`, + `UPDATE review_front_frames SET checked_at=CAST(checked_at AS BLOB)`, + `UPDATE review_front_frames SET prefix_json=replace(prefix_json,'"number":4','"number":5')`, + `UPDATE review_front_frames SET source_observed_at='not-a-time'`, + `UPDATE review_front_frames SET configuration_revision=999`, + `CREATE INDEX invented_front_history ON review_front_frames(checked_at)`, + `ALTER TABLE review_front_frames ADD COLUMN invented_credit INTEGER`, + } { + t.Run(query[:min(50, len(query))], func(t *testing.T) { + f, _ := selectionInventoryFixture(t, "held") + bundle := restoreBundle(t, f) + mutateBundleSQL(t, bundle.Path, query) + assertCurrentSummaryInventoryRefused(t, bundle, false) + }) + } + t.Run("missing-optional-domain", func(t *testing.T) { + f := newRestoreFixture(t) + if _, err := f.store.DB().Exec(`DROP TABLE review_front_frames;DELETE FROM metadata WHERE key='schema:review_fronts'`); err != nil { + t.Fatal(err) + } + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal("valid predecessor refused", err) + } + }) + t.Run("nullable-project-key", func(t *testing.T) { + f := newRestoreFixture(t) + bundle := restoreBundle(t, f) + ddl := strings.Replace(reviewexec.FrontSchemaSQL()[0], "project_id TEXT NOT NULL REFERENCES", "project_id TEXT REFERENCES", 1) + mutateBundleSQL(t, bundle.Path, `DROP TABLE review_front_frames;`+ddl) + assertCurrentSummaryInventoryRefused(t, bundle, false) + }) +} diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index 4fc00271b..74b0ddc97 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,14 +234,22 @@ func TestSelectionInventorySchemaAndPredecessor(t *testing.T) { }) } -// Removing the independent optional domain reconstructs the unchanged parent -// physical schema, rather than relabeling a newer reviews/execution migration. +// The newer scheduling and front-cache domains must be absent from a +// predecessor snapshot along with selection. Scheduling references selections +// directly, so leaving it installed would not describe a valid predecessor. +func dropSelectionPredecessorDomains(t *testing.T, db *sql.DB) { + t.Helper() + if _, err := db.Exec(`DROP TABLE review_automatic_selections; DROP TABLE review_pull_scheduling; DROP TABLE review_scheduling; DROP TABLE review_front_frames; DROP TABLE review_selections; DELETE FROM metadata WHERE key IN ('schema:review_scheduling','schema:review_fronts','schema:review_selection')`); err != nil { + t.Fatal(err) + } +} + +// Removing the new optional domains reconstructs a valid parent schema without +// relabeling a newer reviews/execution migration. func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testing.T) { f := newRestoreFixture(t) db := f.store.DB() - if _, err := db.Exec(`DROP TABLE review_selections;DELETE FROM metadata WHERE key='schema:review_selection'`); err != nil { - t.Fatal(err) - } + dropSelectionPredecessorDomains(t, db) before := backupRows(t, db) 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`) @@ -269,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_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,11 +290,25 @@ func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testin if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:review_selection'`).Scan(&version); err != nil || version != "1" { 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)+5 { + t.Fatal("upgrade did not reinstall the newer optional domains", len(before), len(after)) + } + for domain, version := range map[string]string{"review_selection": "1", "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_selections','review_scheduling','review_pull_scheduling','review_automatic_selections','review_front_frames')`).Scan(&count); err != nil || count != 5 { + t.Fatal("new optional domain tables were not reinstalled", count, err) } - if err := db.QueryRow(`SELECT count(*) FROM sqlite_schema WHERE name IN ('review_scheduling','review_pull_scheduling','review_automatic_selections','review_front_frames','review_pr_followers')`).Scan(&count); err != nil || count != 0 { - t.Fatal("deferred domain installed", 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) diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go new file mode 100644 index 000000000..820408e23 --- /dev/null +++ b/internal/backup/scheduling_test.go @@ -0,0 +1,311 @@ +package backup + +import ( + "context" + "database/sql" + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +type schedulingBackupReader struct { + *selectionInventoryReader + entered chan struct{} + once sync.Once +} + +func (r *schedulingBackupReader) Repository(ctx context.Context, id int64) (reviewprovider.Repository, error) { + r.once.Do(func() { close(r.entered) }) + return r.selectionInventoryReader.Repository(ctx, id) +} + +func schedulingBackupFixture(t *testing.T) (*restoreFixture, *reviewexec.Engine, string) { + t.Helper() + f := newRestoreFixture(t) + e := selectionInventoryEngine(t, f.store) + scope := routePolicyInventoryScope(t, f) + var attempt string + var revision int64 + if err := f.store.DB().QueryRow(`SELECT id,revision FROM review_execution_attempts`).Scan(&attempt, &revision); err != nil { + t.Fatal(err) + } + if _, err := e.Advance(t.Context(), f.project, attempt, revision, "held", "synthetic_preparation_ended", ""); err != nil { + t.Fatal(err) + } + one, zero, on := int64(1), int64(0), true + if _, err := e.Configure(t.Context(), scope, "scheduling-backup-queue", reviewexec.Configuration{ExpectedRevision: &one, CapabilityID: "restore-cap", Mode: "independent", Queue: []int64{2, 4}, Channels: []string{"hosted"}}); err != nil { + t.Fatal(err) + } + if _, err := e.ConfigurePullScheduling(t.Context(), scope, "pause-backup-pull", 2, reviewexec.PullSchedulingRequest{ExpectedRevision: &zero, Paused: &on, Reason: "Fix in progress"}); err != nil { + t.Fatal(err) + } + if _, err := e.ConfigureScheduling(t.Context(), scope, "enable-backup-scheduling", reviewexec.SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &on}); err != nil { + t.Fatal(err) + } + reader := &schedulingBackupReader{selectionInventoryReader: &selectionInventoryReader{state: "selected"}, entered: make(chan struct{})} + ctx, cancel := context.WithCancel(t.Context()) + done, err := e.StartReviewRuns(ctx, map[string]reviewexec.TargetReader{"restore-cap": reader}) + if err != nil { + cancel() + t.Fatal(err) + } + t.Cleanup(cancel) + select { + case <-reader.entered: + case <-time.After(3 * time.Second): + cancel() + t.Fatal("automatic selection did not read synthetic source") + } + var selection string + if err := f.store.DB().QueryRow(`SELECT selection_id FROM review_automatic_selections`).Scan(&selection); err != nil { + cancel() + t.Fatal(err) + } + run, terminal, err := e.WaitRun(t.Context(), scope, selection, 3) + cancel() + select { + case workerErr := <-done: + if workerErr != nil { + t.Fatal(workerErr) + } + case <-time.After(3 * time.Second): + t.Fatal("selection worker did not join") + } + if err != nil || !terminal || run.State != "selected" || run.OperationID == "" { + t.Fatal("automatic selection did not retain a native child", run, err) + } + if err := f.store.DB().QueryRow(`SELECT credential_id FROM review_scheduling WHERE project_id=?`, f.project).Scan(&attempt); err != nil { + t.Fatal(err) + } + return f, e, attempt +} + +func schedulingBackupRows(t *testing.T, db *sql.DB) map[string][][]any { + t.Helper() + rows := map[string][][]any{} + for _, table := range []string{"review_scheduling", "review_pull_scheduling", "review_automatic_selections"} { + rows[table] = restoreRows(t, db, `SELECT * FROM `+table+` ORDER BY 1`) + } + return rows +} + +func TestSchedulingBackupRetainsNativeControlsAndInactiveRestore(t *testing.T) { + f, _, credential := schedulingBackupFixture(t) + before := schedulingBackupRows(t, f.store.DB()) + 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-scheduling") + if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { + t.Fatal(err) + } + restored, err := core.Open(t.Context(), destination) + if err != nil { + t.Fatal(err) + } + defer restored.Close() + if !reflect.DeepEqual(before, schedulingBackupRows(t, restored.DB())) || !reflect.DeepEqual(before, schedulingBackupRows(t, f.store.DB())) || !reflect.DeepEqual(immutable, restoreTree(t, bundle.Path)) { + t.Fatal("backup/inspect/restore changed retained scheduling facts") + } + status, err := ReadRecoveryStatus(t.Context(), restored) + if err != nil || status.State != "inactive" || !status.ProvidersHeld { + t.Fatal("restore enabled provider work", status, err) + } + backupCode(t, StartupGuard(t.Context(), restored), "restore_inactive") + tx, err := restored.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if err := reviewexec.ValidateSchedulingSnapshot(t.Context(), tx); err != nil { + t.Fatal("revoked restored authors lost historical validity", err) + } + _, err = restored.ProjectAutomationScope(t.Context(), tx, f.project, f.principal, f.worker, credential) + backupCode(t, err, "forbidden") +} + +func TestSchedulingBackupHistoricalAuthorizersRemainHistory(t *testing.T) { + f, _, credential := schedulingBackupFixture(t) + for _, kind := range []string{"revoked", "demoted", "retired"} { + t.Run(kind, func(t *testing.T) { + var query string + switch kind { + case "revoked": + query = `UPDATE credentials SET revoked=1 WHERE id=?` + case "demoted": + query = `UPDATE credentials SET is_admin=0 WHERE id=?` + case "retired": + query = `INSERT INTO worker_retirements(project_id,worker_id,retired_at,actor_id) VALUES('` + f.project + `','` + f.worker + `','2026-11-01T00:00:00Z','synthetic-actor')` + } + if kind == "retired" { + if _, err := f.store.DB().Exec(query); err != nil { + t.Fatal(err) + } + } else if _, err := f.store.DB().Exec(query, credential); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if _, err := f.store.DB().Exec(`UPDATE credentials SET revoked=0,is_admin=1 WHERE id=?; DELETE FROM worker_retirements WHERE project_id=? AND worker_id=?`, credential, f.project, f.worker); err != nil { + t.Fatal(err) + } + }) + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + _, err = f.store.ProjectAutomationScope(t.Context(), tx, f.project, f.principal, f.worker, credential) + _ = tx.Rollback() + if err == nil { + t.Fatal("historical authorizer still authorized new automation") + } + before := schedulingBackupRows(t, f.store.DB()) + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal("valid history refused", err) + } + dest := filepath.Join(t.TempDir(), "historical-inactive") + if _, err := Restore(t.Context(), bundle.Path, dest); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(dest, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if !reflect.DeepEqual(before, schedulingBackupRows(t, db)) { + t.Fatal("restore rewrote historical scheduling attribution") + } + }) + } +} + +func schedulingBundleCopy(t *testing.T, source string) string { + t.Helper() + destination := filepath.Join(t.TempDir(), filepath.Base(source)) + if err := os.CopyFS(destination, os.DirFS(source)); err != nil { + t.Fatal(err) + } + if err := filepath.WalkDir(destination, func(p string, d os.DirEntry, err error) error { + if err != nil { + return err + } + mode := os.FileMode(0600) + if d.IsDir() { + mode = 0700 + } + return os.Chmod(p, mode) + }); err != nil { + t.Fatal(err) + } + return destination +} + +func TestSchedulingBackupRefusesResealedShapeReferencesAndProvenance(t *testing.T) { + f, _, _ := schedulingBackupFixture(t) + bundle := restoreBundle(t, f) + for _, tc := range []struct{ name, query string }{ + {"empty-current-event", `UPDATE events SET payload_json='{}' WHERE event_type='review.scheduling_updated'`}, + {"mismatched-current-event", `UPDATE events SET payload_json='{"automatic_hosted":false}' WHERE event_type='review.scheduling_updated'`}, + {"invalid-current-basis", `UPDATE events SET payload_json='{"automatic_hosted":true,"hosted_basis_revision":999,"cli_basis_revision":999}' WHERE event_type='review.scheduling_updated'`}, + {"missing-current-event", `DELETE FROM events WHERE event_type='review.scheduling_updated'`}, + {"wrong-current-event-actor", `UPDATE events SET actor_id='principal_missing' WHERE event_type='review.scheduling_updated'`}, + {"missing-domain", `DELETE FROM metadata WHERE key='schema:review_scheduling'`}, + {"missing-index", `DROP INDEX review_automatic_selections_pull`}, + {"weakened-schema", `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'revision>0','revision>=0') WHERE name='review_scheduling'; PRAGMA writable_schema=OFF`}, + {"missing-worker", `UPDATE review_scheduling SET worker_id='worker_missing'`}, + {"forged-author", `UPDATE review_scheduling SET actor_id='principal_missing'`}, + {"orphan-selection", `UPDATE review_automatic_selections SET selection_id='review_selection_` + strings.Repeat("a", 32) + `'`}, + {"missing-credential", `UPDATE review_automatic_selections SET credential_id='credential_missing'`}, + {"wrong-target", `UPDATE review_automatic_selections SET pull_number=99`}, + {"future-control-revision", `UPDATE review_automatic_selections SET scheduling_revision=99`}, + {"blob-pause-reason", `UPDATE review_pull_scheduling SET reason=CAST(reason AS BLOB)`}, + {"blob-pause-actor", `UPDATE review_pull_scheduling SET actor_id=CAST(actor_id AS BLOB)`}, + {"blob-pause-time", `UPDATE review_pull_scheduling SET updated_at=CAST(updated_at AS BLOB)`}, + {"blob-control-time", `UPDATE review_scheduling SET updated_at=CAST(updated_at AS BLOB)`}, + {"blob-attribution-basis", `UPDATE review_automatic_selections SET basis_sha256=CAST(basis_sha256 AS BLOB)`}, + {"blob-attribution-settled", `UPDATE review_automatic_selections SET settled_basis_sha256=CAST(settled_basis_sha256 AS BLOB)`}, + {"blob-attribution-pull-basis", `UPDATE review_automatic_selections SET pull_basis_sha256=CAST(pull_basis_sha256 AS BLOB)`}, + {"invalid-basis", `UPDATE review_automatic_selections SET basis_sha256='` + strings.Repeat("z", 64) + `'`}, + } { + t.Run(tc.name, func(t *testing.T) { + copy := schedulingBundleCopy(t, bundle.Path) + mutateBundleSQL(t, copy, tc.query) + _, err := Inspect(t.Context(), copy) + backupCode(t, err, "backup_invalid") + dest := filepath.Join(t.TempDir(), "refused") + _, err = Restore(t.Context(), copy, dest) + backupCode(t, err, "backup_invalid") + if _, err := os.Stat(dest); !os.IsNotExist(err) { + t.Fatal("malformed scheduling created a restore destination", err) + } + }) + } + // A genuine predecessor may omit the entire optional domain. Startup adds + // empty controls only, never inferring enabled automation from old history. + old := schedulingBundleCopy(t, bundle.Path) + mutateBundleSQL(t, old, `DROP TABLE review_automatic_selections; DROP TABLE review_pull_scheduling; DROP TABLE review_scheduling; DELETE FROM metadata WHERE key='schema:review_scheduling'`) + if _, err := Inspect(t.Context(), old); err != nil { + t.Fatal("optional absent domain refused", err) + } + dest := filepath.Join(t.TempDir(), "old-inactive") + if _, err := Restore(t.Context(), old, dest); err != nil { + t.Fatal(err) + } + store, err := core.Open(t.Context(), dest) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err := reviewexec.EnsureSchema(t.Context(), store); err != nil { + t.Fatal(err) + } + var count int + if err := store.DB().QueryRow(`SELECT count(*) FROM review_scheduling`).Scan(&count); err != nil || count != 0 { + t.Fatal("old bundle startup enabled automation", count, err) + } +} + +func TestSchedulingCLIBackupAndV1Compatibility(t *testing.T) { + f, e, _ := schedulingBackupFixture(t) + one := int64(1) + on := true + if _, err := e.ConfigureScheduling(t.Context(), routePolicyInventoryScope(t, f), "enable-cli-backup", reviewexec.SchedulingRequest{ExpectedRevision: &one, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { + t.Fatal(err) + } + bundle := restoreBundle(t, f) + var err error + if _, err = Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal("CLI scheduling backup rejected", err) + } + old := schedulingBundleCopy(t, bundle.Path) + mutateBundleSQL(t, old, `ALTER TABLE review_scheduling DROP COLUMN automatic_cli; UPDATE metadata SET value='1' WHERE key='schema:review_scheduling'; UPDATE events SET payload_json='{"automatic_hosted":true}' WHERE event_type='review.scheduling_updated'`) + if _, err = Inspect(t.Context(), old); err != nil { + t.Fatal("v1 scheduling backup rejected", err) + } + dest := filepath.Join(t.TempDir(), "v1-inactive") + if _, err = Restore(t.Context(), old, dest); err != nil { + t.Fatal(err) + } + store, err := core.Open(t.Context(), dest) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err = reviewexec.EnsureSchema(t.Context(), store); err != nil { + t.Fatal(err) + } + var cli, hosted bool + if err = store.DB().QueryRow(`SELECT automatic_cli,automatic_hosted FROM review_scheduling WHERE project_id=?`, f.project).Scan(&cli, &hosted); err != nil || cli || !hosted { + t.Fatal("migration changed opt-in", cli, hosted, err) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index ecdbb3cf5..a11eb0e0e 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -46,6 +46,7 @@ type options struct { } type invocation struct { + reviewScheduling *reviewSchedulingInvocation ownerManagement *ownerManagementInvocation includeRetired bool ciWatch *ciWatchInvocation @@ -359,7 +360,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou if err != nil { return reportClientError(stderr, err, ctx) } - if call.reviewOperationControl != nil { + if call.reviewOperationControl != nil || call.reviewScheduling != nil && call.reviewScheduling.action != "read" { encoded, err := json.Marshal(value) if err == nil { encoded = append(encoded, '\n') @@ -413,6 +414,27 @@ func parseInvocation(args []string) (invocation, bool) { return call, false } call.command = remaining[0] + // Scheduling help is entirely local and has exact leaf grammar. + if len(remaining) >= 3 { + words := remaining + if words[0] == "help" { + words = words[1:] + } else if words[len(words)-1] == "--help" { + words = words[:len(words)-1] + } else { + words = nil + } + if len(words) == 2 || len(words) == 3 { + if words[0] == "reviews" && words[1] == "scheduling" { + name := strings.Join(words, " ") + if _, ok := operationHelp(name); ok { + call.operationHelp = name + return call, true + } + } + } + } + if len(remaining) == 2 && (remaining[1] == "help" || remaining[1] == "--help") && (call.command == "credentials" || call.command == "workers" || call.command == "reviews") { call.operationHelp = call.command + " help" return call, true diff --git a/internal/cli/operation_help.go b/internal/cli/operation_help.go index 533541c84..b9bffbfbd 100644 --- a/internal/cli/operation_help.go +++ b/internal/cli/operation_help.go @@ -15,6 +15,9 @@ type operationHelpResponse struct { } func emitOperationHelp(operation string, stdout, stderr io.Writer) int { + if help, ok := operationHelp(operation); ok { + return emit(stdout, stderr, help) + } if help, ok := ownerManagementHelp(operation); ok { return emit(stdout, stderr, help) } diff --git a/internal/cli/review_operation_control_test.go b/internal/cli/review_operation_control_test.go index 10e646dc5..02af3fd18 100644 --- a/internal/cli/review_operation_control_test.go +++ b/internal/cli/review_operation_control_test.go @@ -6,9 +6,12 @@ import ( "github.com/benhook1013/FireController/internal/cli" "github.com/benhook1013/FireController/internal/client" "github.com/benhook1013/FireController/internal/strictjson" + "io" "net/http" "net/http/httptest" + "reflect" "strings" + "sync/atomic" "testing" ) @@ -108,3 +111,77 @@ func TestReviewControlOutputFailureRetainsSameKeyRecovery(t *testing.T) { t.Fatal("same-key recovery changed effect", code, out, stderr) } } + +func TestReviewSchedulingCLIOutputFailureRetainsSameKeyRecovery(t *testing.T) { + for _, action := range []string{"configure", "pause", "resume"} { + for _, output := range []struct { + name string + writer io.Writer + }{{"failed", roundFailWriter{}}, {"short", shortMapOutput{}}} { + t.Run(action+"/"+output.name, func(t *testing.T) { + f, project, worker := reviewExecutionFixture(t) + var posts atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/scheduling") { + posts.Add(1) + if r.Header.Get("X-FC-Worker") != worker || r.Header.Get("X-FC-Instance") != f.store.InstanceID() || !strings.HasPrefix(r.URL.Path, "/api/v1/projects/"+project+"/") { + t.Error("scheduling mutation lost binding") + } + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"builder": {project, worker}}) + expected, revision := "0", int64(1) + if action == "resume" { + mutationSuccess(t, profiles, "builder", "reviews", "scheduling", "pause", "--pr", "2", "--expect-revision", "0", "--key", "prepare-paused-pull") + expected, revision = "1", 2 + posts.Store(0) + } + args := []string{"reviews", "scheduling", action, "--expect-revision", expected, "--key", "original-scheduling-key"} + state, id := "pull_scheduling_updated", "2" + switch action { + case "configure": + args = append(args, "--automatic-hosted", "true") + state, id = "scheduling_configured", project + case "pause", "resume": + args = append(args, "--pr", "2") + } + full := append([]string{"--profiles-file", profiles, "--profile", "builder"}, args...) + var diag strings.Builder + code := cli.RunContext(t.Context(), full, nil, output.writer, &diag) + var failure struct { + Error client.Error `json:"error"` + } + if code != cli.ExitConfig || json.Unmarshal([]byte(diag.String()), &failure) != nil || failure.Error.Code != "output_failed" || !failure.Error.OutcomeUnknown || !strings.Contains(failure.Error.Action, "exact same key, request and bound instance") || posts.Load() != 1 { + t.Fatal("committed scheduling output failure lost exact recovery or retried", code, diag.String(), posts.Load()) + } + code, out, stderr := mutationInvoke(t, profiles, "builder", args...) + var receipt client.ReviewRequestReceipt + if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &receipt) != nil || receipt.ID != id || receipt.State != state || receipt.Revision != revision || posts.Load() != 2 { + t.Fatal("exact recovery changed the scheduling effect", code, out, stderr, posts.Load()) + } + code, out, stderr = mutationInvoke(t, profiles, "builder", args...) + var replay client.ReviewRequestReceipt + if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &replay) != nil || !reflect.DeepEqual(receipt, replay) || posts.Load() != 3 { + t.Fatal("scheduling replay changed receipt", code, out, stderr) + } + }) + } + } +} + +func TestReviewSchedulingCLIReadOutputFailureDoesNotClaimMutation(t *testing.T) { + f, project, worker := reviewExecutionFixture(t) + server := httptest.NewServer(f.handler) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"builder": {project, worker}}) + for _, suffix := range [][]string{nil, {"read"}, {"read", "--pr", "2"}} { + args := append([]string{"--profiles-file", profiles, "--profile", "builder", "reviews", "scheduling"}, suffix...) + var diag strings.Builder + code := cli.RunContext(t.Context(), args, nil, roundFailWriter{}, &diag) + if code != cli.ExitConfig || !strings.Contains(diag.String(), "output_failed") || strings.Contains(diag.String(), "outcome_unknown") || strings.Contains(diag.String(), "same key") { + t.Fatal("read output failure gained mutation recovery semantics", code, diag.String()) + } + } +} diff --git a/internal/cli/review_scheduling.go b/internal/cli/review_scheduling.go new file mode 100644 index 000000000..2f9fa0ac5 --- /dev/null +++ b/internal/cli/review_scheduling.go @@ -0,0 +1,107 @@ +package cli + +import ( + "context" + "strconv" + "strings" + + "github.com/benhook1013/FireController/internal/client" +) + +type reviewSchedulingInvocation struct { + action string + pull int64 + key string + config client.ConfigureReviewSchedulingRequest + pause client.ConfigureReviewPullSchedulingRequest +} + +func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { + in := &reviewSchedulingInvocation{action: "read"} + if len(args) > 0 && !strings.HasPrefix(args[0], "--") { + in.action, args = args[0], args[1:] + } + allowed := map[string]bool{"--pr": true} + switch in.action { + case "read": + case "configure": + allowed = map[string]bool{"--automatic-hosted": true, "--automatic-cli": true, "--expect-revision": true, "--key": true} + case "pause", "resume": + allowed["--expect-revision"], allowed["--key"] = true, true + if in.action == "pause" { + allowed["--reason"] = true + } + default: + return nil, false + } + values := map[string]string{} + for i := 0; i < len(args); i++ { + flag, value, assigned := strings.Cut(args[i], "=") + if !allowed[flag] { + return nil, false + } + if _, exists := values[flag]; exists { + return nil, false + } + if !assigned { + i++ + if i >= len(args) { + return nil, false + } + value = args[i] + } + if value == "" && flag != "--reason" { + return nil, false + } + values[flag] = value + } + if value, exists := values["--pr"]; exists { + n, err := strconv.ParseInt(value, 10, 32) + if err != nil || n < 1 || strconv.FormatInt(n, 10) != value { + return nil, false + } + in.pull = n + } + if in.action == "read" { + return in, true + } + if !validMutationKey(values["--key"]) { + return nil, false + } + in.key = values["--key"] + revision, err := strconv.ParseInt(values["--expect-revision"], 10, 64) + if err != nil || strconv.FormatInt(revision, 10) != values["--expect-revision"] { + return nil, false + } + if in.action == "configure" { + value := values["--automatic-hosted"] + if value != "true" && value != "false" { + return nil, false + } + in.config = client.ConfigureReviewSchedulingRequest{ExpectedRevision: revision, AutomaticHosted: value == "true"} + if value, exists := values["--automatic-cli"]; exists { + if value != "true" && value != "false" { + return nil, false + } + enabled := value == "true" + in.config.AutomaticCLI = &enabled + } + return in, client.ValidateConfigureReviewScheduling(in.config) == nil + } + in.pause = client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: revision, Paused: in.action == "pause", Reason: values["--reason"]} + return in, client.ValidateConfigureReviewPullScheduling(in.pull, in.pause) == nil +} + +func executeReviewScheduling(ctx context.Context, service *client.Client, in *reviewSchedulingInvocation) (any, error) { + switch in.action { + case "configure": + return service.ConfigureReviewScheduling(ctx, in.key, in.config) + case "pause", "resume": + return service.ConfigureReviewPullScheduling(ctx, in.key, in.pull, in.pause) + default: + if in.pull != 0 { + return service.ReviewPullScheduling(ctx, in.pull) + } + return service.ReviewScheduling(ctx) + } +} diff --git a/internal/cli/review_scheduling_help.go b/internal/cli/review_scheduling_help.go new file mode 100644 index 000000000..15042837d --- /dev/null +++ b/internal/cli/review_scheduling_help.go @@ -0,0 +1,43 @@ +package cli + +func operationHelp(operation string) (operationHelpResponse, bool) { + recovery := "Use an explicit --key (1-128 printable ASCII bytes without surrounding whitespace). After uncertain output retry the same key, exact request and binding; never invent a replacement key." + out := operationHelpResponse{Required: []string{}, Optional: []string{}} + switch operation { + case "reviews scheduling": + out.Usage = " reviews scheduling [--pr N] | configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY | pause|resume --pr N --expect-revision N --key KEY [--reason TEXT]" + out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)", "configure --automatic-hosted true|false (project manager; authorizes future automatic Hosted requests)", "pause|resume --pr N (writer; holds new/undispatched reviews without changing rounds)", "--reason TEXT (optional with pause, at most 256 UTF-8 bytes)"} + out.Optional = append(out.Optional, "reviews scheduling read --help", "reviews scheduling configure --help", "reviews scheduling pause --help", "reviews scheduling resume --help") + out.Semantics = []string{"Automation defaults off. Enabling requires this connection's active bound worker and current project-management authority; CLI automation is separately opt-in via --automatic-cli; omission preserves its current value. Existing grants and taper remain unchanged.", "Pause can precede any intent. Existing provider review collection continues, and separate operation pauses remain in effect. Read the current revision; mutations require an explicit key and preserve original-key recovery.", "No live provider request is needed to read or change a PR pause. Enabling project automation authorizes later Hosted or CLI selection under all existing comparison, obligation, round and provider guards."} + out.Documentation = "docs/review-scheduling.md" + case "reviews scheduling read": + out.Usage = " reviews scheduling read [--pr N]" + out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)"} + out.Semantics = []string{"Returns stored scheduling state and its independent revision. Use the project revision for configure, or the selected PR revision for pause/resume. No provider request or writes."} + out.Example = " reviews scheduling read --pr 42" + out.Documentation = "docs/review-scheduling.md" + case "reviews scheduling configure": + out.Usage = " reviews scheduling configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY" + out.Required = []string{"--automatic-hosted true|false", "--expect-revision N (current project scheduling revision, including 0)", "--key KEY"} + out.Semantics = []string{"Requires project-management authority. Read reviews scheduling for the current project scheduling revision. Enabling authorizes future automatic Hosted or CLI requests through this connection's active bound worker under the existing review guards. Both default off; CLI omission preserves the current value. Automation does not adjudicate findings or increase grants.", recovery} + out.Optional = []string{"--automatic-cli true|false (separate opt-in; omission preserves the current CLI setting)"} + out.Example = " reviews scheduling configure --automatic-hosted true --expect-revision 0 --key automatic-hosted-1" + out.Documentation = "docs/review-scheduling.md" + case "reviews scheduling pause", "reviews scheduling resume": + out.Usage = " " + operation + " --pr N --expect-revision N --key KEY" + out.Required = []string{"--pr N", "--expect-revision N (current PR scheduling revision, including 0)", "--key KEY"} + out.Semantics = []string{"Requires project write access. Read reviews scheduling read --pr N for this PR's scheduling revision. Changes new/undispatched review scheduling in both channels; existing provider collection continues. Does not change rounds, channel closure or separate operation pauses.", recovery} + if operation == "reviews scheduling pause" { + out.Usage += " [--reason TEXT]" + out.Optional = []string{"--reason TEXT (optional, at most 256 UTF-8 bytes)"} + out.Semantics = append(out.Semantics, "May pause before the first review intent. No live provider request is needed to pause a PR.") + } else { + out.Semantics = append(out.Semantics, "Clears the PR pause and its reason. Accepts no --reason flag; does not resume separately paused operations or reopen closed channels.") + } + out.Example = " " + operation + " --pr 42 --expect-revision 0 --key scheduling-42-1" + out.Documentation = "docs/review-scheduling.md" + default: + return out, false + } + return out, true +} diff --git a/internal/cli/review_scheduling_test.go b/internal/cli/review_scheduling_test.go new file mode 100644 index 000000000..980d782d5 --- /dev/null +++ b/internal/cli/review_scheduling_test.go @@ -0,0 +1,144 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" +) + +func TestReviewSchedulingCLIExplicitControlsBeforeProfile(t *testing.T) { + for _, args := range [][]string{ + nil, {"--pr", "7"}, {"read", "--pr=7"}, + {"configure", "--automatic-hosted", "false", "--expect-revision", "0", "--key", "disable"}, + {"configure", "--automatic-hosted=true", "--expect-revision=3", "--key=enable"}, + {"pause", "--pr", "7", "--expect-revision", "0", "--reason", "Preparing changes", "--key", "pause"}, + {"resume", "--pr", "7", "--expect-revision", "1", "--key", "resume"}, + } { + call, ok := parseInvocation(append([]string{"reviews", "scheduling"}, args...)) + if !ok || call.reviewScheduling == nil || call.command != "reviews" { + t.Fatal("supported scheduling syntax refused", args, call, ok) + } + } + for _, args := range [][]string{ + {"configure", "--automatic-hosted", "true", "--key", "missing-revision"}, + {"configure", "--expect-revision", "0", "--key", "missing-explicit-bool"}, + {"configure", "--automatic-hosted", "yes", "--expect-revision", "0", "--key", "bad-bool"}, + {"configure", "--automatic-hosted", "true", "--expect-revision", "-1", "--key", "bad-revision"}, + {"--pr", "0"}, {"--pr", "07"}, {"--pr", "7", "--pr", "8"}, {"--key", "read-mutation"}, + {"pause", "--pr", "7", "--expect-revision", "0"}, + {"pause", "--pr", "7", "--expect-revision", "0", "--key", "bad-reason", "--reason", "line\nbreak"}, + {"pause", "--pr", "7", "--expect-revision", "0", "--key", "bad-reason", "--reason", strings.Repeat("x", 257)}, + {"resume", "--pr", "7", "--expect-revision", "1", "--key", "unexpected-reason", "--reason", "hidden"}, + {"configure", "--automatic-hosted", "true", "--expect-revision", "0", "--key", "foreign", "--worker", "other"}, + } { + var out, diag bytes.Buffer + code := RunContext(t.Context(), append([]string{"--profiles-file", "/missing", "reviews", "scheduling"}, args...), nil, &out, &diag) + if code != ExitUsage || out.Len() != 0 || !strings.Contains(diag.String(), "invalid_arguments") { + t.Fatal("invalid scheduling input reached profile/transport", args, code, out.String(), diag.String()) + } + } + var out, diag bytes.Buffer + if code := RunContext(t.Context(), []string{"--profiles-file", "/missing", "reviews", "scheduling", "--help"}, nil, &out, &diag); code != 0 || diag.Len() != 0 || !strings.Contains(out.String(), "docs/review-scheduling.md") || !strings.Contains(out.String(), "authorizes future") { + t.Fatal("scheduling help not usable offline", code, out.String(), diag.String()) + } +} + +func TestReviewSchedulingCLIOptionalAutomaticCLI(t *testing.T) { + base := []string{"configure", "--automatic-hosted=false", "--expect-revision=0", "--key=cli-setting"} + for _, value := range []string{"", "true", "false"} { + args := append([]string{}, base...) + if value != "" { + args = append(args, "--automatic-cli="+value) + } + in, ok := parseReviewScheduling(args) + if !ok || in.config.AutomaticHosted || (in.config.AutomaticCLI == nil) != (value == "") { + t.Fatalf("lost optional CLI state: %q %+v", value, in) + } + if value != "" && *in.config.AutomaticCLI != (value == "true") { + t.Fatal("wrong explicit CLI state") + } + } + for _, extra := range [][]string{{"--automatic-cli=yes"}, {"--automatic-cli="}, {"--automatic-cli"}, {"--automatic-cli=true", "--automatic-cli=false"}} { + if _, ok := parseReviewScheduling(append(append([]string{}, base...), extra...)); ok { + t.Fatal("accepted invalid CLI flag", extra) + } + } + if _, ok := parseReviewScheduling([]string{"configure", "--automatic-cli=true", "--expect-revision=0", "--key=missing-hosted"}); ok { + t.Fatal("Hosted flag must remain explicit") + } +} + +func TestReviewSchedulingLeafHelpIsOffline(t *testing.T) { + var requests atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { requests.Add(1) })) + defer service.Close() + path := filepath.Join(t.TempDir(), "profiles.json") + private := []byte("PRIVATE_INVALID_PROFILE") + if err := os.WriteFile(path, private, 0600); err != nil { + t.Fatal(err) + } + for _, leaf := range []string{"read", "configure", "pause", "resume"} { + for _, spelling := range [][]string{{"reviews", "scheduling", leaf, "--help"}, {"help", "reviews", "scheduling", leaf}} { + for _, profilePath := range []string{path, filepath.Join(t.TempDir(), "absent.json")} { + args := append([]string{"--profiles-file", profilePath, "--profile", "bound"}, spelling...) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + var stdout, stderr bytes.Buffer + code := RunContext(ctx, args, map[string]string{"FC_SERVER": service.URL}, &stdout, &stderr) + var help operationHelpResponse + if code != ExitSuccess || stderr.Len() != 0 || stdout.Len() > 2500 || json.Unmarshal(stdout.Bytes(), &help) != nil || !strings.HasPrefix(help.Usage, " reviews scheduling "+leaf) || help.Documentation != "docs/review-scheduling.md" { + t.Fatalf("%v: code=%d stdout=%s stderr=%s", args, code, &stdout, &stderr) + } + if leaf != "read" && (!strings.Contains(help.Usage, "--expect-revision N --key KEY") || !strings.Contains(strings.Join(help.Semantics, " "), "same key, exact request")) { + t.Fatal("mutation help omitted revision/key recovery", leaf, help) + } + if leaf == "pause" && !strings.Contains(help.Usage, "[--reason TEXT]") || leaf == "resume" && strings.Contains(help.Usage, "--reason") { + t.Fatal("pause/resume reason syntax drifted", help) + } + if call, ok := parseInvocation(strings.Fields(strings.TrimPrefix(help.Example, " "))); !ok || call.command == "help" || call.reviewScheduling == nil || call.reviewScheduling.action != leaf { + t.Fatal("help example does not select its real scheduling operation", leaf, call, ok) + } + } + } + } + if requests.Load() != 0 { + t.Fatal("help contacted a server") + } + if after, err := os.ReadFile(path); err != nil || !bytes.Equal(after, private) { + t.Fatal("help changed selected configuration", err) + } + parent, _ := operationHelp("reviews scheduling") + for _, leaf := range []string{"read", "configure", "pause", "resume"} { + if !strings.Contains(strings.Join(parent.Optional, " "), "reviews scheduling "+leaf+" --help") { + t.Fatal("parent help does not discover leaf", leaf) + } + } +} + +func TestReviewSchedulingLeafHelpKeepsExactGrammar(t *testing.T) { + for _, args := range [][]string{ + {"reviews", "scheduling", "resume", "--help", "extra"}, + {"reviews", "scheduling", "pause", "--help", "--pr", "42"}, + {"reviews", "scheduling", "configure", "--help=true"}, + {"reviews", "scheduling", "read", "--pr", "42", "--help"}, + {"help", "reviews", "scheduling", "unknown"}, + {"help", "reviews", "scheduling", "resume", "--key", "help-is-not-a-write"}, + {"reviews", "scheduling", "resume", "--help", "--profile=a", "--profile=b"}, + } { + var stdout, stderr bytes.Buffer + if code := RunContext(t.Context(), args, nil, &stdout, &stderr); code != ExitUsage || stdout.Len() != 0 || !strings.Contains(stderr.String(), "invalid_arguments") { + t.Fatalf("%v: code=%d stdout=%s stderr=%s", args, code, &stdout, &stderr) + } + } + call, ok := parseInvocation([]string{"reviews", "scheduling", "pause", "--pr", "42", "--expect-revision", "0", "--key", "pause-1", "--reason", "--help"}) + if !ok || call.command == "help" || call.reviewScheduling == nil || call.reviewScheduling.pause.Reason != "--help" { + t.Fatal("help-looking reason was treated as local help", call, ok) + } +} diff --git a/internal/cli/reviews.go b/internal/cli/reviews.go index 7b375d63f..e219cae48 100644 --- a/internal/cli/reviews.go +++ b/internal/cli/reviews.go @@ -16,6 +16,11 @@ func parseReview(call invocation, args []string) (invocation, bool) { call.reviewOperationControl, ok = parseReviewOperationControl(args) return call, ok } + if call.subcommand == "scheduling" { + var ok bool + call.reviewScheduling, ok = parseReviewScheduling(args) + return call, ok + } if call.subcommand == "ci-wait" { var ok bool call.ciWatch, ok = parseCIWatch(args) @@ -158,6 +163,9 @@ func reviewID(value, prefix string) bool { } func executeReview(ctx context.Context, service *client.Client, call invocation) (any, error) { + if call.reviewScheduling != nil { + return executeReviewScheduling(ctx, service, call.reviewScheduling) + } if call.ciWatch != nil { value, err := service.WatchCI(ctx, call.ciWatch.targets, call.ciWatch.seconds) return client.AgentCIWatch(value), err diff --git a/internal/client/client.go b/internal/client/client.go index 73466d8fe..5be309021 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -474,8 +474,9 @@ func (c *Client) requestWithCapabilities(ctx context.Context, method string, seg defer response.Body.Close() if wait != nil && wait.queuedCause != nil { *wait.queuedCause = "" - if response.Header.Get("X-FC-Review-Queued") == "cli_quota_wait" { - *wait.queuedCause = "cli_quota_wait" + switch cause := response.Header.Get("X-FC-Review-Queued"); cause { + case "cli_quota_wait", "pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained": + *wait.queuedCause = cause } } if response.StatusCode >= 300 && response.StatusCode < 400 { diff --git a/internal/client/review_agent_output.go b/internal/client/review_agent_output.go index 56cf67258..0da3bbc4c 100644 --- a/internal/client/review_agent_output.go +++ b/internal/client/review_agent_output.go @@ -21,6 +21,9 @@ func draftReadinessDiagnostic() *ReviewOperationDiagnostic { } func selectionSourceDiagnostic(reason string) *ReviewOperationDiagnostic { + if hint := schedulingDiagnostic(reason); hint != nil { + return hint + } if reason == "pull_draft" { return draftReadinessDiagnostic() } @@ -45,6 +48,9 @@ func selectionSourceDiagnostic(reason string) *ReviewOperationDiagnostic { default: return nil } + if reason == "source_budget_exhausted" || reason == "source_fetch_timeout" || reason == "source_provider_unavailable" { + return &ReviewOperationDiagnostic{explanation, "An explicit held selection is terminal and has no child operation; after addressing the source issue, if the review remains authorized, use one fresh reviews start / review_start with a new key and current configuration. Its old key replays the hold. An eligible automatic selection may recover on its original identity after at least thirty seconds, subject to its retained retry budget, unchanged authorization and normal admission checks. Preserve the original selection while automatic recovery remains eligible; this diagnostic does not establish eligibility or promise an exact retry time. Keep pending selections and selected child operations on their original identities. No round reset or extra grant is needed."} + } return &ReviewOperationDiagnostic{explanation, "This held selection is terminal and has no child operation. After addressing the source issue, if the review remains authorized, use one fresh reviews start / review_start with a new key and current configuration. The old key replays this hold. Keep pending selections and selected child operations on their original identities. No round reset or extra grant is needed; normal front, source and provider checks still apply."} } @@ -66,6 +72,14 @@ type ReviewOperationStatusOutput struct { } func retainedWaitDiagnostic(wait *ReviewOperationWait, channel, state, reason, queuedCause string) *ReviewOperationDiagnostic { + if state == "queued" { + if hint := schedulingDiagnostic(queuedCause); hint != nil { + return hint + } + } + if hint := agentReviewOperationDiagnostic(channel, state, reason); hint != nil { + return hint + } if wait != nil { if diagnostic := operationWaitDiagnostic(wait, channel); diagnostic != nil { return diagnostic @@ -113,3 +127,12 @@ func operationWaitDiagnostic(w *ReviewOperationWait, channel string) *ReviewOper } return nil } + +func agentReviewOperationDiagnostic(channel, state, reason string) *ReviewOperationDiagnostic { + // Queued reasons can outlive a resumed pause; only the current queued cause + // can establish a scheduling hold. Held operations retain their own reason. + if state == "held" { + return schedulingDiagnostic(reason) + } + return nil +} diff --git a/internal/client/review_agent_output_test.go b/internal/client/review_agent_output_test.go index c3ed74e66..59a5c1a80 100644 --- a/internal/client/review_agent_output_test.go +++ b/internal/client/review_agent_output_test.go @@ -26,6 +26,9 @@ func TestAgentSelectionSourceHoldIsBoundedAndNeverReplacesChild(t *testing.T) { continue } phrases := []string{"terminal and has no child", "After addressing", "if the review remains authorized", "new key and current configuration", "old key replays", "pending selections and selected child", "No round reset or extra grant"} + if reason == "source_budget_exhausted" || reason == "source_fetch_timeout" || reason == "source_provider_unavailable" { + phrases = []string{"An explicit held selection is terminal", "if the review remains authorized", "new key and current configuration", "old key replays", "eligible automatic selection may recover on its original identity", "after at least thirty seconds", "retained retry budget", "unchanged authorization", "Preserve the original selection", "does not establish eligibility or promise an exact retry time", "No round reset or extra grant"} + } if reason == "pull_draft" { phrases = []string{"After marking the PR ready for review", "if this review remains authorized", "new key and current configuration/head", "old key replays this terminal hold", "Do not reset rounds, grant extra reviews or retry automatically", "normal admission and provider checks"} for _, phrase := range []string{"GitHub Draft", "initial review readiness", "does not erase earned review progress"} { diff --git a/internal/client/review_scheduling.go b/internal/client/review_scheduling.go new file mode 100644 index 000000000..efecb7d58 --- /dev/null +++ b/internal/client/review_scheduling.go @@ -0,0 +1,184 @@ +package client + +import ( + "context" + "encoding/json" + "github.com/benhook1013/FireController/internal/strictjson" + "math" + "net/http" + "strconv" + "time" + "unicode" + "unicode/utf8" +) + +type ReviewScheduling struct { + ProjectID string `json:"project_id"` + Revision int64 `json:"revision"` + AutomaticCLI bool `json:"automatic_cli"` + AutomaticHosted bool `json:"automatic_hosted"` + PausedPulls []ReviewPullScheduling `json:"paused_pulls"` + AuthorizingWorkerID string `json:"authorizing_worker_id,omitempty"` + UpdatedAt string `json:"updated_at,omitempty"` + Reason string `json:"reason,omitempty"` +} + +type ReviewPullScheduling 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 ConfigureReviewSchedulingRequest struct { + ExpectedRevision int64 `json:"expected_revision"` + AutomaticHosted bool `json:"automatic_hosted"` + AutomaticCLI *bool `json:"automatic_cli,omitempty"` +} + +type ConfigureReviewPullSchedulingRequest struct { + ExpectedRevision int64 `json:"expected_revision"` + Paused bool `json:"paused"` + Reason string `json:"reason,omitempty"` +} + +func validSchedulingRevision(revision int64) bool { return revision >= 0 && revision < math.MaxInt64 } +func validSchedulingTime(value string) bool { + if len(value) > 64 { + return false + } + at, err := time.Parse(time.RFC3339Nano, value) + return err == nil && !at.IsZero() +} +func validSchedulingReason(reason string) bool { + if len(reason) > 256 || !utf8.ValidString(reason) { + return false + } + for _, r := range reason { + if unicode.IsControl(r) { + return false + } + } + return true +} + +func ValidateConfigureReviewScheduling(input ConfigureReviewSchedulingRequest) error { + if !validSchedulingRevision(input.ExpectedRevision) { + return mutationValidation() + } + return nil +} + +func ValidateConfigureReviewPullScheduling(pull int64, input ConfigureReviewPullSchedulingRequest) error { + if !validPullNumber(pull) || !validSchedulingRevision(input.ExpectedRevision) || !validSchedulingReason(input.Reason) { + return mutationValidation() + } + return nil +} + +func validPullScheduling(value ReviewPullScheduling, project string, pull int64) bool { + if value.ProjectID != project || value.PullNumber != pull || !validPullNumber(pull) || value.Revision < 0 || !validSchedulingReason(value.Reason) || !value.Paused && value.Reason != "" { + return false + } + if value.Revision == 0 { + return !value.Paused && value.Reason == "" && value.ActorID == "" && value.UpdatedAt == "" + } + return validID(value.ActorID) && validSchedulingTime(value.UpdatedAt) +} + +// Older services omit automatic_cli. Accept that as off while always emitting +// an explicit boolean in CLI/MCP output, including after an enabled read. +func decodeReviewSchedulingResponse(data []byte, dst any) error { + if err := strictjson.Decode(data, dst); err != nil { + return err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil || fields == nil { + return strictjson.ErrSyntax + } + if _, present := fields["automatic_cli"]; !present { + fields["automatic_cli"] = json.RawMessage("false") + var err error + data, err = json.Marshal(fields) + if err != nil { + return err + } + } + if !completeShape(data, dst) { + return strictjson.ErrSyntax + } + return nil +} + +func (c *Client) ReviewScheduling(ctx context.Context) (ReviewScheduling, error) { + // Allow 100 paused pulls, including six-byte JSON escaping of each + // 256-byte reason and bounded identities, plus the response envelope. + var value ReviewScheduling + if err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "scheduling"), nil, true, "", nil, http.StatusOK, false, &value, 512<<10, decodeReviewSchedulingResponse); err != nil { + return ReviewScheduling{}, err + } + if value.ProjectID != c.identity.ProjectID || value.Revision < 0 || value.PausedPulls == nil || len(value.PausedPulls) > 100 || value.Reason != "" && !safeCode(value.Reason) || value.AuthorizingWorkerID != "" && !validID(value.AuthorizingWorkerID) { + return ReviewScheduling{}, invalidResponse() + } + if value.Revision == 0 { + if value.AutomaticHosted || value.AutomaticCLI || value.AuthorizingWorkerID != "" || value.UpdatedAt != "" || value.Reason != "" { + return ReviewScheduling{}, invalidResponse() + } + } else if !validSchedulingTime(value.UpdatedAt) || (value.AutomaticHosted || value.AutomaticCLI) && value.AuthorizingWorkerID == "" { + return ReviewScheduling{}, invalidResponse() + } + seen := make(map[int64]bool, len(value.PausedPulls)) + for _, item := range value.PausedPulls { + if !item.Paused || seen[item.PullNumber] || !validPullScheduling(item, c.identity.ProjectID, item.PullNumber) { + return ReviewScheduling{}, invalidResponse() + } + seen[item.PullNumber] = true + } + return value, nil +} + +func (c *Client) ConfigureReviewScheduling(ctx context.Context, key string, input ConfigureReviewSchedulingRequest) (ReviewRequestReceipt, error) { + if !validMutationKey(key) || ValidateConfigureReviewScheduling(input) != nil { + return ReviewRequestReceipt{}, mutationValidation() + } + var receipt ReviewRequestReceipt + if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "scheduling"), key, input, http.StatusOK, &receipt); err != nil { + return receipt, err + } + if receipt.ID != c.identity.ProjectID || receipt.State != "scheduling_configured" || receipt.Revision != input.ExpectedRevision+1 { + return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The scheduling receipt was invalid; retain the original key and request.", http.StatusOK) + } + return receipt, nil +} + +func (c *Client) ReviewPullScheduling(ctx context.Context, pull int64) (ReviewPullScheduling, error) { + if !validPullNumber(pull) { + return ReviewPullScheduling{}, validation() + } + var value ReviewPullScheduling + if err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "pulls", strconv.FormatInt(pull, 10), "scheduling"), nil, true, "", nil, http.StatusOK, false, &value, 4<<10, decodeResponse); err != nil { + return ReviewPullScheduling{}, err + } + if !validPullScheduling(value, c.identity.ProjectID, pull) { + return ReviewPullScheduling{}, invalidResponse() + } + return value, nil +} + +func (c *Client) ConfigureReviewPullScheduling(ctx context.Context, key string, pull int64, input ConfigureReviewPullSchedulingRequest) (ReviewRequestReceipt, error) { + if !validMutationKey(key) || ValidateConfigureReviewPullScheduling(pull, input) != nil { + return ReviewRequestReceipt{}, mutationValidation() + } + var receipt ReviewRequestReceipt + id := strconv.FormatInt(pull, 10) + if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "pulls", id, "scheduling"), key, input, http.StatusOK, &receipt); err != nil { + return receipt, err + } + if receipt.ID != id || receipt.State != "pull_scheduling_updated" || receipt.Revision != input.ExpectedRevision+1 { + return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The PR scheduling receipt was invalid; retain the original key and request.", http.StatusOK) + } + return receipt, nil +} diff --git a/internal/client/review_scheduling_diagnostic.go b/internal/client/review_scheduling_diagnostic.go new file mode 100644 index 000000000..cfe1b600a --- /dev/null +++ b/internal/client/review_scheduling_diagnostic.go @@ -0,0 +1,13 @@ +package client + +func schedulingDiagnostic(reason string) *ReviewOperationDiagnostic { + switch reason { + case "pull_scheduling_paused": + return &ReviewOperationDiagnostic{"New reviews are paused for this PR; this is separate from an individual operation pause. Already issued reviews can still be collected.", "Read review_pull_scheduling_read / reviews scheduling read --pr N. Resume the PR only when authorized. Existing queued work retains its identity and any separate operation pause; a terminal held operation does not resume. Do not reset rounds or grant more reviews to clear this pause."} + case "automation_authorization_changed": + return &ReviewOperationDiagnostic{"Automatic scheduling for this channel is off, its authorization was interrupted, or its retained authorizer no longer has the required access. This retained selection/request cannot authorize provider work.", "Read review_scheduling_read / reviews scheduling. Re-enabling scheduling does not resume an operation whose channel authorization was interrupted. Inspect this retained operation before making a new authorized request. An authorized project manager can deliberately enable scheduling for new work with its current credential and active bound worker. Keep existing issued work on its original identity; do not switch another worker's credentials or reset rounds."} + case "automatic_intent_retained": + return &ReviewOperationDiagnostic{"An automatic review intent already exists for these same review facts; this selection did not create another provider request.", "Inspect existing scoped operations if needed. Ticks and observation refreshes do not restart cancelled, failed or held intent. Use a PR pause to prevent new scheduling across later meaningful changes. A separate explicit request still needs normal authorization and admission."} + } + return nil +} diff --git a/internal/client/review_scheduling_diagnostic_test.go b/internal/client/review_scheduling_diagnostic_test.go new file mode 100644 index 000000000..745f3fd33 --- /dev/null +++ b/internal/client/review_scheduling_diagnostic_test.go @@ -0,0 +1,105 @@ +package client + +import ( + "reflect" + "strings" + "testing" +) + +func TestSchedulingDiagnosticsPreserveRetainedFacts(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { + v := ReviewOperationStatus{ID: "original", State: "held", Stage: "held", Reason: reason, Channel: "hosted", Revision: 3, NextAction: "read_diagnostics"} + out := AgentReviewOperationStatus(v) + if out.Diagnostic == nil || !reflect.DeepEqual(out.ReviewOperationStatus, v) || selectionSourceDiagnostic(reason) == nil { + t.Fatal("missing scheduling diagnostic or changed original facts", reason) + } + if agentReviewOperationDiagnostic("hosted", "active", reason) != nil { + t.Fatal("issued work gained scheduling refusal", reason) + } + } + if schedulingDiagnostic("unknown") != nil { + t.Fatal("invented scheduling refusal") + } +} + +func TestSchedulingDiagnosticsDoNotMislabelCLIAsHosted(t *testing.T) { + for _, reason := range []string{"automation_authorization_changed", "automatic_intent_retained"} { + value := AgentReviewOperationStatus(ReviewOperationStatus{State: "held", Stage: "held", Reason: reason, Channel: "cli", Revision: 1}) + if value.Diagnostic == nil || strings.Contains(value.Diagnostic.Explanation, "Hosted") { + t.Fatal("CLI refusal was attributed to the other channel", value) + } + } +} + +func TestQueuedSchedulingDiagnosticsUseCurrentCause(t *testing.T) { + const due = "2026-11-11T12:00:00Z" + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { + for _, channel := range []string{"cli", "hosted"} { + for _, tc := range []struct { + name, cause, explanation, action string + wait *ReviewOperationWait + }{ + {name: "awaiting_scheduler", cause: "awaiting_scheduler"}, + {name: "queue_order", cause: "queue_order"}, + {name: "absent_cause"}, + {name: "unknown_cause", cause: "unknown"}, + {name: "cooldown", cause: "cooldown", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, + {name: "queue_order_with_timer", cause: "queue_order", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, + {name: "quota_with_timer", cause: "cli_quota_wait", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, + {name: "operation_pause", cause: "operation_paused", wait: &ReviewOperationWait{Paused: true}, explanation: "no retry deadline is recorded", action: "Resume/cancel only this undispatched operation"}, + {name: "operation_pause_with_timer", cause: "operation_paused", wait: &ReviewOperationWait{Paused: true, RetryNotBefore: due}, explanation: "paused before", action: "Resume"}, + {name: "current_pr_pause", cause: "pull_scheduling_paused", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "New reviews are paused for this PR", action: "Resume the PR only when authorized"}, + {name: "current_authorization_hold", cause: "automation_authorization_changed", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "Automatic scheduling for this channel is off", action: "An authorized project manager"}, + {name: "current_retained_intent", cause: "automatic_intent_retained", explanation: "An automatic review intent already exists", action: "Inspect existing scoped operations"}, + {name: "quota_without_timer", cause: "cli_quota_wait"}, + } { + t.Run(channel+"/"+reason+"/"+tc.name, func(t *testing.T) { + explanation, action := tc.explanation, tc.action + if tc.name == "quota_without_timer" && channel == "cli" { + explanation, action = "queued for shared CLI quota rechecks", "Keep this original request queued" + } + operation := ReviewOperation{ID: "original", State: "queued", Reason: reason, Channel: channel, Revision: 3, Wait: tc.wait, queuedCause: tc.cause} + status := ReviewOperationStatus{ID: operation.ID, State: operation.State, Stage: "queued", Reason: reason, Channel: channel, Revision: operation.Revision, Wait: tc.wait, queuedCause: tc.cause, NextAction: "wait"} + full, compact := AgentReviewOperation(operation), AgentReviewOperationStatus(status) + if !reflect.DeepEqual(full.ReviewOperation, operation) || !reflect.DeepEqual(compact.ReviewOperationStatus, status) || !reflect.DeepEqual(full.Diagnostic, compact.Diagnostic) { + t.Fatal("wrappers changed retained facts or disagree", full, compact) + } + if explanation == "" { + if full.Diagnostic != nil { + t.Fatal("historical reason invented a current scheduling hold", full.Diagnostic) + } + return + } + if full.Diagnostic == nil || !strings.Contains(full.Diagnostic.Explanation, explanation) || !strings.Contains(full.Diagnostic.NextAction, action) { + t.Fatal("current cause or retained operation wait guidance was masked", explanation, action, full.Diagnostic) + } + }) + } + } + } +} + +func TestHeldSchedulingDiagnosticsIgnoreQueuedCause(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { + operation := ReviewOperation{State: "held", Channel: channel, Reason: reason, queuedCause: "cooldown"} + status := ReviewOperationStatus{State: "held", Stage: "held", Channel: channel, Reason: reason, queuedCause: "cooldown", NextAction: "read_diagnostics"} + full, compact := AgentReviewOperation(operation), AgentReviewOperationStatus(status) + if !reflect.DeepEqual(full.Diagnostic, schedulingDiagnostic(reason)) || !reflect.DeepEqual(compact.Diagnostic, full.Diagnostic) || !reflect.DeepEqual(full.ReviewOperation, operation) || !reflect.DeepEqual(compact.ReviewOperationStatus, status) { + t.Fatal("held scheduling guidance or retained facts changed", full, compact) + } + } + } +} + +func TestSchedulingDiagnosticExplainsInterruptedAuthorization(t *testing.T) { + diagnostic := schedulingDiagnostic("automation_authorization_changed") + for _, want := range []string{"Re-enabling scheduling does not resume", "Inspect this retained operation", "new authorized request", "original identity"} { + if diagnostic == nil || !strings.Contains(diagnostic.NextAction, want) { + t.Fatalf("missing continuity guidance %q: %+v", want, diagnostic) + } + } + if strings.Contains(diagnostic.Explanation, "Automatic Hosted") { + t.Fatal("shared authorization diagnostic excluded CLI") + } +} diff --git a/internal/client/review_scheduling_test.go b/internal/client/review_scheduling_test.go new file mode 100644 index 000000000..8c3b008d1 --- /dev/null +++ b/internal/client/review_scheduling_test.go @@ -0,0 +1,434 @@ +package client_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "math" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviews" +) + +func TestReviewSchedulingClientActualHTTPControlsDoNotStartWork(t *testing.T) { + f := newMutationFixture(t) + for _, ensure := range []func() error{ + func() error { return reviewexec.EnsureSchema(t.Context(), f.store) }, + func() error { return reviews.EnsureSchema(t.Context(), f.store) }, + } { + if err := ensure(); err != nil { + t.Fatal(err) + } + } + e, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "scheduling-client", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + e.Register(mux) + f.handler = mux + var requests atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests.Add(1); f.handler.ServeHTTP(w, r) })) + defer service.Close() + grant := func(token string, permissions []string) string { + sum := sha256.Sum256([]byte(token)) + return f.call(t, "POST", "/api/v1/projects/"+f.project+"/credentials", f.admin, f.sender, map[string]any{"token_sha256": hex.EncodeToString(sum[:]), "permissions": permissions})["id"].(string) + } + const ownerToken = "synthetic-scheduling-owner" + ownerID := grant(ownerToken, []string{"manage"}) + grant("synthetic-scheduling-writer", []string{"read", "write"}) + grant("synthetic-scheduling-reader", []string{"read"}) + owner := f.newClient(t, ownerToken, f.sender, service.URL) + writer := f.newClient(t, "synthetic-scheduling-writer", f.sender, service.URL) + reader := f.newClient(t, "synthetic-scheduling-reader", f.sender, service.URL) + providerCalls := f.providerCalls.Load() + initial, err := reader.ReviewScheduling(t.Context()) + if err != nil || initial.Revision != 0 || initial.AutomaticHosted || initial.PausedPulls == nil || len(initial.PausedPulls) != 0 || initial.Reason != "" { + t.Fatal(initial, err) + } + pull, err := reader.ReviewPullScheduling(t.Context(), 2) + if err != nil || pull.Revision != 0 || pull.Paused || pull.ProjectID != f.project || pull.PullNumber != 2 { + t.Fatal(pull, err) + } + paused := client.ConfigureReviewPullSchedulingRequest{Paused: true, Reason: "Fix in progress"} + first, err := writer.ConfigureReviewPullScheduling(t.Context(), "pause-before-intent", 2, paused) + if err != nil || first.ID != "2" || first.Revision != 1 { + t.Fatal(first, err) + } + replay, err := writer.ConfigureReviewPullScheduling(t.Context(), "pause-before-intent", 2, paused) + if err != nil || !reflect.DeepEqual(first, replay) { + t.Fatal("pause replay changed", first, replay, err) + } + _, err = writer.ConfigureReviewPullScheduling(t.Context(), "stale-pause", 2, paused) + checkError(t, err, "review_conflict") + _, err = reader.ConfigureReviewPullScheduling(t.Context(), "reader-pause", 2, paused) + checkError(t, err, "forbidden") + _, err = writer.ConfigureReviewPullScheduling(t.Context(), "pause-outside-queue", 99, paused) + if err != nil { + t.Fatal(err) + } + configuration := client.ConfigureReviewExecutionRequest{CapabilityID: "scheduling-client", Mode: "independent", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}} + f.call(t, "POST", "/api/v1/projects/"+f.project+"/reviews/execution/configuration", f.admin, f.sender, configuration) + before := requests.Load() + filtered, err := reader.ReviewScheduling(t.Context()) + if err != nil || requests.Load() != before+1 || len(filtered.PausedPulls) != 1 || filtered.PausedPulls[0].PullNumber != 2 || !filtered.PausedPulls[0].Paused || filtered.PausedPulls[0].Reason != paused.Reason { + t.Fatal("project GET lost queue-filtered pauses or added per-PR requests", filtered, err) + } + enable := client.ConfigureReviewSchedulingRequest{AutomaticHosted: true} + _, err = writer.ConfigureReviewScheduling(t.Context(), "writer-enable", enable) + checkError(t, err, "forbidden") + enabled, err := owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) + if err != nil || enabled.ID != f.project || enabled.Revision != 1 { + t.Fatal(enabled, err) + } + again, err := owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) + if err != nil || !reflect.DeepEqual(enabled, again) { + t.Fatal("enable replay changed", again, err) + } + _, err = owner.ConfigureReviewScheduling(t.Context(), "stale-enable", enable) + checkError(t, err, "review_conflict") + current, err := reader.ReviewScheduling(t.Context()) + if err != nil || !current.AutomaticHosted || current.Revision != 1 || current.AuthorizingWorkerID != f.sender || current.Reason != "" { + t.Fatal(current, err) + } + _, err = writer.ConfigureReviewPullScheduling(t.Context(), "writer-resume", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: 1, Paused: false, Reason: "discard on resume"}) + if err != nil { + t.Fatal(err) + } + resumed, err := reader.ReviewPullScheduling(t.Context(), 2) + if err != nil || resumed.Paused || resumed.Revision != 2 || resumed.Reason != "" { + t.Fatal(resumed, err) + } + if _, err := f.store.DB().Exec(`UPDATE credentials SET revoked=1 WHERE id=?`, ownerID); err != nil { + t.Fatal(err) + } + withdrawn, err := reader.ReviewScheduling(t.Context()) + if err != nil || !withdrawn.AutomaticHosted || withdrawn.Reason != "authorizer_unavailable" || withdrawn.AuthorizingWorkerID != f.sender || len(withdrawn.PausedPulls) != 0 { + t.Fatal("withdrawn original authorization was not reported truthfully", withdrawn, err) + } + _, err = owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) + checkError(t, err, "unauthorized") + for _, table := range []string{"review_operations", "review_execution_attempts", "review_execution_reservations", "review_execution_evidence", "review_round_completions", "review_selections", "review_automatic_selections"} { + var count int + if err := f.store.DB().QueryRow(`SELECT count(*) FROM ` + table).Scan(&count); err != nil || count != 0 { + t.Fatal("settings handler started or credited review work", table, count, err) + } + } + if f.providerCalls.Load() != providerCalls { + t.Fatal("settings/read/pause contacted a provider") + } +} + +func TestReviewSchedulingClientRejectsMalformedWireAndKeepsUnknownMutationsSingleShot(t *testing.T) { + var response atomic.Value + response.Store(`{"project_id":"project-one","revision":0,"automatic_hosted":false,"paused_pulls":[]}`) + var calls atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + calls.Add(1) + w.Header().Set("Content-Type", "application/json") + if r.Method == "POST" { + body, _ := io.ReadAll(r.Body) + want := `{"expected_revision":0,"automatic_hosted":true}` + if strings.Contains(r.URL.Path, "/pulls/2/") { + want = `{"expected_revision":0,"paused":true}` + } + if r.Header.Get("Idempotency-Key") != "original-scheduling-key" || r.Header.Get("X-FC-Worker") != "worker-one" || r.Header.Get("X-FC-Instance") != "instance-one" || string(body) != want { + t.Error("mutation lost original key/body/binding") + } + } + _, _ = io.WriteString(w, response.Load().(string)) + })) + defer service.Close() + c := newClient(t, service) + defaultProject := map[string]any{"project_id": "project-one", "revision": 0, "automatic_hosted": false, "paused_pulls": []any{}} + validPaused := map[string]any{"project_id": "project-one", "pull_number": 2, "revision": 1, "paused": true, "reason": "Fixing", "actor_id": "actor-one", "updated_at": "2026-11-01T00:00:00Z"} + // Exhausted stored revisions remain readable; only another increment is + // invalid. Keep the largest legitimate native int64 exact on the wire. + maxProject := map[string]any{} + for key, value := range defaultProject { + maxProject[key] = value + } + maxProject["revision"], maxProject["updated_at"] = int64(math.MaxInt64), "2026-11-01T00:00:00Z" + encoded, _ := json.Marshal(maxProject) + response.Store(string(encoded)) + projectAtLimit, err := c.ReviewScheduling(t.Context()) + if err != nil || projectAtLimit.Revision != math.MaxInt64 { + t.Fatal("exhausted project revision became unreadable", projectAtLimit, err) + } + maxPull := map[string]any{} + for key, value := range validPaused { + maxPull[key] = value + } + maxPull["revision"] = int64(math.MaxInt64) + encoded, _ = json.Marshal(maxPull) + response.Store(string(encoded)) + pullAtLimit, err := c.ReviewPullScheduling(t.Context(), 2) + if err != nil || pullAtLimit.Revision != math.MaxInt64 { + t.Fatal("exhausted PR revision became unreadable", pullAtLimit, err) + } + for _, tc := range []struct { + name string + change func(map[string]any) + }{ + {"project-binding", func(v map[string]any) { v["project_id"] = "another-project" }}, + {"missing-paused-array", func(v map[string]any) { delete(v, "paused_pulls") }}, + {"null-paused-array", func(v map[string]any) { v["paused_pulls"] = nil }}, + {"duplicate-paused", func(v map[string]any) { v["paused_pulls"] = []any{validPaused, validPaused} }}, + {"default-enabled", func(v map[string]any) { v["automatic_hosted"] = true }}, + {"default-dated", func(v map[string]any) { v["updated_at"] = "2026-11-01T00:00:00Z" }}, + {"negative-revision", func(v map[string]any) { v["revision"] = -1 }}, + {"fractional-revision", func(v map[string]any) { v["revision"] = 1.5 }}, + {"bad-date", func(v map[string]any) { v["revision"] = 1; v["updated_at"] = "PRIVATE_INVALID_DATE" }}, + {"zero-date", func(v map[string]any) { v["revision"] = 1; v["updated_at"] = "0001-01-01T00:00:00Z" }}, + {"oversized-date", func(v map[string]any) { + v["revision"] = 1 + v["updated_at"] = "2026-11-01T00:00:00." + strings.Repeat("1", 50) + "Z" + }}, + } { + t.Run(tc.name, func(t *testing.T) { + v := map[string]any{} + for k, x := range defaultProject { + v[k] = x + } + tc.change(v) + b, _ := json.Marshal(v) + response.Store(string(b)) + _, err := c.ReviewScheduling(t.Context()) + checkError(t, err, "invalid_response", "PRIVATE_INVALID_DATE") + }) + } + for _, tc := range []struct{ name, timestamp string }{ + {"offset", "2026-11-01T05:30:00+05:30"}, + {"redundant-precision", "2026-11-01T00:00:00.000000000Z"}, + } { + t.Run("project-valid-date-"+tc.name, func(t *testing.T) { + v := map[string]any{} + for k, x := range defaultProject { + v[k] = x + } + v["revision"], v["updated_at"] = 1, tc.timestamp + b, _ := json.Marshal(v) + response.Store(string(b)) + if _, err := c.ReviewScheduling(t.Context()); err != nil { + t.Fatalf("valid RFC3339Nano timestamp %q was rejected: %v", tc.timestamp, err) + } + }) + } + for _, tc := range []struct { + name string + change func(map[string]any) + }{ + {"project-binding", func(v map[string]any) { v["project_id"] = "another-project" }}, + {"pull-binding", func(v map[string]any) { v["pull_number"] = 4 }}, + {"default-paused", func(v map[string]any) { v["revision"] = 0 }}, + {"missing-actor", func(v map[string]any) { delete(v, "actor_id") }}, + {"unpaused-reason", func(v map[string]any) { v["paused"] = false }}, + {"bad-date", func(v map[string]any) { v["updated_at"] = "PRIVATE_INVALID_DATE" }}, + {"zero-date", func(v map[string]any) { v["updated_at"] = "0001-01-01T00:00:00Z" }}, + } { + t.Run("pull-"+tc.name, func(t *testing.T) { + v := map[string]any{} + for k, x := range validPaused { + v[k] = x + } + tc.change(v) + b, _ := json.Marshal(v) + response.Store(string(b)) + _, err := c.ReviewPullScheduling(t.Context(), 2) + checkError(t, err, "invalid_response") + }) + } + for _, tc := range []struct{ name, timestamp string }{ + {"offset", "2026-11-01T05:30:00+05:30"}, + {"redundant-precision", "2026-11-01T00:00:00.000000000Z"}, + } { + t.Run("pull-valid-date-"+tc.name, func(t *testing.T) { + v := map[string]any{} + for k, x := range validPaused { + v[k] = x + } + v["updated_at"] = tc.timestamp + b, _ := json.Marshal(v) + response.Store(string(b)) + if _, err := c.ReviewPullScheduling(t.Context(), 2); err != nil { + t.Fatalf("valid RFC3339Nano timestamp %q was rejected: %v", tc.timestamp, err) + } + }) + } + for _, pull := range []bool{false, true} { + body := `{"id":"wrong-target","state":"scheduling_configured","revision":1}` + if pull { + body = `{"id":"4","state":"pull_scheduling_updated","revision":1}` + } + response.Store(body) + before := calls.Load() + var err error + if pull { + _, err = c.ConfigureReviewPullScheduling(t.Context(), "original-scheduling-key", 2, client.ConfigureReviewPullSchedulingRequest{Paused: true}) + } else { + _, err = c.ConfigureReviewScheduling(t.Context(), "original-scheduling-key", client.ConfigureReviewSchedulingRequest{AutomaticHosted: true}) + } + checkError(t, err, "invalid_response") + var unknown *client.Error + if !errors.As(err, &unknown) || !unknown.OutcomeUnknown || calls.Load() != before+1 { + t.Fatal("invalid mutation receipt lost uncertainty or retried", err) + } + } +} + +func TestReviewSchedulingClientLocalValidationNeedsNoConnection(t *testing.T) { + c := &client.Client{} + for _, invoke := range []func() error{ + func() error { _, err := c.ReviewPullScheduling(t.Context(), 0); return err }, + func() error { + _, err := c.ConfigureReviewScheduling(t.Context(), "", client.ConfigureReviewSchedulingRequest{}) + return err + }, + func() error { + _, err := c.ConfigureReviewScheduling(t.Context(), "key", client.ConfigureReviewSchedulingRequest{ExpectedRevision: -1}) + return err + }, + func() error { + _, err := c.ConfigureReviewScheduling(t.Context(), "key", client.ConfigureReviewSchedulingRequest{ExpectedRevision: math.MaxInt64}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2147483648, client.ConfigureReviewPullSchedulingRequest{}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: -1}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: math.MaxInt64}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: "line\nbreak"}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: strings.Repeat("a", 257)}) + return err + }, + func() error { + _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: string([]byte{255})}) + return err + }, + } { + if err := invoke(); err == nil { + t.Fatal("invalid local input reached the unconfigured connection") + } + } +} + +func TestSchedulingOptionalCLIWireContract(t *testing.T) { + for _, state := range []string{"omitted", "true", "false"} { + request := client.ConfigureReviewSchedulingRequest{AutomaticHosted: true} + want := `{"expected_revision":0,"automatic_hosted":true` + if state != "omitted" { + enabled := state == "true" + request.AutomaticCLI = &enabled + want += `,"automatic_cli":` + state + } + encoded, err := json.Marshal(request) + if err != nil || string(encoded) != want+"}" { + t.Fatalf("wrong optional CLI body: %s %v", encoded, err) + } + } + var response string + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, response) + })) + defer service.Close() + c := newClient(t, service) + for _, tc := range []struct { + body string + valid, enabled bool + }{ + {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"paused_pulls":[]}`, true, false}, + {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[]}`, false, false}, + {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"automatic_cli":null,"paused_pulls":[]}`, false, false}, + {`{"project_id":"project-one","revision":1,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[],"updated_at":"2026-11-01T00:00:00Z"}`, false, false}, + {`{"project_id":"project-one","revision":1,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[],"updated_at":"2026-11-01T00:00:00Z","authorizing_worker_id":"worker-one"}`, true, true}, + } { + response = tc.body + value, err := c.ReviewScheduling(t.Context()) + if (err == nil) != tc.valid || tc.valid && value.AutomaticCLI != tc.enabled { + t.Fatalf("wrong scheduling validation: %+v %v", value, err) + } + } +} + +func TestReviewSchedulingClientReadsMaximumEscapedPausedQueue(t *testing.T) { + project := strings.Repeat("<", 128) + value := client.ReviewScheduling{ + ProjectID: project, Revision: math.MaxInt64, AutomaticHosted: true, AutomaticCLI: true, + AuthorizingWorkerID: strings.Repeat("&", 128), UpdatedAt: "2026-11-01T00:00:00.999999999+05:30", + PausedPulls: make([]client.ReviewPullScheduling, 100), + } + for i := range value.PausedPulls { + value.PausedPulls[i] = client.ReviewPullScheduling{ + ProjectID: project, PullNumber: 2147483647 - int64(i), Revision: math.MaxInt64, Paused: true, + Reason: strings.Repeat("<", 256), ActorID: strings.Repeat(">", 128), UpdatedAt: value.UpdatedAt, + } + } + encoded, err := json.Marshal(value) + if err != nil || len(encoded) <= 256<<10 { + t.Fatalf("fixture must exercise escaped reasons and maximum identities: bytes=%d err=%v", len(encoded), err) + } + var response atomic.Value + response.Store(encoded) + var calls atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + calls.Add(1) + if r.Method != http.MethodGet || r.URL.Path != "/api/v1/projects/"+project+"/reviews/scheduling" { + t.Error("scheduling read changed scope or method") + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(response.Load().([]byte)) + })) + defer service.Close() + selected := binding(t, service.URL) + selected.Context.ProjectID = project + c, err := client.New(t.Context(), selected) + if err != nil { + t.Fatal(err) + } + defer c.Close() + got, err := c.ReviewScheduling(t.Context()) + if err != nil || !reflect.DeepEqual(got, value) || calls.Load() != 1 { + t.Fatalf("valid maximum escaped scheduling response failed: calls=%d err=%v", calls.Load(), err) + } + // Retain a finite wire bound even for an otherwise valid response. + response.Store(append(append([]byte(nil), encoded...), []byte(strings.Repeat(" ", 512<<10))...)) + _, err = c.ReviewScheduling(t.Context()) + checkError(t, err, "invalid_response") + if calls.Load() != 2 { + t.Fatal("oversized scheduling read retried", calls.Load()) + } +} diff --git a/internal/core/project_automation.go b/internal/core/project_automation.go new file mode 100644 index 000000000..f4bde2e08 --- /dev/null +++ b/internal/core/project_automation.go @@ -0,0 +1,52 @@ +package core + +import ( + "context" + "database/sql" + "errors" +) + +// AuthenticatedCredentialID identifies the exact current credential behind an +// authenticated scope without exposing its token or hash. It grants no access. +func (s *Store) AuthenticatedCredentialID(ctx context.Context, tx *sql.Tx, scope Scope) (string, error) { + permission := "read" + if scope.Administrative() { + permission = "admin" + } + if err := s.authorize(ctx, tx, scope, permission); err != nil { + return "", err + } + var id string + err := tx.QueryRowContext(ctx, `SELECT id FROM credentials WHERE token_sha256=? AND principal_id=? AND revoked=0`, scope.tokenHash, scope.PrincipalID).Scan(&id) + if err != nil { + return "", storageError(err) + } + return id, nil +} + +// ProjectAutomationScope revalidates an explicitly retained project automation +// authorization. Callers obtain these identities from their own durable control +// record, never from an unauthenticated request. The exact credential must still +// manage this project and its attributed worker must remain active. Subsequent +// Store operations reauthorize the returned scope again at their boundary. +func (s *Store) ProjectAutomationScope(ctx context.Context, tx *sql.Tx, project, principal, worker, credential string) (Scope, error) { + if project == "" || principal == "" || worker == "" || credential == "" { + return Scope{}, Fail("forbidden", "Current project automation authorization is required.", 403) + } + var hash string + err := tx.QueryRowContext(ctx, `SELECT token_sha256 FROM credentials WHERE id=? AND principal_id=? AND revoked=0`, credential, principal).Scan(&hash) + if errors.Is(err, sql.ErrNoRows) { + return Scope{}, Fail("forbidden", "The project automation authorization is no longer current.", 403) + } + if err != nil { + return Scope{}, storageError(err) + } + scope := Scope{ProjectID: project, PrincipalID: principal, WorkerID: worker, tokenHash: hash, instanceID: s.instanceID, admin: true} + if err := s.authorize(ctx, tx, scope, "admin"); err != nil { + return Scope{}, err + } + if err := CheckActiveWorker(ctx, tx, project, worker); err != nil { + return Scope{}, err + } + return scope, nil +} diff --git a/internal/core/project_automation_test.go b/internal/core/project_automation_test.go new file mode 100644 index 000000000..b80723ebb --- /dev/null +++ b/internal/core/project_automation_test.go @@ -0,0 +1,205 @@ +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 }{ + {`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) + _, _, 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/mcpadapter/adapter_test.go b/internal/mcpadapter/adapter_test.go index 1033e368f..a29929db2 100644 --- a/internal/mcpadapter/adapter_test.go +++ b/internal/mcpadapter/adapter_test.go @@ -242,6 +242,8 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { expected["review_obligation_resolve"] = true expected["review_queue_edit"] = true expected["review_operation_control"] = true + expected["review_scheduling_read"], expected["review_scheduling_configure"] = true, true + expected["review_pull_scheduling_read"], expected["review_pull_scheduling_update"] = true, true expected["wait_for_ci"] = true expected["review_rounds_read"], expected["review_rounds_configure"] = true, true expected["review_start"], expected["review_selection_read"] = true, true @@ -267,6 +269,7 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { writes["review_obligation_resolve"] = true writes["review_rounds_configure"] = true writes["review_operation_control"] = true + writes["review_scheduling_configure"], writes["review_pull_scheduling_update"] = true, true writes["job_primary_replace"] = true writes["map_entry_create"], writes["map_entry_replace"], writes["job_workstream_replace"] = true, true, true writes["worker_pause_replace"] = true @@ -286,7 +289,7 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { } delete(expected, tool.Name) a := tool.Annotations - if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_operation_control" || tool.Name == "review_policy_configure" || tool.Name == "review_execution_configure" || tool.Name == "worker_retire" || tool.Name == "project_credential_update" || tool.Name == "project_credential_revoke" || tool.Name == "presentation_replace" || tool.Name == "publication_apply" || tool.Name == "publication_unpublish" || tool.Name == "review_import_apply" || tool.Name == "review_transfer_apply" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { + if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update" || tool.Name == "review_operation_control" || tool.Name == "review_policy_configure" || tool.Name == "review_execution_configure" || tool.Name == "worker_retire" || tool.Name == "project_credential_update" || tool.Name == "project_credential_revoke" || tool.Name == "presentation_replace" || tool.Name == "publication_apply" || tool.Name == "publication_unpublish" || tool.Name == "review_import_apply" || tool.Name == "review_transfer_apply" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "review_pull_scheduling_update" || tool.Name == "review_scheduling_configure" || tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { t.Fatal("untruthful operation annotation") } data, _ := json.Marshal(tool.InputSchema) diff --git a/internal/mcpadapter/arguments.go b/internal/mcpadapter/arguments.go index 5554bf7b8..f116fd643 100644 --- a/internal/mcpadapter/arguments.go +++ b/internal/mcpadapter/arguments.go @@ -63,6 +63,9 @@ func invalidArguments() *Diagnostic { } func parseArguments(name string, data json.RawMessage) (arguments, error) { + if reviewSchedulingTool(name) { + return reviewSchedulingArguments(name, data) + } if name == "wait_for_ci" { return ciWatchArguments(data) } diff --git a/internal/mcpadapter/review_scheduling.go b/internal/mcpadapter/review_scheduling.go new file mode 100644 index 000000000..91d984b57 --- /dev/null +++ b/internal/mcpadapter/review_scheduling.go @@ -0,0 +1,108 @@ +package mcpadapter + +import ( + "bytes" + "encoding/json" + "math" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" +) + +func reviewSchedulingWrite(name string) bool { + return name == "review_scheduling_configure" || name == "review_pull_scheduling_update" +} + +func reviewSchedulingTool(name string) bool { + return reviewSchedulingWrite(name) || name == "review_scheduling_read" || name == "review_pull_scheduling_read" +} + +func reviewSchedulingArguments(name string, raw json.RawMessage) (arguments, error) { + var args arguments + if len(raw) == 0 { + raw = []byte("{}") + } + trimmed := bytes.TrimSpace(raw) + if len(raw) > 4096 || len(trimmed) < 2 || trimmed[0] != '{' || trimmed[len(trimmed)-1] != '}' { + return args, invalidArguments() + } + if name == "review_scheduling_read" { + var empty struct{} + if strictjson.Decode(raw, &empty) != nil { + return args, invalidArguments() + } + return args, nil + } + if name == "review_pull_scheduling_read" { + var wire struct { + PullNumber int64 `json:"pull_number"` + } + if strictjson.Decode(raw, &wire) != nil || wire.PullNumber < 1 || wire.PullNumber > 2147483647 { + return args, invalidArguments() + } + args.pullNumber = wire.PullNumber + return args, nil + } + if name == "review_scheduling_configure" { + var wire struct { + Revision *int64 `json:"expected_revision"` + Enabled *bool `json:"automatic_hosted"` + CLI *bool `json:"automatic_cli,omitempty"` + Key string `json:"idempotency_key"` + } + if strictjson.Decode(raw, &wire) != nil || wire.Revision == nil || wire.Enabled == nil || !client.ValidMutationKey(wire.Key) { + return args, invalidArguments() + } + var present map[string]json.RawMessage + if json.Unmarshal(raw, &present) != nil || present["automatic_cli"] != nil && wire.CLI == nil { + return args, invalidArguments() + } + args.key = wire.Key + args.reviewScheduling = client.ConfigureReviewSchedulingRequest{ExpectedRevision: *wire.Revision, AutomaticHosted: *wire.Enabled, AutomaticCLI: wire.CLI} + if client.ValidateConfigureReviewScheduling(args.reviewScheduling) != nil { + return arguments{}, invalidArguments() + } + return args, nil + } + var wire struct { + PullNumber int64 `json:"pull_number"` + Revision *int64 `json:"expected_revision"` + Paused *bool `json:"paused"` + Reason *string `json:"reason,omitempty"` + Key string `json:"idempotency_key"` + } + if name != "review_pull_scheduling_update" || strictjson.Decode(raw, &wire) != nil || wire.Revision == nil || wire.Paused == nil || !client.ValidMutationKey(wire.Key) { + return args, invalidArguments() + } + var present map[string]json.RawMessage + if json.Unmarshal(raw, &present) != nil || present["reason"] != nil && (wire.Reason == nil || !*wire.Paused) { + return args, invalidArguments() + } + args.key, args.pullNumber = wire.Key, wire.PullNumber + args.reviewPullScheduling = client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: *wire.Revision, Paused: *wire.Paused} + if wire.Reason != nil { + args.reviewPullScheduling.Reason = *wire.Reason + } + if client.ValidateConfigureReviewPullScheduling(args.pullNumber, args.reviewPullScheduling) != nil { + return arguments{}, invalidArguments() + } + return args, nil +} + +func reviewSchedulingDefinitions() []definition { + object := func(properties map[string]any, required ...string) map[string]any { + if required == nil { + required = []string{} + } + return map[string]any{"type": "object", "additionalProperties": false, "properties": properties, "required": required} + } + revision := map[string]any{"type": "integer", "minimum": 0, "maximum": int64(math.MaxInt64 - 1)} + pull := map[string]any{"type": "integer", "minimum": 1, "maximum": 2147483647} + key := map[string]any{"type": "string", "minLength": 1, "maxLength": 128, "description": "Explicit original idempotency key; retain with the exact request after unknown outcome."} + return []definition{ + {"review_scheduling_read", "Read this project's automatic Hosted and CLI settings and current queued PR pauses in one provider-free call. No settings, review or allowance changes. See docs/review-scheduling.md.", object(map[string]any{})}, + {"review_scheduling_configure", "Project manager: explicitly enable or disable automatic future Hosted or CLI requests under existing source, obligation, round and provider guards. Both default off. Optional automatic_cli preserves the current CLI setting when omitted. Existing grants and taper apply; no automatic adjudication or grant increase. Enabling retains this connection's current credential and active bound worker; withdrawn authority stops new automatic actions. This setting can authorize asynchronous provider work. Current revision and explicit key required; no automatic mutation retry. See docs/review-scheduling.md.", object(map[string]any{"expected_revision": revision, "automatic_hosted": map[string]any{"type": "boolean"}, "automatic_cli": map[string]any{"type": "boolean", "description": "Optional CLI opt-in; omission preserves the current setting."}, "idempotency_key": key}, "expected_revision", "automatic_hosted", "idempotency_key")}, + {"review_pull_scheduling_read", "Read one PR's temporary scheduling pause before or after an intent exists. Does not change Draft, grant, taper, closure or active provider work.", object(map[string]any{"pull_number": pull}, "pull_number")}, + {"review_pull_scheduling_update", "Writer: explicitly pause or resume new and undispatched reviews for one PR, including automatic Hosted and CLI selection. Does not cancel already-issued reviews or stop collecting results, change round credit or clear a separate operation pause. Retain current revision/key; reason is optional plain text only while paused and must be omitted on resume. See docs/review-scheduling.md.", object(map[string]any{"pull_number": pull, "expected_revision": revision, "paused": map[string]any{"type": "boolean"}, "reason": map[string]any{"type": "string", "maxLength": 256, "description": "Optional reason; omit on resume."}, "idempotency_key": key}, "pull_number", "expected_revision", "paused", "idempotency_key")}, + } +} diff --git a/internal/mcpadapter/review_scheduling_arguments_test.go b/internal/mcpadapter/review_scheduling_arguments_test.go new file mode 100644 index 000000000..a3d54d153 --- /dev/null +++ b/internal/mcpadapter/review_scheduling_arguments_test.go @@ -0,0 +1,53 @@ +package mcpadapter + +import ( + "encoding/json" + "testing" +) + +func TestSchedulingOptionalCLIArguments(t *testing.T) { + for _, value := range []string{"", "true", "false"} { + raw := `{"expected_revision":0,"automatic_hosted":false,"idempotency_key":"cli-setting"` + if value != "" { + raw += `,"automatic_cli":` + value + } + args, err := reviewSchedulingArguments("review_scheduling_configure", json.RawMessage(raw+"}")) + if err != nil || (args.reviewScheduling.AutomaticCLI == nil) != (value == "") { + t.Fatalf("lost optional CLI state %q: %+v %v", value, args, err) + } + if value != "" && *args.reviewScheduling.AutomaticCLI != (value == "true") { + t.Fatal("wrong CLI state") + } + } + for _, raw := range []string{ + `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":null,"idempotency_key":"key"}`, + `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":"true","idempotency_key":"key"}`, + `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":true,"automatic_cli":false,"idempotency_key":"key"}`, + `{"expected_revision":0,"automatic_cli":true,"idempotency_key":"key"}`, + } { + if _, err := reviewSchedulingArguments("review_scheduling_configure", json.RawMessage(raw)); err == nil { + t.Fatal("accepted malformed CLI configuration", raw) + } + } +} + +func TestSchedulingPauseReasonIsOmittedOnResume(t *testing.T) { + for _, raw := range []string{ + `{"pull_number":7,"expected_revision":2,"paused":false,"idempotency_key":"resume"}`, + `{"pull_number":7,"expected_revision":2,"paused":true,"reason":"","idempotency_key":"pause-empty-reason"}`, + `{"pull_number":7,"expected_revision":2,"paused":true,"reason":"Fixing","idempotency_key":"pause-reason"}`, + } { + if _, err := reviewSchedulingArguments("review_pull_scheduling_update", json.RawMessage(raw)); err != nil { + t.Fatalf("rejected valid scheduling update %s: %v", raw, err) + } + } + for _, raw := range []string{ + `{"pull_number":7,"expected_revision":2,"paused":false,"reason":"no longer allowed","idempotency_key":"resume-reason"}`, + `{"pull_number":7,"expected_revision":2,"paused":false,"reason":"","idempotency_key":"resume-empty-reason"}`, + `{"pull_number":7,"expected_revision":2,"paused":false,"reason":null,"idempotency_key":"resume-null-reason"}`, + } { + if _, err := reviewSchedulingArguments("review_pull_scheduling_update", json.RawMessage(raw)); err == nil { + t.Fatalf("accepted reason on resume: %s", raw) + } + } +} diff --git a/internal/mcpadapter/review_scheduling_test.go b/internal/mcpadapter/review_scheduling_test.go new file mode 100644 index 000000000..253178de7 --- /dev/null +++ b/internal/mcpadapter/review_scheduling_test.go @@ -0,0 +1,120 @@ +package mcpadapter_test + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/profile" + "github.com/benhook1013/FireController/internal/reviewexec" +) + +func TestSchedulingSDKBoundControlsAndDiscovery(t *testing.T) { + f := mutationFixture(t) + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + engine, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "scheduling-fixture", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + engine.Register(mux) + server := httptest.NewServer(mux) + defer server.Close() + managerCredential := filepath.Join(t.TempDir(), "manager.token") + if err := os.WriteFile(managerCredential, []byte(f.admin), 0600); err != nil { + t.Fatal(err) + } + managerProfile := profiles(t, map[string]profile.Context{"chosen": {Profile: "chosen", ServerURL: server.URL, InstanceID: f.store.InstanceID(), ProjectID: f.project, WorkerID: f.sender}}, managerCredential) + manager := reviewControlsStdio(t, managerProfile, "chosen") + writer := connect(t, f.adapter(t, server.URL, f.sender), "") + beforeProviders := f.providers.Load() + var initial client.ReviewScheduling + decodeResult(t, call(t, writer, "review_scheduling_read", nil), &initial) + if initial.Revision != 0 || initial.AutomaticHosted || initial.PausedPulls == nil { + t.Fatal(initial) + } + diagnosticResult(t, call(t, writer, "review_scheduling_configure", map[string]any{"expected_revision": 0, "automatic_hosted": true, "idempotency_key": "writer-cannot-enable"}), "forbidden", false) + input := map[string]any{"expected_revision": 0, "automatic_hosted": true, "idempotency_key": "manager-enable"} + var first, replay client.ReviewRequestReceipt + decodeResult(t, call(t, manager, "review_scheduling_configure", input), &first) + decodeResult(t, call(t, manager, "review_scheduling_configure", input), &replay) + if first != replay || first.ID != f.project || first.Revision != 1 { + t.Fatal(first, replay) + } + // CLI opt-in is independent; a legacy Hosted-only write preserves it. + decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 1, "automatic_hosted": false, "automatic_cli": true, "idempotency_key": "manager-cli-enable"}), &first) + var automatic client.ReviewScheduling + decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) + if automatic.AutomaticHosted || !automatic.AutomaticCLI || automatic.AuthorizingWorkerID != f.sender { + t.Fatal("CLI opt-in lost shared authorization", automatic) + } + decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 2, "automatic_hosted": true, "idempotency_key": "manager-legacy-preserve"}), &first) + decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) + if !automatic.AutomaticHosted || !automatic.AutomaticCLI { + t.Fatal("legacy configuration changed CLI opt-in", automatic) + } + decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 3, "automatic_hosted": true, "automatic_cli": false, "idempotency_key": "manager-cli-disable"}), &first) + decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) + if !automatic.AutomaticHosted || automatic.AutomaticCLI { + t.Fatal("explicit CLI disable was lost", automatic) + } + var paused client.ReviewRequestReceipt + decodeResult(t, call(t, writer, "review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 0, "paused": true, "reason": "Preparing changes", "idempotency_key": "pause-before-intent"}), &paused) + if paused.ID != strconv.Itoa(7) || paused.Revision != 1 { + t.Fatal(paused) + } + var state client.ReviewPullScheduling + decodeResult(t, call(t, writer, "review_pull_scheduling_read", map[string]any{"pull_number": 7}), &state) + if !state.Paused || state.Reason != "Preparing changes" || state.ProjectID != f.project { + t.Fatal(state) + } + decodeResult(t, call(t, writer, "review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 1, "paused": false, "idempotency_key": "resume-before-intent"}), &paused) + decodeResult(t, call(t, writer, "review_pull_scheduling_read", map[string]any{"pull_number": 7}), &state) + if state.Paused || state.Reason != "" || state.Revision != 2 { + t.Fatal(state) + } + for _, tc := range []struct { + name string + args map[string]any + }{ + {"review_scheduling_read", map[string]any{"project_id": "foreign"}}, + {"review_scheduling_configure", map[string]any{"expected_revision": 1, "automatic_hosted": nil, "idempotency_key": "null"}}, + {"review_scheduling_configure", map[string]any{"expected_revision": 1, "idempotency_key": "missing-bool"}}, + {"review_pull_scheduling_read", map[string]any{"pull_number": 0}}, + {"review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 2, "paused": nil, "idempotency_key": "null-pause"}}, + {"review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 2, "paused": true, "reason": nil, "idempotency_key": "null-reason"}}, + } { + diagnosticResult(t, call(t, manager, tc.name, tc.args), "invalid_arguments", false) + } + listed, err := allDiscoveredTools(t, manager) + if err != nil { + t.Fatal(err) + } + seen := 0 + for _, tool := range listed.Tools { + if tool.Name != "review_scheduling_read" && tool.Name != "review_scheduling_configure" && tool.Name != "review_pull_scheduling_read" && tool.Name != "review_pull_scheduling_update" { + continue + } + seen++ + write := tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update" + if tool.Annotations == nil || tool.Annotations.ReadOnlyHint == write || tool.Annotations.OpenWorldHint == nil || *tool.Annotations.OpenWorldHint != (tool.Name == "review_scheduling_configure") { + t.Fatal("unsafe annotations", tool.Name) + } + } + if seen != 4 || f.providers.Load() != beforeProviders { + t.Fatal("missing tools or provider work", seen, f.providers.Load(), beforeProviders) + } + for _, table := range []string{"review_selections", "review_operations", "review_execution_attempts"} { + var n int + if err := f.store.DB().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil || n != 0 { + t.Fatal("handler started review work", table, n, err) + } + } +} diff --git a/internal/mcpadapter/tools.go b/internal/mcpadapter/tools.go index fb60b931b..de96427b1 100644 --- a/internal/mcpadapter/tools.go +++ b/internal/mcpadapter/tools.go @@ -20,6 +20,8 @@ const maxToolWaitSeconds = 50 type arguments struct { operationControl client.ReviewOperationControl + reviewScheduling client.ConfigureReviewSchedulingRequest + reviewPullScheduling client.ConfigureReviewPullSchedulingRequest ciWatchTargets []client.CIWatchTarget ownerManagement *ownerManagementInvocation existingManagement *existingManagementArgs @@ -84,17 +86,20 @@ func boundServer(binding profile.Binding) *mcp.Server { definitions = append(definitions, projectMapDefinitions()...) definitions = append(definitions, jobContextDefinition(), messageWaitDefinition()) definitions = append(definitions, ciWatchDefinition()) + definitions = append(definitions, reviewSchedulingDefinitions()...) known := make(map[string]bool) transports := sessionTransports{pools: make(map[*mcp.ServerSession]*client.TransportPool)} for _, tool := range definitions { known[tool.name] = true - write := ownerManagementWrite(tool.name) || existingManagementWrite(tool.name) || tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" - openWorld := tool.name == "wait_for_ci" || tool.name == "review_start" || checkpointWrite(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" - destructive := ownerManagementDestructive(tool.name) || existingManagementDestructive(tool.name) || tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" + write := reviewSchedulingWrite(tool.name) || ownerManagementWrite(tool.name) || existingManagementWrite(tool.name) || tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" + openWorld := tool.name == "review_pull_scheduling_update" || tool.name == "review_scheduling_configure" || tool.name == "wait_for_ci" || tool.name == "review_start" || checkpointWrite(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" + destructive := reviewSchedulingWrite(tool.name) || ownerManagementDestructive(tool.name) || existingManagementDestructive(tool.name) || tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" s.AddTool(&mcp.Tool{Name: tool.name, Description: tool.description, InputSchema: tool.schema, Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !write, IdempotentHint: true, DestructiveHint: &destructive, OpenWorldHint: &openWorld}}, func(ctx context.Context, request *mcp.CallToolRequest) (*mcp.CallToolResult, error) { var args arguments var err error - if tool.name == "wait_for_ci" { + if reviewSchedulingTool(tool.name) { + args, err = reviewSchedulingArguments(tool.name, request.Params.Arguments) + } else if tool.name == "wait_for_ci" { args, err = ciWatchArguments(request.Params.Arguments) } else if ownerManagementTool(tool.name) { args, err = ownerManagementArguments(tool.name, request.Params.Arguments) @@ -202,6 +207,14 @@ func boundServer(binding profile.Binding) *mcp.Server { value, err = service.ReviewExecution(ctx) case "review_operations_list": value, err = service.ReviewOperations(ctx, args.reviewOperations) + case "review_scheduling_read": + value, err = service.ReviewScheduling(ctx) + case "review_scheduling_configure": + value, err = service.ConfigureReviewScheduling(ctx, args.key, args.reviewScheduling) + case "review_pull_scheduling_read": + value, err = service.ReviewPullScheduling(ctx, args.pullNumber) + case "review_pull_scheduling_update": + value, err = service.ConfigureReviewPullScheduling(ctx, args.key, args.pullNumber, args.reviewPullScheduling) case "wait_for_ci": var watch client.CIWatchResult watch, err = service.WatchCI(ctx, args.ciWatchTargets, args.reviewSourceWait) diff --git a/internal/reviewexec/attempt_projection.go b/internal/reviewexec/attempt_projection.go index 70ed64a1a..6df650c1d 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) { return reviews.Receipt{}, publicationConflict() diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 42f574850..e3d57807f 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -91,6 +91,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 @@ -146,6 +160,11 @@ func (e *Engine) startAttempt(ctx context.Context, project, id string, draftRead } return err } + if preferred, err := e.preferredCLIQueued(ctx, tx, o, c); err != nil { + return err + } else if preferred { + return nil + } var repositoryID int64 if earlier, err := e.earlierQueuedReviewIntent(ctx, tx, o, c, revision); err != nil { return err @@ -236,6 +255,15 @@ func (e *Engine) Admit(ctx context.Context, project, id string, expectedRevision if anchor.PullNumber != o.PullNumber || anchor.CandidateSHA != o.HeadSHA { return conflict() } + // Preparation may have overlapped a PR pause or a withdrawal of the + // automatic intent's authority. Recheck in this admission transaction, + // before recording a possibly issued action. + if err := requirePullScheduling(ctx, tx, project, o.PullNumber); err != nil { + return err + } + if err := e.requireAutomaticOperation(ctx, tx, o); err != nil { + return err + } if err := requireSourceObligationsClear(ctx, tx, project, o.PullNumber); err != nil { return err } @@ -371,7 +399,9 @@ func (e *Engine) Advance(ctx context.Context, project, id string, expectedRevisi return err } operationState, operationAttempt := state, o.AttemptID - if o.Channel == "cli" && reason == cliDraftWait && state == "held" && o.State == "preparing" && o.AttemptID == a.ID && a.Anchor == nil && a.Intent == "" && a.ExternalID == "" { + // Only an unused preparation may detach and retain the same queued intent. + retainQueued := o.Channel == "cli" && reason == cliDraftWait || reason == "pull_scheduling_paused" || reason == "automation_authorization_changed" + if retainQueued && state == "held" && o.State == "preparing" && o.AttemptID == a.ID && a.Anchor == nil && a.Intent == "" && a.ExternalID == "" { operationState, operationAttempt = "queued", "" } if _, err = tx.ExecContext(ctx, `UPDATE review_operations SET state=?,revision=revision+1,reason=?,attempt_id=?,updated_at=? WHERE id=?`, operationState, reason, operationAttempt, at, a.OperationID); err != nil { diff --git a/internal/reviewexec/carried_obligations.go b/internal/reviewexec/carried_obligations.go index 995854343..489d518f1 100644 --- a/internal/reviewexec/carried_obligations.go +++ b/internal/reviewexec/carried_obligations.go @@ -32,5 +32,8 @@ func sourceObligationReadError(err error) error { if errors.As(err, &failure) && failure.Code == "repository_changed" { return sourceHold("repository_changed") } + if adoptionholds.IsProjectStateError(err) { + return &automaticProjectStateError{err} + } return err } diff --git a/internal/reviewexec/cli_coverage.go b/internal/reviewexec/cli_coverage.go index 9df50dcb2..76786551b 100644 --- a/internal/reviewexec/cli_coverage.go +++ b/internal/reviewexec/cli_coverage.go @@ -83,7 +83,7 @@ func channelProgress(ctx context.Context, tx *sql.Tx, project string, repository return ComparisonState{}, err } if dirty { - return ComparisonState{}, adjudicationStorageError() + return ComparisonState{}, &automaticProjectStateError{adjudicationStorageError()} } c, err := readRoundControl(ctx, tx, project, number, channel) if err != nil { diff --git a/internal/reviewexec/cli_draft_wait.go b/internal/reviewexec/cli_draft_wait.go index f35930500..2193c12c4 100644 --- a/internal/reviewexec/cli_draft_wait.go +++ b/internal/reviewexec/cli_draft_wait.go @@ -209,14 +209,21 @@ func (e *Engine) recordCLIDraftDecision(ctx context.Context, o Operation, reason // historicalCLIDraftOperation identifies an unused preparation detached when // GitHub returned the PR to Draft. It supplies attribution for history only. func historicalCLIDraftOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (Operation, bool, error) { + return historicalUnusedPreparationOperation(ctx, q, o, a, false) +} + +// historicalUnusedPreparationOperation verifies detached draft and scheduling +// holds without inventing provider evidence or changing the current operation. +func historicalUnusedPreparationOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt, scheduling bool) (Operation, bool, error) { var reason string if err := q.QueryRowContext(ctx, `SELECT reason FROM review_execution_transitions WHERE attempt_id=? AND revision=?`, a.ID, a.Revision).Scan(&reason); err != nil { return Operation{}, false, err } - if reason != cliDraftWait { + draft := reason == cliDraftWait + if !draft && !(scheduling && (reason == "pull_scheduling_paused" || reason == "automation_authorization_changed")) { 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 @@ -225,11 +232,11 @@ func historicalCLIDraftOperation(ctx context.Context, q EvidenceQuery, o Operati EXISTS(SELECT 1 FROM review_execution_transitions WHERE attempt_id=first.attempt_id AND revision NOT IN (1,2)) OR EXISTS(SELECT 1 FROM review_execution_reservations WHERE attempt_id=first.attempt_id) OR EXISTS(SELECT 1 FROM review_execution_evidence WHERE attempt_id=first.attempt_id) - OR EXISTS(SELECT 1 FROM review_cli_preflight WHERE attempt_id=first.attempt_id) + OR (? AND EXISTS(SELECT 1 FROM review_cli_preflight WHERE attempt_id=first.attempt_id)) FROM review_execution_transitions first JOIN review_execution_transitions last ON last.attempt_id=first.attempt_id AND last.revision=2 WHERE first.attempt_id=? AND first.revision=1 AND first.state='preparing' AND first.reason='preparing' - AND last.state='held' AND first.external_id='' AND last.external_id=''`, a.ID).Scan(&startedAt, &heldAt, &occupied) + AND last.state='held' AND first.external_id='' AND last.external_id=''`, draft, a.ID).Scan(&startedAt, &heldAt, &occupied) if err != nil { return Operation{}, false, err } @@ -238,6 +245,6 @@ 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 + o.AttemptID, o.State, o.Reason, o.Wait = a.ID, "held", reason, nil return o, true, nil } diff --git a/internal/reviewexec/cli_wait_test.go b/internal/reviewexec/cli_wait_test.go index 3c7bbdfc6..da456a2ff 100644 --- a/internal/reviewexec/cli_wait_test.go +++ b/internal/reviewexec/cli_wait_test.go @@ -34,6 +34,66 @@ func cliWaitFixture(t *testing.T) (*attemptFixture, Attempt, CLIAllowanceObserva return f, a, in, &now } +func TestOperationStatusRetryDeadlineVersionCompatibility(t *testing.T) { + for _, state := range []string{"held", "queued"} { + t.Run(state, func(t *testing.T) { + f, a, in := cooldownObservationFixture(t) + if err := f.e.RecordHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + if state == "held" { + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "hosted_allowance_cooldown", ""); err != nil { + t.Fatal(err) + } + } else if _, err := f.e.ScheduleHostedCooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + original := cliWaitRead(t, f, a.OperationID) + status, err := f.e.ReadOperationStatus(t.Context(), operationReadScope(t, f), a.OperationID) + if err != nil || status.State != state { + t.Fatal("invalid retained status fixture", status, err) + } + due := in.Observation.RetryNotBefore.Format(time.RFC3339Nano) + if state == "held" && (status.RetryNotBefore != due || original.Allowance == nil || original.Allowance.RetryNotBefore != due) || state == "queued" && (status.RetryNotBefore != "" || status.Wait == nil || status.Wait.RetryNotBefore != due) { + t.Fatal("deadline was not retained in its state-specific location", status, original) + } + snapshot := func() string { + return snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "review_hosted_preflight") + snapshotTable(t, f, "receipts") + snapshotTable(t, f, "events") + } + before := snapshot() + base := "/api/v1/projects/" + attemptProject + "/reviews/operations/" + a.OperationID + for _, version := range []string{"", "1", "2", "3", "4", "5", "unknown"} { + t.Run("version_"+version, func(t *testing.T) { + fullResponse := versionWaitRead(t, f, base, version) + statusResponse := versionWaitRead(t, f, base+"/status", version) + var full Operation + var compact OperationStatus + if err := json.Unmarshal(fullResponse.Body.Bytes(), &full); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(statusResponse.Body.Bytes(), &compact); err != nil { + t.Fatal(err) + } + wantFull, wantCompact := original, status + if version != "3" && version != "5" { + wantFull.Allowance = nil + wantCompact.RetryNotBefore = "" + } + if version != "1" && version != "2" && version != "3" && version != "5" { + wantFull.Wait, wantCompact.Wait = nil, nil + } + if !reflect.DeepEqual(full, wantFull) || !reflect.DeepEqual(compact, wantCompact) { + t.Fatalf("negotiated full/status reads lost or exposed retained facts: full=%+v compact=%+v want_full=%+v want_compact=%+v", full, compact, wantFull, wantCompact) + } + }) + } + if before != snapshot() { + t.Fatal("versioned reads changed retained history or scheduling") + } + }) + } +} + func cliWaitRead(t *testing.T, f *attemptFixture, id string) Operation { t.Helper() o, err := readOperation(t.Context(), f.store.DB(), attemptProject, id) @@ -490,13 +550,13 @@ func TestCLISharedQuotaHTTPDiagnostics(t *testing.T) { before[table] = snapshotTable(t, f, table) } for _, suffix := range []string{"", "/status"} { - for _, version := range []string{"", "1", "2", "3"} { + for _, version := range []string{"", "1", "2", "3", "4", "5", "unsupported"} { req := httptest.NewRequest("GET", "/api/v1/projects/"+otherAttemptProject+"/reviews/operations/"+other.ID+suffix, nil) req.Header.Set("Authorization", "Bearer "+f.other) req.Header.Set(operationWaitHeader, version) w := httptest.NewRecorder() mux.ServeHTTP(w, req) - want := "" + want := "awaiting_scheduler" if mode == "shared" || mode == "cancelled-origin" { want = "cli_quota_wait" } @@ -528,6 +588,42 @@ func TestCLISharedQuotaHTTPDiagnostics(t *testing.T) { } } +func TestCLISharedQuotaHTTPDiagnosticsPreferPause(t *testing.T) { + for _, mode := range []string{"operation", "project"} { + t.Run(mode, func(t *testing.T) { + f, a, _, _ := cliWaitFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + other := f.enqueue(t, otherAttemptProject, "paused-diagnostic-cli", "cli", 2, 1) + if mode == "operation" { + admissionSQL(t, f, `INSERT INTO review_operation_waits(operation_id,baseline_attempt_id,retry_not_before,paused) VALUES(?,NULL,'',1)`, other.ID) + } else { + f.configure(t, otherAttemptProject, "test-capability", 1, true) + } + mux := http.NewServeMux() + f.e.Register(mux) + before := snapshotTable(t, f, "review_operation_waits") + for _, suffix := range []string{"", "/status"} { + for _, version := range []string{"", "1", "2", "3", "4", "5", "unsupported"} { + req := httptest.NewRequest("GET", "/api/v1/projects/"+otherAttemptProject+"/reviews/operations/"+other.ID+suffix, nil) + req.Header.Set("Authorization", "Bearer "+f.other) + req.Header.Set(operationWaitHeader, version) + w := httptest.NewRecorder() + mux.ServeHTTP(w, req) + if w.Code != http.StatusOK || w.Header().Get(queuedDiagnosticHeader) != mode+"_paused" { + t.Fatalf("%s schema %q: quota diagnostic hid pause: %d %v", suffix, version, w.Code, w.Header()) + } + } + } + if before != snapshotTable(t, f, "review_operation_waits") { + t.Fatal("pause diagnostic changed retained wait") + } + }) + } +} + // Retained audit history can be invalid without remaining a live account timer. // The same sampled instant governs candidate selection and the admission guard. func TestCLIAccountRetryDeadlineFutureHistory(t *testing.T) { @@ -586,7 +682,7 @@ func TestCLIAccountRetryDeadlineFutureHistory(t *testing.T) { t.Error("pending used expired or unrelated account history", pending, err) } scope := f.scope(t, otherAttemptProject, f.other, false) - if got := f.e.sharedCLIQuotaWait(t.Context(), scope, other.ID); got != (live && !invalid) { + if got := f.e.queuedDiagnostic(t.Context(), scope, other.ID, other.Revision) == "cli_quota_wait"; got != (live && !invalid) { t.Error("shared quota diagnostic differs from live validated deadline", got) } for _, table := range tables { @@ -933,10 +1029,8 @@ func TestPausedExpiredCLIWaitDoesNotReportQuotaHeader(t *testing.T) { req.Header.Set(operationWaitHeader, version) w := httptest.NewRecorder() mux.ServeHTTP(w, req) - want := "" - if live { - want = "cli_quota_wait" - } + // Scheduling diagnostics prioritize an explicit pause over quota. + want := "operation_paused" if w.Code != http.StatusOK || w.Header().Get("X-FC-Review-Queued") != want { t.Fatal(live, suffix, version, w.Code, w.Header(), w.Body.String()) } diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go index 329342623..9a04970a8 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -73,6 +73,20 @@ func (e *Engine) evaluateFrontPlan(ctx context.Context, q *sql.Tx, r Run, repo i if state.RoundsConfigured && state.RoundsComplete || !state.RoundsConfigured && state.Covered { return evaluatedFront{state: "complete", plan: plan}, nil } + scheduling, err := readPullScheduling(ctx, q, r.ProjectID, plan.Pull.Number) + if err != nil { + return evaluatedFront{}, err + } + if scheduling.Paused { + return evaluatedFront{state: "held", reason: "pull_scheduling_paused", plan: plan}, nil + } + suppressed, err := e.automaticPullSuppressed(ctx, q, r, plan.Pull.Number) + if err != nil { + return evaluatedFront{}, err + } + if suppressed { + return evaluatedFront{state: "held", reason: "automatic_intent_retained", plan: plan}, nil + } if plan.Pull.State != "open" { return evaluatedFront{state: "held", reason: "front_unavailable", plan: plan}, nil } diff --git a/internal/reviewexec/front_frame.go b/internal/reviewexec/front_frame.go new file mode 100644 index 000000000..7aef24627 --- /dev/null +++ b/internal/reviewexec/front_frame.go @@ -0,0 +1,154 @@ +package reviewexec + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "errors" + "slices" + "time" + + "github.com/benhook1013/FireController/internal/reviewprovider" + "github.com/benhook1013/FireController/internal/strictjson" +) + +const maxFrontPrefixBytes = 128 * 1024 + +// frontPull deliberately omits provider titles, statistics, captures and bodies. +type frontPull struct { + Number int64 `json:"number"` + VisibleAtAcquisition bool `json:"visible_at_acquisition"` + State string `json:"state"` + Merged bool `json:"merged"` + HeadSHA string `json:"head_sha"` + BaseSHA string `json:"base_sha"` + BaseRef string `json:"base_ref"` + ParentPullNumber int64 `json:"parent_pull_number"` + ParentSHA string `json:"parent_sha"` + ObservedAt string `json:"observed_at"` + SourceReason string `json:"source_reason,omitempty"` +} +type frontFrame struct { + repository, configuration int64 + checkedAt, observedAt, sourceReason string + complete bool + prefix []frontPull +} + +func (f frontFrame) plans() []SourcePlan { + out := make([]SourcePlan, 0, len(f.prefix)) + for _, p := range f.prefix { + out = append(out, SourcePlan{Repository: reviewprovider.Repository{ID: f.repository}, Pull: reviewprovider.Pull{RepositoryID: f.repository, Number: p.Number, State: p.State, Merged: p.Merged, HeadSHA: p.HeadSHA, BaseSHA: p.BaseSHA, BaseRef: p.BaseRef}, ParentPullNumber: p.ParentPullNumber, ParentSHA: p.ParentSHA, ObservedAt: p.ObservedAt, SourceReason: p.SourceReason}) + } + return out +} +func validFrontFrame(f frontFrame, c Configuration, channel string) bool { + if f.repository < 1 || f.configuration < 1 || !roundTime(f.checkedAt) || validateConfigurationShape(c) != nil || c.Paused || !slices.Contains(c.Channels, channel) || *c.ExpectedRevision != f.configuration-1 || len(f.prefix) > len(c.Queue) || len(f.prefix) > 100 || f.prefix == nil || (f.sourceReason != "" && (!identifier.MatchString(f.sourceReason) || len(f.sourceReason) > 128)) { + return false + } + if f.complete != (len(f.prefix) == len(c.Queue) && f.sourceReason == "") || len(f.prefix) == 0 && f.sourceReason == "" && len(c.Queue) > 0 { + return false + } + observed := "" + var latest time.Time + for i, p := range f.prefix { + if p.Number != c.Queue[i] || (p.State != "open" && p.State != "closed") || p.Merged && p.State != "closed" || !sha.MatchString(p.HeadSHA) || !sha.MatchString(p.BaseSHA) || !sha.MatchString(p.ParentSHA) || p.ParentSHA != p.BaseSHA || p.BaseRef == "" || !safeText(p.BaseRef, 256) || !roundTime(p.ObservedAt) || p.SourceReason != "" && !perPullSourceHold(p.SourceReason) { + return false + } + if p.ParentPullNumber < 0 || p.ParentPullNumber > 2147483647 || p.ParentPullNumber == p.Number || c.Mode == "independent" && p.ParentPullNumber != 0 { + return false + } + if p.ParentPullNumber != 0 { + for _, parent := range f.prefix { + if parent.Number == p.ParentPullNumber && (parent.State != "open" || parent.Merged || parent.HeadSHA != p.ParentSHA) { + return false + } + } + } + + at, _ := time.Parse(time.RFC3339Nano, p.ObservedAt) + if observed == "" || at.After(latest) { + latest = at + observed = p.ObservedAt + } + } + return f.observedAt == observed +} +func writeFrontFrame(ctx context.Context, tx *sql.Tx, r Run, repo int64, c Configuration, choice runChoice) error { + f := frontFrame{repository: repo, configuration: r.ConfigurationRevision, checkedAt: stamp(), sourceReason: choice.sourceReason, prefix: []frontPull{}} + var hasProjection bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='review_current_pulls')`).Scan(&hasProjection); err != nil { + return err + } + for _, p := range choice.prefix { + visible := false + if hasProjection { + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_current_pulls WHERE project_id=? AND number=?)`, r.ProjectID, p.Pull.Number).Scan(&visible); err != nil { + return err + } + } + f.prefix = append(f.prefix, frontPull{Number: p.Pull.Number, VisibleAtAcquisition: visible, State: p.Pull.State, Merged: p.Pull.Merged, HeadSHA: p.Pull.HeadSHA, BaseSHA: p.Pull.BaseSHA, BaseRef: p.Pull.BaseRef, ParentPullNumber: p.ParentPullNumber, ParentSHA: p.ParentSHA, ObservedAt: p.ObservedAt, SourceReason: p.SourceReason}) + if f.observedAt == "" { + f.observedAt = p.ObservedAt + } else { + a, _ := time.Parse(time.RFC3339Nano, f.observedAt) + b, _ := time.Parse(time.RFC3339Nano, p.ObservedAt) + if b.After(a) { + f.observedAt = p.ObservedAt + } + } + } + f.complete = len(f.prefix) == len(c.Queue) && f.sourceReason == "" + body, err := json.Marshal(f.prefix) + if err != nil { + return err + } + // Malformed/overbudget source can replace only with explicit unavailable; + // never make an otherwise valid admission depend on retaining rich facts. + if len(body) > maxFrontPrefixBytes || !validFrontFrame(f, c, r.Channel) { + f.prefix = []frontPull{} + f.complete = false + f.observedAt = "" + f.sourceReason = "source_unavailable" + body = []byte("[]") + } + _, err = tx.ExecContext(ctx, `INSERT INTO review_front_frames(project_id,channel,repository_id,configuration_revision,checked_at,source_observed_at,complete,source_reason,prefix_json) VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(project_id,channel) DO UPDATE SET repository_id=excluded.repository_id,configuration_revision=excluded.configuration_revision,checked_at=excluded.checked_at,source_observed_at=excluded.source_observed_at,complete=excluded.complete,source_reason=excluded.source_reason,prefix_json=excluded.prefix_json`, r.ProjectID, r.Channel, f.repository, f.configuration, f.checkedAt, f.observedAt, f.complete, f.sourceReason, string(body)) + return err +} +func readFrontFrame(ctx context.Context, q EvidenceQuery, project, channel string) (frontFrame, bool, error) { + var f frontFrame + var repository, configuration, complete sql.NullInt64 + var checked, observed, reason, body sql.NullString + err := q.QueryRowContext(ctx, `SELECT CASE WHEN typeof(repository_id)='integer' THEN repository_id END,CASE WHEN typeof(configuration_revision)='integer' THEN configuration_revision END,CASE WHEN typeof(checked_at)='text' AND length(CAST(checked_at AS BLOB))<=64 THEN checked_at END,CASE WHEN typeof(source_observed_at)='text' AND length(CAST(source_observed_at AS BLOB))<=64 THEN source_observed_at END,CASE WHEN typeof(complete)='integer' THEN complete END,CASE WHEN typeof(source_reason)='text' AND length(CAST(source_reason AS BLOB))<=128 THEN source_reason END,CASE WHEN typeof(prefix_json)='text' AND length(CAST(prefix_json AS BLOB))<=131072 THEN prefix_json END FROM review_front_frames WHERE project_id=? AND channel=?`, project, channel).Scan(&repository, &configuration, &checked, &observed, &complete, &reason, &body) + if errors.Is(err, sql.ErrNoRows) { + return f, false, nil + } + if err != nil { + return f, false, err + } + // Guarded NULLs are malformed project data, not query/transaction failures. + if !repository.Valid || !configuration.Valid || !checked.Valid || !observed.Valid || !complete.Valid || !reason.Valid || !body.Valid || complete.Int64 < 0 || complete.Int64 > 1 || strictjson.Decode([]byte(body.String), &f.prefix) != nil { + return f, false, runUnavailable() + } + f.repository, f.configuration = repository.Int64, configuration.Int64 + f.checkedAt, f.observedAt, f.sourceReason = checked.String, observed.String, reason.String + f.complete = complete.Int64 == 1 + canonical, err := json.Marshal(f.prefix) + if err != nil || !bytes.Equal(canonical, []byte(body.String)) { + return f, false, runUnavailable() + } + var configBody sql.NullString + 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=?`, project, f.configuration).Scan(&configBody) + if errors.Is(err, sql.ErrNoRows) { + return f, false, runUnavailable() + } + if err != nil { + return f, false, err + } + var c Configuration + if !configBody.Valid || strictjson.Decode([]byte(configBody.String), &c) != nil || !validFrontFrame(f, c, channel) { + return f, false, runUnavailable() + } + return f, true, nil +} diff --git a/internal/reviewexec/front_schema.go b/internal/reviewexec/front_schema.go new file mode 100644 index 000000000..7a9ec55f7 --- /dev/null +++ b/internal/reviewexec/front_schema.go @@ -0,0 +1,23 @@ +package reviewexec + +import ( + "context" + "database/sql" + "github.com/benhook1013/FireController/internal/core" +) + +func EnsureFrontSchema(ctx context.Context, store *core.Store) error { + if err := store.EnsureSchema(ctx, "review_fronts", FrontSchemaSQL()); err != nil { + return err + } + return store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { return validateFrontDefinition(ctx, tx) }) +} + +// FrontSchemaSQL is independent canonical DDL for the optional current cache. +func FrontSchemaSQL() []string { + return []string{`CREATE TABLE review_front_frames( + project_id TEXT NOT NULL REFERENCES projects(id),channel TEXT NOT NULL CHECK(channel IN ('cli','hosted')), + repository_id INTEGER NOT NULL CHECK(repository_id>0),configuration_revision INTEGER NOT NULL CHECK(configuration_revision>0), + checked_at TEXT NOT NULL,source_observed_at TEXT NOT NULL,complete INTEGER NOT NULL CHECK(complete IN (0,1)),source_reason TEXT NOT NULL,prefix_json TEXT NOT NULL, + PRIMARY KEY(project_id,channel),FOREIGN KEY(project_id,configuration_revision) REFERENCES review_execution_config(project_id,revision))`} +} diff --git a/internal/reviewexec/front_snapshot.go b/internal/reviewexec/front_snapshot.go new file mode 100644 index 000000000..455ee71d2 --- /dev/null +++ b/internal/reviewexec/front_snapshot.go @@ -0,0 +1,110 @@ +package reviewexec + +import ( + "context" + "fmt" + "strings" +) + +// ValidateFrontSnapshot validates historical source facts, not current policy, +// rounds, credentials or repository binding. Old valid frames remain backups. +func ValidateFrontSnapshot(ctx context.Context, q EvidenceQuery) error { + if err := validateFrontPhysical(ctx, q); err != nil { + return err + } + project, channel := "", "" + for { + rows, err := q.QueryContext(ctx, `SELECT project_id,channel FROM review_front_frames WHERE project_id>? OR (project_id=? AND channel>?) ORDER BY project_id,channel LIMIT 64`, project, project, channel) + if err != nil { + return err + } + type key struct{ project, channel string } + page := []key{} + for rows.Next() { + var k key + if err = rows.Scan(&k.project, &k.channel); err != nil { + break + } + page = append(page, k) + } + if err == nil { + err = rows.Err() + } + rows.Close() + if err != nil { + return err + } + for _, k := range page { + if !identifier.MatchString(k.project) || !validChannel(k.channel) { + return runUnavailable() + } + if _, found, err := readFrontFrame(ctx, q, k.project, k.channel); err != nil { + return err + } else if !found { + return runUnavailable() + } + project, channel = k.project, k.channel + } + if len(page) < 64 { + return nil + } + } +} +func validateFrontPhysical(ctx context.Context, q EvidenceQuery) error { + if err := validateFrontDefinition(ctx, q); err != nil { + return err + } + checks := []string{"project_id=''", "repository_id<1", "configuration_revision<1", "complete NOT IN (0,1)", "NOT EXISTS(SELECT 1 FROM projects p WHERE p.id=review_front_frames.project_id)"} + for _, col := range strings.Fields("repository_id configuration_revision complete") { + checks = append(checks, "typeof("+col+")!='integer'") + } + for _, col := range strings.Fields("project_id channel checked_at source_observed_at source_reason prefix_json") { + limit := 128 + if col == "checked_at" || col == "source_observed_at" { + limit = 64 + } + if col == "prefix_json" { + limit = maxFrontPrefixBytes + } + checks = append(checks, fmt.Sprintf("typeof(%s)!='text' OR length(CAST(%s AS BLOB))>%d", col, col, limit)) + } + var bad bool + if err := q.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM review_front_frames WHERE "+strings.Join(checks, " OR ")+")").Scan(&bad); err != nil { + return err + } + if bad { + return runUnavailable() + } + return nil +} + +// Startup checks shared schema only; optional row content is isolated by readers. +func validateFrontDefinition(ctx context.Context, q EvidenceQuery) error { + rows, err := q.QueryContext(ctx, `SELECT name,CASE WHEN length(CAST(sql AS BLOB))<=16384 THEN sql END FROM sqlite_schema WHERE tbl_name='review_front_frames' AND (type='table' OR sql IS NOT NULL) LIMIT 3`) + if err != nil { + return err + } + count := 0 + for rows.Next() { + var name, body string + if err = rows.Scan(&name, &body); err != nil { + break + } + count++ + if name != "review_front_frames" || strings.TrimSpace(body) != strings.TrimSpace(FrontSchemaSQL()[0]) { + err = runUnavailable() + break + } + } + if err == nil { + err = rows.Err() + } + rows.Close() + if err != nil { + return err + } + if count != 1 { + return runUnavailable() + } + return nil +} diff --git a/internal/reviewexec/hosted_priority_test.go b/internal/reviewexec/hosted_priority_test.go index 03b6f37b1..e5c049692 100644 --- a/internal/reviewexec/hosted_priority_test.go +++ b/internal/reviewexec/hosted_priority_test.go @@ -3,18 +3,18 @@ package reviewexec import ( "bytes" "context" + "crypto/sha256" "database/sql" + "encoding/json" "errors" + "fmt" "log/slog" "strings" - - "crypto/sha256" - "fmt" - "github.com/benhook1013/FireController/internal/core" "sync" "testing" "time" + "github.com/benhook1013/FireController/internal/core" "github.com/benhook1013/FireController/internal/reviewprovider" ) @@ -191,6 +191,61 @@ func TestHostedPriorityInvalidIntentCannotReserveTurn(t *testing.T) { f.start(t, attemptProject, lower) } +func TestHostedCooldownQueuePriorityProjection(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + lower := f.enqueue(t, attemptProject, "display-later-first", "hosted", 4, 1) + due := priorityCooldown(t, f, lower, 4, 3*time.Minute) + head := f.enqueue(t, attemptProject, "display-head-second", "hosted", 2, 1) + priorityCooldown(t, f, head, 2, 4*time.Minute) + f.e.schedulingNow = func() time.Time { return due.Add(-time.Minute) } + path := roundProgressPath(attemptProject) + "?pull_numbers=4,2&view=stages" + read := func(version string) RoundProgress { + t.Helper() + response := versionWaitRead(t, f, path, version) + var result RoundProgress + if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + if len(result.Items) != 2 { + t.Fatal("missing displayed rows", result) + } + return result + } + before := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "receipts") + snapshotTable(t, f, "events") + result := read("5") + lowerWait, headWait := result.Items[0].Channels[0].Wait, result.Items[1].Channels[0].Wait + if lowerWait == nil || headWait == nil || lowerWait.QueueAheadPullNumber != 2 || headWait.QueueAheadPullNumber != 0 || lowerWait.RetryNotBefore != due.Format(time.RFC3339Nano) { + t.Fatal("timer masked actual accepted priority", result) + } + // Even while both independent timers are in the future, diagnostics explain + // the actual earlier accepted request before the later request's timer. + w := statusHTTP(t, f, lower.ID, "", "wait=0") + if w.Header().Get(queuedDiagnosticHeader) != "queue_order" { + t.Fatal("later cooldown hid queue order", w.Header()) + } + for _, version := range []string{"1", "2", "3"} { + old := read(version) + if old.Items[0].Channels[0].Wait == nil || old.Items[0].Channels[0].Wait.QueueAheadPullNumber != 0 { + t.Fatal("legacy wait shape changed", version, old) + } + if strings.Contains(versionWaitRead(t, f, path, version).Body.String(), "queue_ahead_pull_number") { + t.Fatal("queue hint escaped negotiation", version) + } + } + if after := snapshotTable(t, f, "review_operations") + snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "review_execution_attempts") + snapshotTable(t, f, "receipts") + snapshotTable(t, f, "events"); before != after { + t.Fatal("presentation read changed retained work") + } + timerControl(t, f, head.ID, "pause", "display-pause-head") + if read("5").Items[0].Channels[0].Wait.QueueAheadPullNumber != 0 { + t.Fatal("paused earlier request reserved display priority") + } + timerControl(t, f, head.ID, "cancel", "display-cancel-head") + if read("5").Items[0].Channels[0].Wait.QueueAheadPullNumber != 0 { + t.Fatal("mere earlier queue row reserved display priority") + } +} + // Damaged retained history cannot authorize a queue jump or stop another project. func TestPriorityConfigurationHistoryIsolation(t *testing.T) { for _, channel := range []string{"cli", "hosted"} { @@ -295,3 +350,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 dc149e503..b502351cd 100644 --- a/internal/reviewexec/hosted_wait.go +++ b/internal/reviewexec/hosted_wait.go @@ -18,14 +18,20 @@ const operationWaitHeader = "X-FC-Operation-Wait" // Version 1 advertised Hosted cooldown baselines only. Keep its existing CLI // queued/pause shape; version 2 additionally understands CLI quota baselines. // Version 3 adds the retained provider allowance estimate, never a retry clock. +// Version 5 extends version 3 with current same-project Hosted queue priority. func operationWaitForResponse(wait *OperationWait, channel, version string) *OperationWait { - if wait == nil || version != "1" && version != "2" && version != "3" { + if wait == nil || version != "1" && version != "2" && version != "3" && version != "5" { return nil } + copy := *wait + if version != "5" { + copy.QueueAheadPullNumber = 0 + } + wait = © if version == "1" && channel == "cli" && wait.BaselineAttemptID != "" { return &OperationWait{Paused: wait.Paused} } - if version != "3" { + if version != "3" && version != "5" { copy := *wait copy.CLIAllowance = nil return © @@ -39,7 +45,7 @@ func operationForResponse(operation Operation, version string) Operation { // response capabilities negotiates their public request/response contract. operation.AllowOutOfOrder, operation.OverrideFileLimit = false, false operation.Wait = operationWaitForResponse(operation.Wait, operation.Channel, version) - if version != "3" { + if version != "3" && version != "5" { operation.Allowance = nil } return operation @@ -48,10 +54,11 @@ func operationForResponse(operation Operation, version string) Operation { // OperationWait retains dispatch scheduling, not provider availability or review // completion. A paused ordinary queued operation need not have a cooldown. type OperationWait struct { - CLIAllowance *AllowanceObservation `json:"cli_allowance,omitempty"` - BaselineAttemptID string `json:"baseline_attempt_id,omitempty"` - RetryNotBefore string `json:"retry_not_before,omitempty"` - Paused bool `json:"paused"` + QueueAheadPullNumber int64 `json:"queue_ahead_pull_number,omitempty"` + CLIAllowance *AllowanceObservation `json:"cli_allowance,omitempty"` + BaselineAttemptID string `json:"baseline_attempt_id,omitempty"` + RetryNotBefore string `json:"retry_not_before,omitempty"` + Paused bool `json:"paused"` } func waitUnavailable() error { diff --git a/internal/reviewexec/hosted_wait_validation.go b/internal/reviewexec/hosted_wait_validation.go index d8a93101f..703fba9f2 100644 --- a/internal/reviewexec/hosted_wait_validation.go +++ b/internal/reviewexec/hosted_wait_validation.go @@ -18,6 +18,7 @@ func ValidateOperationWaitsSnapshot(ctx context.Context, tx *sql.Tx) error { LEFT JOIN review_operations o ON o.id=a.operation_id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE (o.id IS NULL OR o.attempt_id<>a.id) AND t.reason IN ('allowance_exhausted','hosted_allowance_cooldown') + UNION SELECT o.project_id,o.id FROM review_operations o JOIN review_execution_attempts a ON a.operation_id=o.id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE a.id<>o.attempt_id AND t.reason IN ('pull_scheduling_paused','automation_authorization_changed') ORDER BY 2`, cliDraftWait, cliDraftWait) if err != nil { return err @@ -96,7 +97,7 @@ func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) foundCurrent = true continue } - _, draft, err := historicalCLIDraftOperation(ctx, tx, o, a) + _, draft, err := historicalUnusedPreparationOperation(ctx, tx, o, a, true) if err != nil { if errors.Is(err, sql.ErrNoRows) { return waitUnavailable() diff --git a/internal/reviewexec/http.go b/internal/reviewexec/http.go index b6c64a784..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 } @@ -198,9 +200,7 @@ func (e *Engine) readOperationHTTP(w http.ResponseWriter, r *http.Request) { operation.Observer = e.observerStatus(operation) } operation = operationForResponse(operation, r.Header.Get(operationWaitHeader)) - if operation.Channel == "cli" && operation.State == "queued" && e.sharedCLIQuotaWait(r.Context(), scope, operation.ID) { - w.Header().Set("X-FC-Review-Queued", "cli_quota_wait") - } + e.queuedResponseHeader(w, r, scope, operation.ID, operation.State, operation.Channel, operation.Revision) core.WriteJSON(w, http.StatusOK, operation) } @@ -221,38 +221,3 @@ func (e *Engine) readExecutionConfigurationHTTP(w http.ResponseWriter, r *http.R } core.WriteJSON(w, http.StatusOK, configuration) } - -// sharedCLIQuotaWait supplies only a diagnostic for an already authorized read. -// Invalid or unavailable bindings provide no account-level quota assertion. -func (e *Engine) sharedCLIQuotaWait(ctx context.Context, scope core.Scope, id string) bool { - waiting := false - err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { - o, err := readOperationBase(ctx, tx, scope.ProjectID, id) - if err != nil { - return err - } - if o.Channel != "cli" || o.State != "queued" { - return nil - } - c, revision, err := readConfiguration(ctx, tx, scope.ProjectID) - if err != nil { - return err - } - compatible, err := compatibleQueuedConfiguration(ctx, tx, o, c, revision) - if err != nil { - return err - } - capability, ok := e.capabilities[c.CapabilityID] - if !compatible || !ok || e.validateConfiguration(c) != nil || o.CapabilityFingerprint != capability.Fingerprint { - return nil - } - now := e.sampleExecutionTime() - due, err := cliAccountRetryDeadline(ctx, tx, capability, now) - if err != nil { - return err - } - waiting = now.Before(due) - return nil - }) - return err == nil && waiting -} diff --git a/internal/reviewexec/operation_status.go b/internal/reviewexec/operation_status.go index 1bc5330a5..f22794ddd 100644 --- a/internal/reviewexec/operation_status.go +++ b/internal/reviewexec/operation_status.go @@ -172,11 +172,9 @@ func (e *Engine) readOperationStatusHTTP(w http.ResponseWriter, r *http.Request) value.Observer = nil } value.Wait = operationWaitForResponse(value.Wait, value.Channel, r.Header.Get(operationWaitHeader)) - if r.Header.Get(operationWaitHeader) != "3" { + if version := r.Header.Get(operationWaitHeader); version != "3" && version != "5" { value.RetryNotBefore = "" } - if value.Channel == "cli" && value.State == "queued" && e.sharedCLIQuotaWait(r.Context(), scope, value.ID) { - w.Header().Set("X-FC-Review-Queued", "cli_quota_wait") - } + e.queuedResponseHeader(w, r, scope, value.ID, value.State, value.Channel, value.Revision) core.WriteJSON(w, http.StatusOK, value) } diff --git a/internal/reviewexec/policy.go b/internal/reviewexec/policy.go index 7bdf8cce1..eb0230529 100644 --- a/internal/reviewexec/policy.go +++ b/internal/reviewexec/policy.go @@ -112,15 +112,19 @@ func (e *Engine) ConfigurePolicy(ctx context.Context, scope core.Scope, key stri func readPolicy(ctx context.Context, tx *sql.Tx, project string) (PolicyRecord, error) { var record PolicyRecord var body string - err := tx.QueryRowContext(ctx, `SELECT project_id,revision,actor_id,created_at,body_json FROM review_policy_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, project).Scan(&record.ProjectID, &record.Revision, &record.ActorID, &record.RecordedAt, &body) + var bodyValue, revisionValue any + err := tx.QueryRowContext(ctx, `SELECT project_id,revision,actor_id,created_at,body_json FROM review_policy_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, project).Scan(&record.ProjectID, &revisionValue, &record.ActorID, &record.RecordedAt, &bodyValue) if errors.Is(err, sql.ErrNoRows) { return PolicyRecord{}, core.Fail("reviews_policy_unconfigured", "Configure explicit project review requirements before assessing policy.", 409) } if err != nil { return PolicyRecord{}, err } - if len(body) > 1024 || strictjson.Decode([]byte(body), &record.Policy) != nil || !validPolicy(record.Policy) { - return PolicyRecord{}, core.Fail("storage_unavailable", "Stored project review policy is unavailable.", 500) + var validBody, validRevision bool + body, validBody = bodyValue.(string) + record.Revision, validRevision = revisionValue.(int64) + if !validBody || !validRevision || record.Revision < 1 || len(body) > 1024 || strictjson.Decode([]byte(body), &record.Policy) != nil || !validPolicy(record.Policy) { + return PolicyRecord{}, automaticProjectStateFailure("storage_unavailable", "Stored project review policy is unavailable.", 500) } return record, nil } diff --git a/internal/reviewexec/policy_admission.go b/internal/reviewexec/policy_admission.go index cea371e88..7255d65cb 100644 --- a/internal/reviewexec/policy_admission.go +++ b/internal/reviewexec/policy_admission.go @@ -47,6 +47,12 @@ func policyAdmissionConflict() error { func (e *Engine) currentExecutionContext(ctx context.Context, tx *sql.Tx, operation Operation) (ExecutionContext, error) { result := ExecutionContext{Operation: operation} + if err := requirePullScheduling(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil { + return ExecutionContext{}, err + } + if err := e.requireAutomaticOperation(ctx, tx, operation); err != nil { + return ExecutionContext{}, err + } if err := requireSourceObligationsClear(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil { return ExecutionContext{}, err } diff --git a/internal/reviewexec/queued_diagnostic.go b/internal/reviewexec/queued_diagnostic.go new file mode 100644 index 000000000..52e88588b --- /dev/null +++ b/internal/reviewexec/queued_diagnostic.go @@ -0,0 +1,199 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "net/http" + + "github.com/benhook1013/FireController/internal/core" +) + +const queuedDiagnosticHeader = "X-FC-Review-Queued" +const queuedReservationHeader = "X-FC-Review-Reservation" + +type queuedReservation struct { + Kind string `json:"kind"` + OperationID string `json:"operation_id,omitempty"` + PullNumber int64 `json:"pull_number,omitempty"` + Channel string `json:"channel,omitempty"` + State string `json:"state,omitempty"` +} + +// A best-effort current scheduling hint, never retained journal state or +// 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. +func (e *Engine) queuedResponseHeader(w http.ResponseWriter, r *http.Request, scope core.Scope, id, state, channel string, revision int64) { + if state != "queued" { + return + } + cause, reservation := e.queuedDiagnosticDetails(r.Context(), 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" { + cause = "awaiting_scheduler" + } + if cause != "" { + w.Header().Set(queuedDiagnosticHeader, cause) + } + if reservation != nil { + if body, err := json.Marshal(reservation); err == nil && len(body) <= 512 { + w.Header().Set(queuedReservationHeader, string(body)) + } + } +} +func (e *Engine) queuedDiagnostic(ctx context.Context, scope core.Scope, id string, revision int64) string { + cause, _ := e.queuedDiagnosticDetails(ctx, scope, id, revision) + return cause +} + +func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, id string, revision int64) (string, *queuedReservation) { + cause := "" + var reservation *queuedReservation + err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { + op, err := readOperation(ctx, tx, scope.ProjectID, id) + if err != nil { + return err + } + 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 + } + var originalJSON, latestJSON sql.NullString + var repositoryID, latestRevision int64 + err = tx.QueryRowContext(ctx, `SELECT CASE WHEN length(CAST(c.body_json AS BLOB))<=32768 THEN c.body_json END,CASE WHEN length(CAST(latest.body_json AS BLOB))<=32768 THEN latest.body_json END,p.github_repository_id,latest.revision FROM review_execution_config c JOIN projects p ON p.id=c.project_id JOIN review_execution_config latest ON latest.project_id=c.project_id AND latest.revision=(SELECT MAX(revision) FROM review_execution_config WHERE project_id=c.project_id) WHERE c.project_id=? AND c.revision=?`, op.ProjectID, op.ConfigurationRevision).Scan(&originalJSON, &latestJSON, &repositoryID, &latestRevision) + if err != nil { + return err + } + var original, latest Configuration + if !originalJSON.Valid || !latestJSON.Valid || json.Unmarshal([]byte(originalJSON.String), &original) != nil || json.Unmarshal([]byte(latestJSON.String), &latest) != nil || validateConfigurationShape(original) != nil || validateConfigurationShape(latest) != nil { + return adjudicationStorageError() + } + switch { + case op.Wait != nil && op.Wait.Paused: + cause = "operation_paused" + return nil + case latest.Paused: + 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 + } + if op.Channel == "cli" { + compatible, err := compatibleQueuedConfiguration(ctx, tx, op, latest, latestRevision) + if err != nil { + return err + } + if capability, ok := e.capabilities[latest.CapabilityID]; compatible && ok && e.validateConfiguration(latest) == nil && capability.Fingerprint == op.CapabilityFingerprint { + now := e.sampleExecutionTime() + due, err := cliAccountRetryDeadline(ctx, tx, capability, now) + if err != nil { + return err + } + if now.Before(due) { + cause = "cli_quota_wait" + return nil + } + } + } + earlier, err := e.earlierQueuedReviewIntent(ctx, tx, op, latest, latestRevision) + if err != nil { + return err + } + if earlier != nil { + cause = "queue_order" + return nil + } + if op.Wait != nil && op.Wait.RetryNotBefore != "" && e.sampleExecutionTime().Before(mustWaitTime(op.Wait.RetryNotBefore)) { + cause = "cooldown" + return nil + } + cause = "awaiting_scheduler" + capability, ok := e.capabilities[original.CapabilityID] + if !ok || capability.Fingerprint != op.CapabilityFingerprint { + return nil + } + reservation, err = queuedReservationHolder(ctx, tx, op, capability, repositoryID) + if reservation != nil { + cause = "reservation_busy" + } + return err + }) + if err != nil { + return "", nil + } + return cause, reservation +} + +// One matching reservation is enough to explain waiting. Joined current identity +// must agree before naming a same-project holder; no age-based stale inference +// or foreign operation facts leave this read. Hosted account exclusivity is per +// repository, while CLI retains the shared account boundary. +func queuedReservationHolder(ctx context.Context, tx *sql.Tx, waiting Operation, capability Capability, repositoryID int64) (*queuedReservation, error) { + var provider, account, channel, attemptID string + var repo, pull int64 + var aOperation, aProject, aProvider, aAccount, aState, anchor sql.NullString + var oID, oProject, oAttempt, oChannel, oState, oHead sql.NullString + var aRevision, oPull, oRepo sql.NullInt64 + err := tx.QueryRowContext(ctx, `SELECT r.provider,r.account,r.action_class,r.repository_id,r.pull_number,r.attempt_id, + a.operation_id,a.project_id,a.provider,a.account,a.state,a.revision, + CASE WHEN length(CAST(a.anchor_json AS BLOB))<=2048 THEN a.anchor_json END, + o.id,o.project_id,o.attempt_id,o.channel,o.state,o.head_sha,o.pull_number,p.github_repository_id + FROM review_execution_reservations r + LEFT JOIN review_execution_attempts a ON a.id=r.attempt_id + LEFT JOIN review_operations o ON o.id=a.operation_id + LEFT JOIN projects p ON p.id=o.project_id + WHERE r.provider=? AND r.action_class=? AND ((r.account=? AND (?='cli' OR r.repository_id=?)) OR (r.repository_id=? AND r.pull_number=?)) + ORDER BY r.attempt_id LIMIT 1`, capability.Provider, waiting.Channel, capability.Account, waiting.Channel, repositoryID, repositoryID, waiting.PullNumber).Scan(&provider, &account, &channel, &repo, &pull, &attemptID, &aOperation, &aProject, &aProvider, &aAccount, &aState, &aRevision, &anchor, &oID, &oProject, &oAttempt, &oChannel, &oState, &oHead, &oPull, &oRepo) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + unproven := &queuedReservation{Kind: "reservation_unproven"} + if repo < 1 || pull < 1 || pull > 2147483647 || !sha.MatchString(oHead.String) || !hostedObservationID(attemptID, "review_attempt_") || !hostedObservationID(oID.String, "review_operation_") || oID.String == waiting.ID || aOperation.String != oID.String || aProject.String == "" || aProject.String != oProject.String || aProvider.String != provider || aAccount.String != account || oAttempt.String != attemptID || oChannel.String != channel || oPull.Int64 != pull || oRepo.Int64 != repo || aRevision.Int64 < 1 || aState.String != oState.String || !reservationLiveState(aState.String) || !anchor.Valid { + return unproven, nil + } + if anchor.String == "null" { + if aState.String != "preparing" { + return unproven, nil + } + } else { + var admitted Anchor + if json.Unmarshal([]byte(anchor.String), &admitted) != nil || encoded(admitted) != anchor.String || !validEvidenceAnchor(admitted) || admitted.RepositoryID != repo || admitted.PullNumber != pull || admitted.CandidateSHA != oHead.String { + return unproven, nil + } + } + if oProject.String != waiting.ProjectID { + return &queuedReservation{Kind: "other_project"}, nil + } + return &queuedReservation{Kind: "same_project", OperationID: oID.String, PullNumber: pull, Channel: channel, State: aState.String}, nil +} + +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) { + if state.Operation != nil { + o := state.Operation + e.queuedResponseHeader(w, r, scope, o.ID, o.State, o.Channel, o.Revision) + } +} diff --git a/internal/reviewexec/requests.go b/internal/reviewexec/requests.go index 14020d509..fa931627e 100644 --- a/internal/reviewexec/requests.go +++ b/internal/reviewexec/requests.go @@ -120,18 +120,19 @@ func (e *Engine) Configure(ctx context.Context, scope core.Scope, key string, c } func readConfiguration(ctx context.Context, tx *sql.Tx, project string) (Configuration, int64, error) { - var body string - var revision int64 + var rawRevision, rawBody any var c Configuration - err := tx.QueryRowContext(ctx, `SELECT revision,body_json FROM review_execution_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, project).Scan(&revision, &body) + err := tx.QueryRowContext(ctx, `SELECT revision,body_json FROM review_execution_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, project).Scan(&rawRevision, &rawBody) if errors.Is(err, sql.ErrNoRows) { return c, 0, core.Fail("reviews_unconfigured", "Review execution is not configured for this project.", 409) } if err != nil { return c, 0, err } - if json.Unmarshal([]byte(body), &c) != nil { - return c, 0, core.Fail("storage_unavailable", "Stored review configuration is unavailable.", 500) + revision, revisionOK := rawRevision.(int64) + body, bodyOK := rawBody.(string) + if !revisionOK || revision < 1 || !bodyOK || json.Unmarshal([]byte(body), &c) != nil { + return c, 0, automaticProjectStateFailure("storage_unavailable", "Stored review configuration is unavailable.", 500) } return c, revision, nil } @@ -161,6 +162,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 @@ -223,13 +227,40 @@ func readOperation(ctx context.Context, tx EvidenceQuery, project, id string) (O return o, err } +// retainedOperationDecodeError is produced only by a destination scanner after +// SQL has returned a value. Query, transaction and context errors never acquire +// this classification, so priority can isolate corrupt candidates safely. +type retainedOperationDecodeError struct{ error } + +func (e *retainedOperationDecodeError) Unwrap() error { return e.error } + +type operationValueScanner[T string | int64 | bool] struct{ destination *T } + +func (s operationValueScanner[T]) Scan(value any) error { + var decoded sql.Null[T] + if err := decoded.Scan(value); err != nil || !decoded.Valid { + return &retainedOperationDecodeError{core.Fail("storage_unavailable", "Stored review operation is unavailable.", 500)} + } + *s.destination = decoded.V + return nil +} + +func operationValue[T string | int64 | bool](destination *T) sql.Scanner { + return operationValueScanner[T]{destination: destination} +} + +func isRetainedOperationDecodeError(err error) bool { + var malformed *retainedOperationDecodeError + return errors.As(err, &malformed) +} + func readOperationBase(ctx context.Context, tx EvidenceQuery, project, id string) (Operation, error) { var o Operation orderColumn, limitColumn, err := operationFlagColumns(ctx, tx) 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(&o.ID, &o.ProjectID, &o.ActorID, &o.WorkerID, &o.ConfigurationRevision, &o.PolicyRevision, &o.CapabilityFingerprint, &o.PullNumber, &o.Channel, &o.HeadSHA, &o.State, &o.Revision, &o.Reason, &o.AttemptID, &o.CreatedAt, &o.UpdatedAt, &o.AllowOutOfOrder, &o.OverrideFileLimit) + 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)) if errors.Is(err, sql.ErrNoRows) { return o, core.Fail("not_found", "The review operation is unavailable in this project.", 404) } diff --git a/internal/reviewexec/round_controls.go b/internal/reviewexec/round_controls.go index 52a21a56e..d1b474915 100644 --- a/internal/reviewexec/round_controls.go +++ b/internal/reviewexec/round_controls.go @@ -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/round_progress.go b/internal/reviewexec/round_progress.go index 504b72cb4..6525a2e95 100644 --- a/internal/reviewexec/round_progress.go +++ b/internal/reviewexec/round_progress.go @@ -67,6 +67,9 @@ func (e *Engine) ReadRoundProgressStages(ctx context.Context, scope core.Scope, } func (e *Engine) readRoundProgress(ctx context.Context, scope core.Scope, numbers []int64, stages bool) (RoundProgress, error) { + return e.readRoundProgressWithQueuePriority(ctx, scope, numbers, stages, false) +} +func (e *Engine) readRoundProgressWithQueuePriority(ctx context.Context, scope core.Scope, numbers []int64, stages, queuePriority bool) (RoundProgress, error) { if ctx == nil || e == nil || e.store == nil || !identifier.MatchString(scope.ProjectID) || !validRoundProgressNumbers(numbers) { return RoundProgress{}, invalid() } @@ -95,7 +98,7 @@ func (e *Engine) readRoundProgress(ctx context.Context, scope core.Scope, number } if stages { progress.PendingExecution, progress.PendingAdjudication = &execution, &adjudication - progress.Wait, err = readChannelWait(ctx, tx, scope.ProjectID, number, channel) + progress.Wait, err = e.readChannelWait(ctx, tx, scope.ProjectID, number, channel, queuePriority) if err != nil { return err } @@ -114,7 +117,7 @@ func (e *Engine) readRoundProgress(ctx context.Context, scope core.Scope, number } // Project only a current queued intent, never infer a timer from a held run. -func readChannelWait(ctx context.Context, tx *sql.Tx, project string, number int64, channel string) (*OperationWait, error) { +func (e *Engine) readChannelWait(ctx context.Context, tx *sql.Tx, project string, number int64, channel string, queuePriority bool) (*OperationWait, error) { var id string err := tx.QueryRowContext(ctx, `SELECT o.id FROM review_operations o JOIN review_operation_waits w ON w.operation_id=o.id WHERE o.project_id=? AND o.pull_number=? AND o.channel=? AND o.state='queued' AND o.attempt_id='' ORDER BY o.created_at,o.id LIMIT 1`, project, number, channel).Scan(&id) if errors.Is(err, sql.ErrNoRows) { @@ -127,5 +130,24 @@ func readChannelWait(ctx context.Context, tx *sql.Tx, project string, number int if err != nil { return nil, err } - return currentOperationWait(o), nil + wait := currentOperationWait(o) + if !queuePriority || channel != "hosted" || wait == nil || wait.Paused { + return wait, nil + } + // Reuse actual accepted-intent admission priority, not the first PR with + // remaining rounds. The latter may be skipped legitimately by lookahead. + // These are bounded local reads in this same authorized snapshot; no source + // refresh or provider request is performed. An unavailable hint leaves the + // original retained timer intact rather than fabricating a queue blocker. + configuration, revision, err := readConfiguration(ctx, tx, project) + if err != nil { + return wait, nil + } + earlier, err := e.earlierQueuedReviewIntent(ctx, tx, o, configuration, revision) + if err == nil && earlier != nil { + copy := *wait + copy.QueueAheadPullNumber = earlier.PullNumber + wait = © + } + return wait, nil } diff --git a/internal/reviewexec/round_progress_http.go b/internal/reviewexec/round_progress_http.go index b7f316a60..3494775b5 100644 --- a/internal/reviewexec/round_progress_http.go +++ b/internal/reviewexec/round_progress_http.go @@ -54,7 +54,7 @@ func (e *Engine) readRoundProgressHTTP(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } - progress, err := e.readRoundProgress(r.Context(), scope, numbers, r.URL.Query().Get("view") == "stages") + progress, err := e.readRoundProgressWithQueuePriority(r.Context(), scope, numbers, r.URL.Query().Get("view") == "stages", r.Header.Get(operationWaitHeader) == "5") if err != nil { core.WriteError(w, err) return 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 9fc2264a1..b1233f689 100644 --- a/internal/reviewexec/run_http.go +++ b/internal/reviewexec/run_http.go @@ -87,6 +87,7 @@ func waitCapacityError(err error) bool { func (e *Engine) enqueueRunHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Add("Vary", "Prefer") + w.Header().Add("Vary", operationWaitHeader) scope, err := e.store.Scope(r, "write") if err != nil { core.WriteError(w, err) @@ -159,6 +160,7 @@ func (e *Engine) enqueueRunHTTP(w http.ResponseWriter, r *http.Request) { return } if terminal { + e.queuedRunResponseHeader(w, r, scope, state) core.WriteJSON(w, http.StatusOK, state) return } @@ -168,6 +170,7 @@ func (e *Engine) enqueueRunHTTP(w http.ResponseWriter, r *http.Request) { func (e *Engine) readRunHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Add("Vary", "Prefer") + w.Header().Add("Vary", operationWaitHeader) scope, err := e.store.Scope(r, "read") if err != nil { core.WriteError(w, err) @@ -196,5 +199,6 @@ func (e *Engine) readRunHTTP(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } + e.queuedRunResponseHeader(w, r, scope, state) core.WriteJSON(w, http.StatusOK, state) } diff --git a/internal/reviewexec/run_http_test.go b/internal/reviewexec/run_http_test.go index 9e64fa104..63d1202c7 100644 --- a/internal/reviewexec/run_http_test.go +++ b/internal/reviewexec/run_http_test.go @@ -13,7 +13,7 @@ import ( "github.com/benhook1013/FireController/internal/reviewprovider" ) -func runHTTPCall(t *testing.T, f *attemptFixture, handler http.Handler, method, path, body, key, wait string) *httptest.ResponseRecorder { +func runHTTPCall(t *testing.T, f *attemptFixture, handler http.Handler, method, path, body, key, wait string, waitVersion ...string) *httptest.ResponseRecorder { t.Helper() r := httptest.NewRequest(method, path, strings.NewReader(body)) r.Header.Set("Authorization", "Bearer "+f.writer) @@ -25,11 +25,78 @@ func runHTTPCall(t *testing.T, f *attemptFixture, handler http.Handler, method, if wait != "" { r.Header.Set("Prefer", wait) } + if len(waitVersion) > 0 { + r.Header.Set(operationWaitHeader, waitVersion[0]) + } w := httptest.NewRecorder() handler.ServeHTTP(w, r) return w } +func TestRunHTTPWaitNegotiationVary(t *testing.T) { + f := selectionFixture(t) + mux := http.NewServeMux() + f.e.Register(mux) + path := "/api/v1/projects/" + attemptProject + "/reviews/selections" + versions := []string{"", "1", "2", "3", "4", "5", "unsupported"} + assertVary := func(t *testing.T, w *httptest.ResponseRecorder) { + t.Helper() + vary := strings.Join(w.Header().Values("Vary"), ",") + for _, header := range []string{"Prefer", operationWaitHeader} { + if !strings.Contains(vary, header) { + t.Errorf("missing Vary: %s in %v", header, w.Header()) + } + } + } + var original []byte + for _, version := range versions { + t.Run("POST/"+version, func(t *testing.T) { + w := runHTTPCall(t, f, mux, "POST", path, `{"channel":"cli"}`, "negotiated-run", "wait=0", version) + if w.Code != http.StatusAccepted { + t.Fatal("selection not accepted", w.Code, w.Body.String()) + } + assertVary(t, w) + if original == nil { + original = append([]byte(nil), w.Body.Bytes()...) + } else if !bytes.Equal(original, w.Body.Bytes()) { + t.Fatal("negotiation changed original receipt") + } + }) + } + var receipt Receipt + if err := json.Unmarshal(original, &receipt); err != nil { + t.Fatal(err) + } + // Select the later independent PR while the front PR is a draft, then + // accept a front-PR intent before reading the original selected child. + selectionNext(t, f, &refreshTestReader{pull: func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { + draft := n == 2 + return reviewprovider.Pull{Number: n, RepositoryID: 801, State: "open", IsDraft: &draft, HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }}) + f.enqueue(t, attemptProject, "front-run-intent", "cli", 2, 1) + before := selectionCounts(t, f) + for _, version := range versions { + t.Run("GET/"+version, func(t *testing.T) { + w := runHTTPCall(t, f, mux, "GET", path+"/"+receipt.ID, "", "", "wait=0", version) + var state RunState + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &state) != nil || state.Selection.ID != receipt.ID || state.Operation == nil || state.Operation.PullNumber != 4 || state.Operation.State != "queued" { + t.Fatal("original selected child unavailable", w.Code, w.Body.String()) + } + assertVary(t, w) + want := "awaiting_scheduler" + if version == "2" || version == "3" || version == "4" || version == "5" { + want = "queue_order" + } + if got := w.Header().Get(queuedDiagnosticHeader); got != want { + t.Fatalf("diagnostic=%q, want %q", got, want) + } + }) + } + if selectionCounts(t, f) != before { + t.Fatal("negotiated reads changed durable state") + } +} + func TestRunHTTPStrictOptionalAssertionsAndOriginalReceipt(t *testing.T) { f := selectionFixture(t) mux := http.NewServeMux() diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 4a073bd10..02081f181 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -40,7 +40,7 @@ const runColumns = `id,project_id,actor_id,worker_id,channel,configuration_revis func validRunID(id string) bool { return hostedObservationID(id, "review_selection_") } func runPending(state string) bool { return state == "queued" || state == "selecting" } func runUnavailable() error { - return core.Fail("storage_unavailable", "Stored review selection is unavailable.", 500) + return automaticProjectStateFailure("storage_unavailable", "Stored review selection is unavailable.", 500) } func validRun(r Run) bool { created, e1 := time.Parse(time.RFC3339Nano, r.CreatedAt) @@ -62,10 +62,13 @@ func validRun(r Run) bool { } func readRun(ctx context.Context, q EvidenceQuery, project, id string) (Run, error) { var r Run - err := q.QueryRowContext(ctx, `SELECT `+runColumns+` FROM review_selections WHERE project_id=? AND id=?`, project, id).Scan(&r.ID, &r.ProjectID, &r.ActorID, &r.WorkerID, &r.Channel, &r.ConfigurationRevision, &r.PolicyRevision, &r.CapabilityFingerprint, &r.ExpectedPullNumber, &r.State, &r.Reason, &r.Revision, &r.OperationID, &r.CreatedAt, &r.UpdatedAt) + err := scanRoundValues(q.QueryRowContext(ctx, `SELECT `+runColumns+` FROM review_selections WHERE project_id=? AND id=?`, project, id), &r.ID, &r.ProjectID, &r.ActorID, &r.WorkerID, &r.Channel, &r.ConfigurationRevision, &r.PolicyRevision, &r.CapabilityFingerprint, &r.ExpectedPullNumber, &r.State, &r.Reason, &r.Revision, &r.OperationID, &r.CreatedAt, &r.UpdatedAt) if errors.Is(err, sql.ErrNoRows) { return r, core.Fail("not_found", "The review selection is unavailable in this project.", 404) } + if automaticProjectRefused(err) { + return Run{}, runUnavailable() + } if err != nil { return r, err } @@ -126,7 +129,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 { @@ -191,6 +194,16 @@ func (e *Engine) enqueueRunTx(ctx context.Context, tx *sql.Tx, scope core.Scope, } func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configuration, int64, string, error) { + if err := e.requireAutomaticRun(ctx, tx, r); err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Status == 403 { + return Configuration{}, 0, "automation_authorization_changed", nil + } + return Configuration{}, 0, "", err + } + if reason, err := automaticSourceRecoveryFence(ctx, tx, r); err != nil || reason != "" { + return Configuration{}, 0, reason, err + } c, revision, err := readConfiguration(ctx, tx, r.ProjectID) if err != nil { return c, 0, "", err @@ -223,6 +236,19 @@ func (e *Engine) runBinding(ctx context.Context, tx *sql.Tx, r Run) (Configurati if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND channel=? AND state IN ('queued','preparing','posting','active','uncertain'))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { return c, 0, "", err } + if busy { + var automatic bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id=?)`, r.ProjectID, r.ID).Scan(&automatic); err != nil { + return c, 0, "", err + } + if automatic { + // Existing queued requests retain their turn; automatic front + // evaluation considers only the prefix before the earliest one. + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND channel=? AND state IN ('preparing','posting','active','uncertain'))`, r.ProjectID, r.Channel).Scan(&busy); err != nil { + return c, 0, "", err + } + } + } if busy { return c, repository, "review_inflight", nil } @@ -263,15 +289,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 string + 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 } @@ -287,6 +316,16 @@ func (e *Engine) RecoverReviewRuns(ctx context.Context) error { } for _, k := range keys { r, err := readRun(ctx, tx, k.p, k.id) + if automaticProjectRefused(err) || err == nil && r.Revision == math.MaxInt64 { + didChange, err := quarantineSelection(ctx, tx, Run{ProjectID: k.p, ID: k.id, State: "selecting", Revision: k.revision}) + if err != nil { + return err + } + if didChange { + changed = append(changed, k.id) + } + continue + } if err != nil { return err } @@ -433,3 +472,20 @@ func AbandonReviewRuns(ctx context.Context, tx *sql.Tx, at time.Time) (int64, er } return int64(len(selected)), nil } + +// A corrupt revision is an opaque retained value, never an arithmetic operand. +const selectionClaimRevision = `CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision ELSE 0 END` + +// Quarantine only the observed pending row. Keep its original damaged fields +// and any child link for diagnosis; do not fabricate a readable history entry. +func quarantineSelection(ctx context.Context, tx *sql.Tx, expected Run) (bool, error) { + if expected.State != "queued" && expected.State != "selecting" { + return false, nil + } + result, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held',reason='local_read_unavailable',revision=CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision+1 ELSE revision END WHERE project_id=? AND id=? AND state=? AND `+selectionClaimRevision+`=?`, expected.ProjectID, expected.ID, expected.State, expected.Revision) + if err != nil { + return false, err + } + n, err := result.RowsAffected() + return n == 1, err +} diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index bf4dd7028..699e5fe22 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -7,6 +7,7 @@ import ( "github.com/benhook1013/FireController/internal/core" "github.com/benhook1013/FireController/internal/reviewprovider" "github.com/benhook1013/FireController/internal/reviews" + "math" "reflect" "slices" "sync" @@ -179,7 +180,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) @@ -244,6 +245,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 +253,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 +267,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 { @@ -398,7 +407,12 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR if workerCtx.Err() != nil { return } - worked, err := e.runNext(workerCtx, owned) + generated, err := e.coordinateAutomaticHosted(workerCtx, owned) + var worked bool + if err == nil { + worked, err = e.runNext(workerCtx, owned) + } + worked = worked || generated if err != nil { if workerCtx.Err() != nil { return @@ -443,11 +457,11 @@ func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) ( // 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 + err := tx.QueryRowContext(ctx, `SELECT s.project_id,s.id,`+selectionClaimRevision+` FROM review_selections s WHERE s.state='queued' AND (SELECT count(*) FROM review_operations WHERE state IN ('queued','preparing','posting','active','uncertain')) 1 || cliValue < 0 || cliValue > 1 { + return s, schedulingUnavailable() + } + 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, schedulingUnavailable() + } + return s, nil +} + +// Channel basis revisions are carried in the current scheduling event, not in +// the authorization revision. Legacy events retain the shared revision verbatim: +// deploying this change must not regenerate cancelled or failed intent digests. +func schedulingBasisRevisions(ctx context.Context, tx *sql.Tx, s schedulingRecord) (hosted, cli int64, err error) { + if s.Revision == 0 { + return 0, 0, nil + } + rows, err := tx.QueryContext(ctx, `SELECT actor_id,CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision=? LIMIT 2`, s.ProjectID, s.ProjectID, s.Revision) + if err != nil { + return 0, 0, err + } + defer rows.Close() + count := 0 + for rows.Next() { + count++ + var actor string + var payload sql.NullString + if err = rows.Scan(&actor, &payload); err != nil { + return 0, 0, err + } + var event 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"` + } + if count != 1 || actor != s.actor || !payload.Valid || strictjson.Decode([]byte(payload.String), &event) != nil || event.Hosted == nil || *event.Hosted != s.AutomaticHosted || event.CLI == nil && s.AutomaticCLI || event.CLI != nil && *event.CLI != s.AutomaticCLI { + return 0, 0, schedulingUnavailable() + } + hosted, cli = s.Revision, s.Revision + if len(event.HostedBasis) != 0 || len(event.CLIBasis) != 0 { + if json.Unmarshal(event.HostedBasis, &hosted) != nil || json.Unmarshal(event.CLIBasis, &cli) != nil || string(event.HostedBasis) == "null" || string(event.CLIBasis) == "null" || hosted < 1 || cli < 1 || hosted > s.Revision || cli > s.Revision { + return 0, 0, schedulingUnavailable() + } + } + } + if err = rows.Err(); err != nil { + return 0, 0, err + } + if err = rows.Close(); err != nil { + return 0, 0, err + } + if count != 1 { + return 0, 0, schedulingUnavailable() + } + return hosted, cli, nil +} + +func schedulingAuthorizerAllowed(ctx context.Context, tx *sql.Tx, s schedulingRecord) (bool, error) { + if !s.AutomaticHosted && !s.AutomaticCLI { + return false, nil + } + var allowed bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM credentials c WHERE c.id=? AND c.principal_id=? AND c.revoked=0 AND (c.is_admin=1 OR EXISTS(SELECT 1 FROM grants g WHERE g.credential_id=c.id AND g.project_id=? AND g.can_read=1 AND g.can_write=1 AND g.can_manage=1)) AND EXISTS(SELECT 1 FROM workers w WHERE w.project_id=? AND w.id=? AND NOT EXISTS(SELECT 1 FROM worker_retirements r WHERE r.project_id=w.project_id AND r.worker_id=w.id)))`, s.credential, s.actor, s.ProjectID, s.ProjectID, s.AuthorizingWorkerID).Scan(&allowed) + return allowed, err +} +func (e *Engine) ReadScheduling(ctx context.Context, scope core.Scope) (Scheduling, error) { + var out Scheduling + err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { + s, err := readScheduling(ctx, tx, scope.ProjectID) + if err != nil { + return err + } + out = s.Scheduling + out.PausedPulls = []PullScheduling{} + c, _, configErr := readConfiguration(ctx, tx, scope.ProjectID) + if configErr != nil { + var failure *core.Error + if !errors.As(configErr, &failure) || failure.Code != "reviews_unconfigured" { + return configErr + } + } else { + if validateConfigurationShape(c) != nil { + return schedulingUnavailable() + } + for _, pull := range c.Queue { + p, err := readPullScheduling(ctx, tx, scope.ProjectID, pull) + if err != nil { + return err + } + if p.Paused { + out.PausedPulls = append(out.PausedPulls, p) + } + } + } + if s.AutomaticHosted || s.AutomaticCLI { + var held bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM metadata WHERE (key='restore:provider_state' AND value='held') OR (key='restore:state' AND value='inactive'))`).Scan(&held); err != nil { + return err + } + if held { + out.Reason = "provider_hold" + return nil + } + ok, err := schedulingAuthorizerAllowed(ctx, tx, s) + if err != nil { + return err + } + if !ok { + out.Reason = "authorizer_unavailable" + } + } + return nil + }) + return out, err +} +func validSchedulingRevision(r *int64) bool { return r != nil && *r >= 0 && *r < math.MaxInt64 } +func (e *Engine) ConfigureScheduling(ctx context.Context, scope core.Scope, key string, input SchedulingRequest) (json.RawMessage, error) { + if !validSchedulingRevision(input.ExpectedRevision) || input.AutomaticHosted == nil { + return nil, invalid() + } + scope = scope.RequireAdministration() + out, err := e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.scheduling", Target: "scheduling", Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { + old, err := readScheduling(ctx, tx, scope.ProjectID) + if err != nil { + return nil, err + } + if old.Revision != *input.ExpectedRevision { + return nil, conflict() + } + automaticCLI := old.AutomaticCLI + if input.AutomaticCLI != nil { + automaticCLI = *input.AutomaticCLI + } + credential := "" + if *input.AutomaticHosted || automaticCLI { + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, scope.WorkerID); err != nil { + return nil, err + } + credential, err = e.store.AuthenticatedCredentialID(ctx, tx, scope) + if err != nil { + return nil, err + } + allowed, err := schedulingAuthorizerAllowed(ctx, tx, schedulingRecord{Scheduling: Scheduling{ProjectID: scope.ProjectID, AutomaticHosted: true, AuthorizingWorkerID: scope.WorkerID}, actor: scope.PrincipalID, credential: credential}) + if err != nil { + return nil, err + } + if !allowed { + return nil, core.Fail("forbidden", "An active bound project manager must authorize automatic review scheduling.", 403) + } + } + hostedBasis, cliBasis, err := schedulingBasisRevisions(ctx, tx, old) + if err != nil { + return nil, err + } + authorizerChanged := old.actor != scope.PrincipalID || old.AuthorizingWorkerID != scope.WorkerID || old.credential != credential + hostedChanged, cliChanged := old.AutomaticHosted != *input.AutomaticHosted, old.AutomaticCLI != automaticCLI + // A write changing only the other channel is not a new intent here. + // Reasserting unchanged settings remains an intentional rearm of the + // supplied channels; omitted CLI retains its basis, just like its bit. + reassert := !hostedChanged && !cliChanged + if authorizerChanged || hostedChanged || reassert { + hostedBasis = old.Revision + 1 + } + if authorizerChanged || cliChanged || reassert && input.AutomaticCLI != nil { + cliBasis = old.Revision + 1 + } + at := stamp() + worker := scope.WorkerID + _, err = tx.ExecContext(ctx, `INSERT INTO review_scheduling(project_id,revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(project_id) DO UPDATE SET revision=excluded.revision,automatic_hosted=excluded.automatic_hosted,automatic_cli=excluded.automatic_cli,actor_id=excluded.actor_id,worker_id=excluded.worker_id,credential_id=excluded.credential_id,updated_at=excluded.updated_at`, scope.ProjectID, old.Revision+1, *input.AutomaticHosted, automaticCLI, scope.PrincipalID, worker, credential, at) + if err != nil { + return nil, err + } + if err = core.AppendEvent(ctx, tx, scope, "review.scheduling_updated", scope.ProjectID, old.Revision+1, map[string]any{"automatic_hosted": *input.AutomaticHosted, "automatic_cli": automaticCLI, "hosted_basis_revision": hostedBasis, "cli_basis_revision": cliBasis}); err != nil { + return nil, err + } + return Receipt{ID: scope.ProjectID, State: "scheduling_configured", Revision: old.Revision + 1}, nil + }) + if err == nil { + e.wakeScheduling() + } + return out, err +} +func readPullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) (s PullScheduling, err error) { + s.ProjectID = project + s.PullNumber = pull + var revision, paused, reason, actor, updated any + err = tx.QueryRowContext(ctx, `SELECT revision,paused,reason,actor_id,updated_at FROM review_pull_scheduling WHERE project_id=? AND pull_number=?`, project, pull).Scan(&revision, &paused, &reason, &actor, &updated) + if errors.Is(err, sql.ErrNoRows) { + return s, nil + } + if err != nil { + return s, err + } + var revisionOK, reasonOK, actorOK, updatedOK bool + s.Revision, revisionOK = revision.(int64) + pausedValue, pausedOK := paused.(int64) + s.Reason, reasonOK = reason.(string) + s.ActorID, actorOK = actor.(string) + s.UpdatedAt, updatedOK = updated.(string) + if !revisionOK || !pausedOK || !reasonOK || !actorOK || !updatedOK || pausedValue < 0 || pausedValue > 1 { + return s, schedulingUnavailable() + } + s.Paused = pausedValue == 1 + if s.Revision < 1 || !identifier.MatchString(s.ActorID) || !roundTime(s.UpdatedAt) || !validSchedulingReason(s.Reason) || !s.Paused && s.Reason != "" { + return s, schedulingUnavailable() + } + return s, nil +} +func validSchedulingReason(s string) bool { + return len(s) <= 256 && utf8.ValidString(s) && strings.IndexFunc(s, unicode.IsControl) < 0 +} +func (e *Engine) ReadPullScheduling(ctx context.Context, scope core.Scope, pull int64) (PullScheduling, error) { + if pull < 1 || pull > 2147483647 { + return PullScheduling{}, invalid() + } + var out PullScheduling + err := e.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { + var err error + out, err = readPullScheduling(ctx, tx, scope.ProjectID, pull) + return err + }) + return out, err +} +func (e *Engine) ConfigurePullScheduling(ctx context.Context, scope core.Scope, key string, pull int64, input PullSchedulingRequest) (json.RawMessage, error) { + if pull < 1 || pull > 2147483647 || !validSchedulingRevision(input.ExpectedRevision) || input.Paused == nil || !validSchedulingReason(input.Reason) { + return nil, invalid() + } + out, err := e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.pull_scheduling", Target: strconv.FormatInt(pull, 10), Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { + old, err := readPullScheduling(ctx, tx, scope.ProjectID, pull) + if err != nil { + return nil, err + } + if old.Revision != *input.ExpectedRevision { + return nil, conflict() + } + reason := input.Reason + if !*input.Paused { + reason = "" + } + _, err = tx.ExecContext(ctx, `INSERT INTO review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(project_id,pull_number) DO UPDATE SET revision=excluded.revision,paused=excluded.paused,reason=excluded.reason,actor_id=excluded.actor_id,updated_at=excluded.updated_at`, scope.ProjectID, pull, old.Revision+1, *input.Paused, reason, scope.PrincipalID, stamp()) + if err != nil { + return nil, err + } + if err = core.AppendEvent(ctx, tx, scope, "review.pull_scheduling_updated", strconv.FormatInt(pull, 10), old.Revision+1, map[string]any{"pull_number": pull, "paused": *input.Paused}); err != nil { + return nil, err + } + return Receipt{ID: strconv.FormatInt(pull, 10), State: "pull_scheduling_updated", Revision: old.Revision + 1}, nil + }) + if err == nil { + e.wakeScheduling() + } + return out, err +} +func (e *Engine) wakeScheduling() { + select { + case e.runWake <- struct{}{}: + default: + } + select { + case e.wake <- struct{}{}: + default: + } +} +func requirePullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) error { + s, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + return err + } + if s.Paused { + return core.Fail("pull_scheduling_paused", "New review admission is paused for this PR; existing issued reviews can still be collected.", 409) + } + return nil +} diff --git a/internal/reviewexec/scheduling_admission0030_test.go b/internal/reviewexec/scheduling_admission0030_test.go new file mode 100644 index 000000000..688c0d6ae --- /dev/null +++ b/internal/reviewexec/scheduling_admission0030_test.go @@ -0,0 +1,126 @@ +package reviewexec + +import ( + "context" + "reflect" + "testing" +) + +func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, change := range []string{"explicit-pause", "automatic-pause", "disable", "disable-reenable", "revoke", "lost-management"} { + t.Run(channel+"/"+change, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + automatic := change != "explicit-pause" + var id string + if automatic { + if channel == "hosted" { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + } else { + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + } + selectionNext(t, f, &refreshTestReader{}) + id = schedulingLatest(t, f).OperationID + } else { + id = f.enqueue(t, attemptProject, "late-explicit-pause", channel, 2, 1).ID + } + before := roundOperation(t, f, id) + attribution := snapshotTable(t, f, "review_automatic_selections") + waits := snapshotTable(t, f, "review_operation_waits") + reason := "automation_authorization_changed" + if change == "explicit-pause" || change == "automatic-pause" { + reason = "pull_scheduling_paused" + } + var preparedAttempt Attempt + driver := &controlledDriver{prepare: func(ctx context.Context, op Operation, _ Configuration, a Attempt) (Preparation, error) { + if _, err := f.e.ExecutionContext(ctx, op.ProjectID, op.ID); err != nil { + t.Fatal("preparation did not begin with valid controls", err) + } + preparedAttempt = a + switch change { + case "explicit-pause", "automatic-pause": + schedulingPause(t, f, 2, 0, true) + case "disable", "disable-reenable": + if channel == "hosted" { + schedulingEnable(t, f, 1, false) + if change == "disable-reenable" { + schedulingEnable(t, f, 2, true) + } + } else { + schedulingCLIEnable(t, f, 1, false) + if change == "disable-reenable" { + schedulingCLIEnable(t, f, 2, true) + } + } + case "revoke": + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) + case "lost-management": + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + } + intent := "" + if channel == "hosted" { + intent = "unposted-preparation-intent" + } + return Preparation{Anchor: attemptAnchor(op.ProjectID, op.PullNumber), Intent: intent}, nil + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal("late control refusal became a worker failure", err) + } + after := roundOperation(t, f, id) + if after.State != "queued" || after.Reason != reason || after.AttemptID != "" || after.ActorID != before.ActorID || after.WorkerID != before.WorkerID || after.HeadSHA != before.HeadSHA || after.ConfigurationRevision != before.ConfigurationRevision || after.Channel != before.Channel || driver.prepares.Load() != 1 || driver.calls.Load() != 0 { + t.Fatal("late refusal lost the request or dispatched", before, after) + } + if attribution != snapshotTable(t, f, "review_automatic_selections") || waits != snapshotTable(t, f, "review_operation_waits") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("late refusal changed attribution/waits, duplicated work or stranded capacity") + } + var state, anchor, intent, external string + if err := f.store.DB().QueryRow(`SELECT state,anchor_json,intent,external_id FROM review_execution_attempts WHERE id=?`, preparedAttempt.ID).Scan(&state, &anchor, &intent, &external); err != nil || state != "held" || anchor != "null" || intent != "" || external != "" { + t.Fatal("unused attempt recorded dispatch intent", state, anchor, intent, external, err) + } + if change == "explicit-pause" || change == "automatic-pause" { + schedulingPause(t, f, 2, 1, false) + driver.prepare = nil + driver.dispatch = func(ctx context.Context, op Operation, _ Attempt, record func(context.Context, string) error) (Result, error) { + external := "" + if op.Channel == "hosted" { + external = "synthetic_resume_trigger" + if err := record(ctx, external); err != nil { + return Result{}, err + } + } + return Result{State: "completed", Reason: "synthetic_capture", ExternalID: external}, nil + } + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil || driver.calls.Load() != 1 || roundOperation(t, f, id).State != "completed" { + t.Fatal("resume did not finish the same queued operation", err) + } + } else if change == "disable-reenable" { + attempt, err := f.e.StartAttempt(t.Context(), attemptProject, id) + if err != nil || attempt.ID != "" { + t.Fatal("re-enabling resurrected interrupted authorization", attempt, err) + } + } + }) + } + } +} + +func TestSchedulingAdmitRefusalLeavesPreparationUntouched(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + op := f.enqueue(t, attemptProject, "direct-late-pause", "cli", 2, 1) + a := f.start(t, attemptProject, op) + schedulingPause(t, f, 2, 0, true) + before := roundTables(t, f) + _, err := f.e.Admit(t.Context(), attemptProject, a.ID, a.Revision, attemptAnchor(attemptProject, 2), "") + attemptCode(t, err, "pull_scheduling_paused") + if !reflect.DeepEqual(before, roundTables(t, f)) { + t.Fatal("refused admission changed preparing state before supervisor settlement") + } + if err := f.e.finishPreparation(a, "held", "pull_scheduling_paused"); err != nil { + t.Fatal(err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("refused preparation retained capacity") + } +} diff --git a/internal/reviewexec/scheduling_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go new file mode 100644 index 000000000..3804a5709 --- /dev/null +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -0,0 +1,72 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" +) + +// A configuration owner change governs new selections. It need not replace an +// already-selected operation whose own lane has never been withdrawn. Require +// complete durable control history instead of inferring continuity from the +// current enabled bit. The caller still validates the original exact credential, +// principal and active worker; both historical attribution and child stay intact. +func retainedAutomaticAuthorization(ctx context.Context, tx *sql.Tx, r Run, revision int64, originalActor string, current schedulingRecord) (bool, error) { + if r.State != "selected" || r.OperationID == "" || revision < 1 || revision >= current.Revision || current.Revision-revision > 10000 { + return false, nil + } + allowed, err := schedulingAuthorizerAllowed(ctx, tx, current) + if err != nil || !allowed { + return false, err + } + var bound bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections s JOIN review_operations o ON o.project_id=s.project_id AND o.id=s.operation_id WHERE s.project_id=? AND s.id=? AND s.state='selected' AND s.operation_id=? AND s.actor_id=? AND s.worker_id=? AND s.channel=? AND o.actor_id=s.actor_id AND o.worker_id=s.worker_id AND o.channel=s.channel)`, r.ProjectID, r.ID, r.OperationID, r.ActorID, r.WorkerID, r.Channel).Scan(&bound) + if err != nil || !bound { + return false, err + } + return automaticChannelContinuous(ctx, tx, r, revision, originalActor, current) +} + +// An unchanged authorizer may finish an unselected intent after an unrelated +// channel change. Every revision must still prove its own channel stayed on. +func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision int64, originalActor string, current schedulingRecord) (bool, error) { + if revision < 1 || revision >= current.Revision || current.Revision-revision > 10000 { + return false, nil + } + rows, err := tx.QueryContext(ctx, `SELECT revision,actor_id,payload_json FROM events WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision BETWEEN ? AND ? ORDER BY revision,sequence LIMIT 10002`, r.ProjectID, r.ProjectID, revision, current.Revision) + if err != nil { + return false, err + } + defer rows.Close() + expected := revision + for rows.Next() { + var recorded int64 + var actor string + var payload []byte + if err = rows.Scan(&recorded, &actor, &payload); err != nil { + return false, err + } + if recorded != expected || recorded == revision && actor != originalActor || recorded == current.Revision && actor != current.actor { + return false, nil + } + var settings struct { + Hosted *bool `json:"automatic_hosted"` + CLI *bool `json:"automatic_cli"` + } + if len(payload) > 4096 || json.Unmarshal(payload, &settings) != nil { + return false, nil + } + enabled := settings.Hosted + if r.Channel == "cli" { + enabled = settings.CLI + } + if enabled == nil || !*enabled { + return false, nil + } + expected++ + } + if err = rows.Err(); err != nil { + return false, err + } + return expected == current.Revision+1, nil +} diff --git a/internal/reviewexec/scheduling_authorization_continuity_test.go b/internal/reviewexec/scheduling_authorization_continuity_test.go new file mode 100644 index 000000000..fc1a9becb --- /dev/null +++ b/internal/reviewexec/scheduling_authorization_continuity_test.go @@ -0,0 +1,277 @@ +package reviewexec + +import ( + "context" + "database/sql" + "github.com/benhook1013/FireController/internal/core" + "testing" + "time" +) + +func continuityFixture(t *testing.T, channel string, selected bool) (*attemptFixture, Run) { + t.Helper() + f := schedulingFixtureWithQueue(t, []int64{2}) + if channel == "hosted" { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + } else { + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + } + if selected { + selectionNext(t, f, &refreshTestReader{}) + } + r := schedulingLatest(t, f) + admissionSQL(t, f, `INSERT INTO workers VALUES(?,'replacement-worker','Replacement manager')`, attemptProject) + continuityConfigure(t, f, 1, true, true) + return f, r +} +func continuityConfigure(t *testing.T, f *attemptFixture, revision int64, hosted, cli bool) { + t.Helper() + scope := selectionScope(t, f, attemptProject, f.admin, "write") + scope.WorkerID = "replacement-worker" + _, err := f.e.ConfigureScheduling(t.Context(), scope, core.NewID("continuity"), SchedulingRequest{ExpectedRevision: &revision, AutomaticHosted: &hosted, AutomaticCLI: &cli}) + if err != nil { + t.Fatal(err) + } +} +func continuityGuard(t *testing.T, f *attemptFixture, r Run) error { + t.Helper() + return f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return f.e.requireAutomaticRun(ctx, tx, r) }) +} +func TestRetainedAutomaticAuthorizationSurvivesUnrelatedLaneToggle(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + t.Run(channel, func(t *testing.T) { + f, r := continuityFixture(t, channel, true) + if channel == "hosted" { + // Pre-CLI scheduling events recorded only the Hosted choice. + admissionSQL(t, f, `UPDATE events SET payload_json='{"automatic_hosted":true}' WHERE event_type='review.scheduling_updated' AND revision=1`) + } + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return ValidateSchedulingSnapshot(ctx, tx) }); err != nil { + t.Fatal(err) + } + attribution := snapshotTable(t, f, "review_automatic_selections") + selections := snapshotTable(t, f, "review_selections") + if err := continuityGuard(t, f, r); err != nil { + t.Fatal("valid continuously enabled intent denied", err) + } + a, err := f.e.StartAttempt(t.Context(), attemptProject, r.OperationID) + if err != nil || a.ID == "" || a.OperationID != r.OperationID { + t.Fatal("original operation did not resume", a, err) + } + if snapshotTable(t, f, "review_automatic_selections") != attribution || snapshotTable(t, f, "review_selections") != selections { + t.Fatal("continuity rewrote ownership or selected a replacement") + } + op := cliWaitRead(t, f, r.OperationID) + if op.ActorID != r.ActorID || op.WorkerID != r.WorkerID || op.Channel != channel { + t.Fatal("original identity changed", op) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 { + t.Fatal("duplicate operation") + } + }) + } +} + +func TestRetainedAutomaticAuthorizationRequiresCompleteAuthorityAndHistory(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, fault := range []string{"lane-disabled", "lane-off-on", "missing-initial", "missing-middle", "missing-current", "duplicate-revision", "original-actor", "current-actor", "malformed-payload", "null-lane", "revoked-original", "lost-manage", "retired-original", "revoked-current", "mismatched-child", "unselected"} { + t.Run(channel+"/"+fault, func(t *testing.T) { + f, r := continuityFixture(t, channel, fault != "unselected") + switch fault { + case "lane-disabled", "lane-off-on": + hosted, cli := true, true + if channel == "hosted" { + hosted = false + } else { + cli = false + } + continuityConfigure(t, f, 2, hosted, cli) + if fault == "lane-off-on" { + continuityConfigure(t, f, 3, true, true) + } + case "missing-initial": + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.scheduling_updated' AND revision=1`) + case "missing-current": + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.scheduling_updated' AND revision=2`) + case "missing-middle": + continuityConfigure(t, f, 2, true, true) + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.scheduling_updated' AND revision=2`) + case "duplicate-revision": + admissionSQL(t, f, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) SELECT project_id,event_type,resource_id,revision,actor_id,payload_json,created_at FROM events WHERE event_type='review.scheduling_updated' AND revision=1`) + case "original-actor": + admissionSQL(t, f, `UPDATE events SET actor_id='forged-actor' WHERE event_type='review.scheduling_updated' AND revision=1`) + case "current-actor": + admissionSQL(t, f, `UPDATE events SET actor_id='forged-actor' WHERE event_type='review.scheduling_updated' AND revision=2`) + case "malformed-payload": + admissionSQL(t, f, `UPDATE events SET payload_json='{}' WHERE event_type='review.scheduling_updated' AND revision=2`) + case "null-lane": + admissionSQL(t, f, `UPDATE events SET payload_json='{"automatic_hosted":null,"automatic_cli":null}' WHERE event_type='review.scheduling_updated' AND revision=2`) + case "revoked-original": + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) + case "lost-manage": + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + case "retired-original": + admissionSQL(t, f, `INSERT INTO worker_retirements VALUES(?,'selection-worker',?,'synthetic-actor')`, attemptProject, stamp()) + case "revoked-current": + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id=(SELECT credential_id FROM review_scheduling WHERE project_id=?)`, attemptProject) + case "mismatched-child": + admissionSQL(t, f, `UPDATE review_operations SET worker_id='replacement-worker' WHERE id=?`, r.OperationID) + } + if fault == "unselected" && (r.State != "queued" || r.OperationID != "") { + t.Fatal("unselected fixture unexpectedly has a child", r) + } + attemptCode(t, continuityGuard(t, f, r), "automation_authorization_changed") + if r.OperationID != "" && fault != "mismatched-child" { + a, err := f.e.StartAttempt(t.Context(), attemptProject, r.OperationID) + if err != nil || a.ID != "" { + t.Fatal("invalid continuity dispatched", a, err) + } + } + }) + } + } +} + +func TestRetainedAutomaticAuthorizationKeepsQuotaWaitIdentity(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + a := f.start(t, attemptProject, Receipt{ID: r.OperationID}) + in := CLIAllowanceObservation{Anchor: attemptAnchor(attemptProject, 2), ObservedAt: stamp(), Remaining: 0, Limit: 3, FullCapacityInMS: 86400000, RollingWindowMS: 86400000, ChangedFiles: 2} + if err := f.e.RecordCLIExhaustion(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + original := cliWaitRead(t, f, r.OperationID) + due := cliWaitDue(t, original) + admissionSQL(t, f, `INSERT INTO workers VALUES(?,'replacement-worker','Replacement manager')`, attemptProject) + continuityConfigure(t, f, 1, true, true) + wait := snapshotTable(t, f, "review_operation_waits") + if err := continuityGuard(t, f, r); err != nil { + t.Fatal(err) + } + if wait != snapshotTable(t, f, "review_operation_waits") { + t.Fatal("continuity changed deadline or baseline") + } + f.e.schedulingNow = func() time.Time { return due.Add(time.Second) } + next, err := f.e.StartAttempt(t.Context(), attemptProject, r.OperationID) + if err != nil || next.ID == "" || next.OperationID != r.OperationID { + t.Fatal("same quota operation did not resume", next, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 { + t.Fatal("quota intent replaced") + } +} + +func TestRetainedAutomaticAuthorizationKeepsHostedCooldownThroughRestart(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + due := priorityCooldown(t, f, Receipt{ID: r.OperationID}, 2, time.Minute) + before := snapshotTable(t, f, "review_operation_waits") + admissionSQL(t, f, `INSERT INTO workers VALUES(?,'replacement-worker','Replacement manager')`, attemptProject) + continuityConfigure(t, f, 1, true, true) + restarted, err := New(f.store, attemptCapabilities) + if err != nil { + t.Fatal(err) + } + f.e = restarted + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + if before != snapshotTable(t, f, "review_operation_waits") { + t.Fatal("ownership update/restart changed retained timer") + } + f.e.schedulingNow = func() time.Time { return due.Add(time.Second) } + next, err := f.e.StartAttempt(t.Context(), attemptProject, r.OperationID) + if err != nil || next.ID == "" || next.OperationID != r.OperationID { + t.Fatal("same Hosted operation did not resume", next, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections`) != 1 { + t.Fatal("Hosted request replaced") + } +} + +func TestRetainedAutomaticAuthorizationDiagnosticIsReadOnly(t *testing.T) { + f, r := continuityFixture(t, "hosted", true) + continuityConfigure(t, f, 2, false, true) + continuityConfigure(t, f, 3, true, true) + before := selectionCounts(t, f) + snapshotTable(t, f, "review_automatic_selections") + w := statusHTTP(t, f, r.OperationID, "", "wait=0") + if w.Code != 200 || w.Header().Get(queuedDiagnosticHeader) != "automation_authorization_changed" { + t.Fatal(w.Code, w.Header(), w.Body.String()) + } + if before != selectionCounts(t, f)+snapshotTable(t, f, "review_automatic_selections") { + t.Fatal("diagnostic changed retained intent") + } +} + +func TestAutomaticSameAuthorizerRevisionContinuity(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, state := range []string{"queued", "selecting", "selected"} { + for _, change := range []string{"unchanged", "unrelated-channel", "same-settings", "off-on", "missing-history"} { + t.Run(channel+"/"+state+"/"+change, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + configure := func(revision int64, hosted, cli bool) { + t.Helper() + if _, err := f.e.ConfigureScheduling(t.Context(), scope, core.NewID("same-authorizer"), SchedulingRequest{ExpectedRevision: &revision, AutomaticHosted: &hosted, AutomaticCLI: &cli}); err != nil { + t.Fatal(err) + } + } + configure(0, true, true) + generate := f.e.generateAutomaticHosted + if channel == "cli" { + generate = f.e.generateAutomaticCLI + } + if worked, err := generate(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}); err != nil || !worked { + t.Fatal(worked, err) + } + if state == "selected" { + selectionNext(t, f, &refreshTestReader{}) + } else if state == "selecting" { + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=2 WHERE project_id=?`, attemptProject) + } + r := schedulingLatest(t, f) + switch change { + case "unrelated-channel": + configure(1, channel == "hosted", channel == "cli") + case "same-settings", "missing-history": + configure(1, true, true) + if change == "missing-history" { + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.scheduling_updated' AND revision=1`) + } + case "off-on": + configure(1, channel != "hosted", channel != "cli") + attemptCode(t, continuityGuard(t, f, r), "automation_authorization_changed") + configure(2, true, true) + } + before := selectionCounts(t, f) + snapshotTable(t, f, "review_automatic_selections") + err := continuityGuard(t, f, r) + denied := change == "off-on" || change == "missing-history" + if denied { + attemptCode(t, err, "automation_authorization_changed") + } else if err != nil { + t.Fatal("continuous same-authorizer run refused", err) + } + if after := selectionCounts(t, f) + snapshotTable(t, f, "review_automatic_selections"); after != before { + t.Fatal("authorization guard mutated retained intent") + } + if state == "selected" { + a, err := f.e.StartAttempt(t.Context(), attemptProject, r.OperationID) + if err != nil || (a.ID == "") != denied { + t.Fatal("dispatch did not honor continuity", a, err) + } + } + }) + } + } + } +} diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go new file mode 100644 index 000000000..ceb9f57af --- /dev/null +++ b/internal/reviewexec/scheduling_automatic.go @@ -0,0 +1,691 @@ +package reviewexec + +import ( + "bytes" + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "io" + "slices" + "strings" + "time" + + "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 (e *Engine) requireAutomaticRun(ctx context.Context, tx *sql.Tx, r Run) error { + var retainedRevision any + var actor, worker, credential string + err := tx.QueryRowContext(ctx, `SELECT scheduling_revision,actor_id,worker_id,credential_id FROM review_automatic_selections WHERE project_id=? AND selection_id=?`, r.ProjectID, r.ID).Scan(&retainedRevision, &actor, &worker, &credential) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil { + return err + } + // Preserve query failures while classifying malformed retained SQLite values. + revision, validRevision := retainedRevision.(int64) + if !validRevision || revision < 1 { + return schedulingUnavailable() + } + s, err := readScheduling(ctx, tx, r.ProjectID) + if err != nil { + return err + } + if revision > s.Revision || !automaticChannelEnabled(s, r.Channel) || r.ActorID != actor || r.WorkerID != worker || !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() + } + } + _, err = e.store.ProjectAutomationScope(ctx, tx, r.ProjectID, actor, worker, credential) + var failure *core.Error + if errors.As(err, &failure) && failure.Status >= 400 && failure.Status < 500 { + return automaticDenied() + } + return err +} +func (e *Engine) requireAutomaticOperation(ctx context.Context, tx *sql.Tx, o Operation) error { + var selection string + err := tx.QueryRowContext(ctx, `SELECT s.id FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id AND a.project_id=s.project_id WHERE s.project_id=? AND s.operation_id=?`, o.ProjectID, o.ID).Scan(&selection) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil { + return err + } + r, err := readRun(ctx, tx, o.ProjectID, selection) + if err != nil { + return err + } + if r.OperationID != o.ID || r.ActorID != o.ActorID || r.WorkerID != o.WorkerID || r.Channel != o.Channel { + return schedulingUnavailable() + } + return e.requireAutomaticRun(ctx, tx, r) +} + +const automaticCurrentRunsBasisQuery = `SELECT v.id,v.channel,v.head_sha,v.complete,v.finalized,v.found,v.accepted,v.routed,v.fixed FROM review_current_runs c JOIN review_run_memberships m ON m.project_id=c.project_id AND m.id=c.id AND m.start_revision=c.start_revision JOIN review_run_versions v ON v.project_id=m.project_id AND v.id=m.id AND v.version_revision=m.version_revision WHERE c.project_id=? AND c.pull_number=? AND v.channel='hosted' AND v.outcome='completed' ORDER BY v.id LIMIT 10001` +const automaticCurrentFindingsBasisQuery = `SELECT f.run_id,f.source_finding_id,f.disposition,f.fix_sha,f.proof_note,f.route_json FROM review_current_runs c JOIN review_run_memberships m ON m.project_id=c.project_id AND m.id=c.id AND m.start_revision=c.start_revision JOIN review_finding_versions f ON f.project_id=m.project_id AND f.run_id=m.id AND f.run_version_revision=m.version_revision WHERE c.project_id=? AND c.pull_number=? ORDER BY f.run_id,f.position LIMIT 10001` + +// Query text remains part of the retained intent digest. Pin only physical join +// order for current-reference reads; never replace the digest input with hints. +func automaticBasisQuery(query string, pinJoins bool) string { + if pinJoins { + return strings.ReplaceAll(query, " JOIN ", " CROSS JOIN ") + } + return query +} + +// The semantic digest excludes projection revisions, observation timestamps, +// attempt states and selection/operation transitions. Failed/cancelled requests +// therefore cannot create their own next automatic request. Only original source +// facts and deliberate controls, completed results and finding work change it. +func automaticPullBasis(ctx context.Context, tx *sql.Tx, project string, pull int64) (string, error) { + return automaticPullBasisChannel(ctx, tx, project, pull, "hosted") +} + +type automaticBasisRead struct { + prefix []byte + revision int64 + workspace bool + frame frontFrame + hasFrame bool +} + +// 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 + s, err := readScheduling(ctx, tx, project) + if err != nil { + return out, err + } + hosted, cli, err := schedulingBasisRevisions(ctx, tx, s) + if err != nil { + return out, err + } + out.revision = hosted + if channel == "cli" { + out.revision = cli + } + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE name='review_current_pulls' AND type='table')`).Scan(&out.workspace); err != nil { + return out, err + } + out.frame, out.hasFrame, err = readFrontFrame(ctx, tx, project, channel) + if err != nil { + return out, err + } + var prefix bytes.Buffer + appendRows := automaticBasisAppender(ctx, tx, &prefix, channel, out.revision) + for _, query := range []string{ + `SELECT revision,automatic_hosted FROM review_scheduling WHERE project_id=?`, + `SELECT revision FROM review_execution_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, + `SELECT revision FROM review_policy_config WHERE project_id=? ORDER BY revision DESC LIMIT 1`, + } { + if err := appendRows(query, false, project); err != nil { + return out, err + } + } + out.prefix = prefix.Bytes() + return out, nil +} + +func automaticPullBasisChannel(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string) (string, error) { + shared, err := readAutomaticBasis(ctx, tx, project, channel) + if err != nil { + return "", err + } + return automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) +} + +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}) + rows, err := tx.QueryContext(ctx, automaticBasisQuery(query, pinJoins), args...) + if err != nil { + return err + } + defer rows.Close() + cols, err := rows.Columns() + if err != nil { + return err + } + count := 0 + for rows.Next() { + count++ + if count > 10000 { + return automaticProjectStateFailure("overloaded", "Automatic scheduling needs a narrower retained review scope.", 503) + } + values := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range values { + ptrs[i] = &values[i] + } + if err = rows.Scan(ptrs...); err != nil { + return err + } + for i, v := range values { + if b, ok := v.([]byte); ok { + values[i] = string(b) + } + } + // Keep the original query label and JSON framing. Only the + // channel's semantic revision differs after a relevant write. + if query == `SELECT revision,automatic_`+channel+` FROM review_scheduling WHERE project_id=?` { + values[0] = basisRevision + } + b, err := json.Marshal(values) + if err != nil { + return err + } + h.Write(b) + h.Write([]byte{'\n'}) + } + if err = rows.Err(); err != nil { + return err + } + return rows.Close() + } +} + +func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, shared automaticBasisRead) (string, error) { + basisRevision := shared.revision + h := sha256.New() + h.Write(shared.prefix) + appendRows := automaticBasisAppender(ctx, tx, h, channel, basisRevision) + queries := []struct { + sql string + args []any + }{ + {`SELECT revision,paused,reason FROM review_pull_scheduling WHERE project_id=? AND pull_number=?`, []any{project, pull}}, + {`SELECT epoch,grant_revision,closed,minimum,maximum,maximum_unbounded,used,dry,tapered FROM review_round_controls WHERE project_id=? AND pull_number=? AND channel='` + channel + `'`, []any{project, pull}}, + {`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`, []any{project, pull}}, + {`SELECT id,revision,state,disposition,has_fix FROM review_finding_routes WHERE project_id=? AND (source_pull_number=? OR target_pull_number=?) ORDER BY id LIMIT 10001`, []any{project, pull, pull}}, + {`SELECT o.id,o.revision,o.status FROM review_adoption_targets t JOIN review_adoption_obligations o ON o.id=t.obligation_id AND o.project_id=t.project_id WHERE t.project_id=? AND t.pull_number=? ORDER BY o.id LIMIT 10001`, []any{project, pull}}, + } + for _, q := range queries { + if err := appendRows(q.sql, false, q.args...); err != nil { + return "", err + } + } + if shared.workspace { + if err := appendRows(`SELECT p.state,p.head_sha,p.base_ref,p.base_sha,json_extract(p.metadata_json,'$.is_draft') FROM review_current_pulls c JOIN review_pull_memberships m ON m.project_id=c.project_id AND m.number=c.number AND m.start_revision=c.start_revision JOIN review_pull_versions p ON p.project_id=m.project_id AND p.number=m.number AND p.version_revision=m.version_revision WHERE c.project_id=? AND c.number=?`, false, project, pull); err != nil { + return "", err + } + if err := appendRows(strings.ReplaceAll(automaticCurrentRunsBasisQuery, "'hosted'", "'"+channel+"'"), true, project, pull); err != nil { + return "", err + } + if err := appendRows(automaticCurrentFindingsBasisQuery, true, project, pull); err != nil { + return "", err + } + } + dependencies, err := automaticDependenciesWithFrame(ctx, tx, project, pull, channel, shared.frame, shared.hasFrame) + if err != nil { + return "", err + } + h.Write([]byte(encoded(dependencies))) + + return hex.EncodeToString(h.Sum(nil)), nil +} + +// Only a source-owned retained parent chain supplies dependency identity. +// These local facts can make a distinct intent eligible; they never substitute +// for the selection worker's fresh source or final predecessor guard. +func automaticDependencies(ctx context.Context, tx *sql.Tx, project string, pull int64) ([]any, error) { + return automaticDependenciesChannel(ctx, tx, project, pull, "hosted") +} + +func automaticDependenciesChannel(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string) ([]any, error) { + frame, found, err := readFrontFrame(ctx, tx, project, channel) + if err != nil { + return nil, err + } + return automaticDependenciesWithFrame(ctx, tx, project, pull, channel, frame, found) +} + +func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, frame frontFrame, found bool) ([]any, error) { + out := []any{} + if !found { + return out, nil + } + byNumber := make(map[int64]frontPull, len(frame.prefix)) + for _, p := range frame.prefix { + byNumber[p.Number] = p + } + current, found := byNumber[pull] + if !found { + return out, nil + } + seen := map[int64]bool{pull: true} + for parent := current.ParentPullNumber; parent != 0; { + if seen[parent] || len(seen) > 100 { + return nil, errors.Join(errAutomaticParentCycle, schedulingUnavailable()) + } + seen[parent] = true + p, exists := byNumber[parent] + if !exists { + out = append(out, []any{parent, "source_prefix_incomplete"}) + break + } + progress, err := channelProgress(ctx, tx, project, frame.repository, parent, channel) + if err != nil { + return nil, err + } + control, err := readRoundRecord(ctx, tx, project, parent, channel) + if err != nil { + return nil, err + } + obligations, err := sourceObligationCount(ctx, tx, project, parent) + if err != nil { + return nil, err + } + routes, err := pendingIncomingRoutes(ctx, tx, project, parent) + if err != nil { + return nil, err + } + var completed int64 + if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM review_comparison_proofs WHERE project_id=? AND pull_number=? AND channel='`+channel+`' AND state='ready'`, project, parent).Scan(&completed); err != nil { + return nil, err + } + out = append(out, []any{parent, p.HeadSHA, p.ParentPullNumber, p.ParentSHA, progress, control.Configured, control.Epoch, control.grantRevision, control.Closed, control.Used, control.Dry, control.Tapered, completed, obligations, routes}) + parent = p.ParentPullNumber + } + return out, nil +} + +// Planning can move on to a distinct unattempted PR without treating an +// operation's state transition as a reason to recreate that operation. A +// selected PR is suppressed by its own semantic basis, independently of peers. +func automaticPlanningBasis(ctx context.Context, tx *sql.Tx, project string, c Configuration, ignoreSelection string) (string, bool, error) { + return automaticPlanningBasisChannel(ctx, tx, project, c, ignoreSelection, "hosted") +} + +func automaticPlanningBasisChannel(ctx context.Context, tx *sql.Tx, project string, c Configuration, ignoreSelection string, channel string) (string, bool, error) { + limit, err := automaticHostedQueuedPrefixChannel(ctx, tx, project, c, channel) + if err != nil { + return "", false, err + } + var shared automaticBasisRead + if len(c.Queue) > 0 { + shared, err = readAutomaticBasis(ctx, tx, project, channel) + if err != nil { + return "", false, err + } + } + values := make([]any, 0, len(c.Queue)) + remaining := []int64{} + for position, pull := range c.Queue { + basis, err := automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) + if err != nil { + return "", false, err + } + values = append(values, []any{pull, basis}) + if position >= limit { + continue + } + p, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + return "", false, err + } + if p.Paused { + continue + } + pending, err := automaticHostedPendingPullChannel(ctx, tx, project, pull, channel) + if err != nil { + return "", false, err + } + if pending { + continue + } + var seen bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id<>? AND pull_number=? AND pull_basis_sha256=?)`, project, ignoreSelection, pull, basis).Scan(&seen); err != nil { + return "", false, err + } + if !seen { + remaining = append(remaining, pull) + } + } + sum := sha256.Sum256([]byte(encoded([]any{values, remaining}))) + return hex.EncodeToString(sum[:]), len(remaining) > 0, nil +} + +// A waiting request keeps its identity and deadline. Automatic selection may +// reconsider only earlier PRs, rather than duplicate that request or prefetch +// farther successors merely because the request is not executing yet. +func automaticHostedQueuedPrefix(ctx context.Context, tx *sql.Tx, project string, c Configuration) (int, error) { + return automaticHostedQueuedPrefixChannel(ctx, tx, project, c, "hosted") +} + +func automaticHostedQueuedPrefixChannel(ctx context.Context, tx *sql.Tx, project string, c Configuration, channel string) (int, error) { + queue, err := json.Marshal(c.Queue) + if err != nil { + return 0, err + } + var limit int + err = tx.QueryRowContext(ctx, `SELECT COALESCE(MIN(q.key),?) FROM review_operations o JOIN json_each(?) q ON q.value=o.pull_number WHERE o.project_id=? AND o.channel='`+channel+`' AND o.state='queued' +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)`, len(c.Queue), string(queue), project).Scan(&limit) + return limit, err +} + +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) { + var automatic bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=? AND project_id=?)`, r.ID, r.ProjectID).Scan(&automatic); err != nil { + return false, err + } + if !automatic { + return false, nil + } + 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 := automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + if err != nil { + return false, err + } + if position := slices.Index(c.Queue, pull); position < 0 || position >= limit { + return true, nil + } + basis, err := automaticPullBasisChannel(ctx, tx, r.ProjectID, pull, r.Channel) + if err != nil { + return false, err + } + var seen bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id<>? AND pull_number=? AND pull_basis_sha256=?)`, r.ProjectID, r.ID, pull, basis).Scan(&seen) + return seen, err +} +func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64) error { + var automatic bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=? AND project_id=?)`, r.ID, r.ProjectID).Scan(&automatic); err != nil { + return err + } + if !automatic { + return nil + } + c, _, err := readConfiguration(ctx, tx, r.ProjectID) + if err != nil { + return err + } + basis, _, err := automaticPlanningBasisChannel(ctx, tx, r.ProjectID, c, r.ID, r.Channel) + if err != nil { + return err + } + pullBasis := "" + if pull > 0 { + pullBasis, err = automaticPullBasisChannel(ctx, tx, r.ProjectID, pull, r.Channel) + if err != nil { + return err + } + } + _, err = tx.ExecContext(ctx, `UPDATE review_automatic_selections SET settled_basis_sha256=?,pull_number=?,pull_basis_sha256=? WHERE selection_id=? AND project_id=?`, basis, pull, pullBasis, r.ID, r.ProjectID) + return err +} + +// One bounded local coordinator pass. Existing selection workers own every +// provider read and fresh source/admission check; this method creates no attempt. +func (e *Engine) generateAutomaticHosted(ctx context.Context, readers map[string]TargetReader) (bool, error) { + var projects []string + if err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, `SELECT project_id FROM review_scheduling WHERE automatic_hosted=1 ORDER BY (project_id<=?),project_id LIMIT 100`, e.automaticCursor) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var p string + if err = rows.Scan(&p); err != nil { + return err + } + projects = append(projects, p) + } + return rows.Err() + }); err != nil { + return false, err + } + for _, project := range projects { + e.automaticCursor = project + worked, err := e.generateAutomaticProject(ctx, project, "hosted", readers) + if automaticProjectRefused(err) { + continue + } + if err != nil { + return false, err + } + if worked { + return true, nil + } + } + return false, nil +} + +func (e *Engine) coordinateAutomaticHosted(ctx context.Context, readers map[string]TargetReader) (bool, error) { + e.automaticMu.Lock() + defer e.automaticMu.Unlock() + if ctx.Err() != nil { + return false, ctx.Err() + } + now := time.Now() + if now.Before(e.automaticNext) { + return false, nil + } + e.automaticNext = now.Add(5 * time.Second) + worked, hostedErr := e.generateAutomaticHosted(ctx, readers) + if ctx.Err() != nil { + return worked, ctx.Err() + } + cliWorked, cliErr := e.generateAutomaticCLI(ctx, readers) + if ctx.Err() != nil { + return worked || cliWorked, ctx.Err() + } + // A transient admission/deadline refusal in one channel must not suppress + // the other channel or hide its fatal storage error. + transient := func(err error) error { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "overloaded" { + return nil + } + return err + } + return worked || cliWorked, errors.Join(transient(hostedErr), transient(cliErr)) +} + +func automaticChannelEnabled(s schedulingRecord, channel string) bool { + return channel == "hosted" && s.AutomaticHosted || channel == "cli" && s.AutomaticCLI +} + +// The read preflight can only nominate work. Repeat the entire plan under the +// serialized writer and compare its identity before using ordinary acceptance +// or retry CAS. Idle and permanently suppressed projects never take the writer. +type automaticProjectPlan struct { + scheduling schedulingRecord + scope core.Scope + basis string + retry *Run +} + +func (e *Engine) planAutomaticProject(ctx context.Context, tx *sql.Tx, project, channel string, readers map[string]TargetReader) (*automaticProjectPlan, error) { + var restored 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(&restored); err != nil { + return nil, err + } + if restored { + return nil, nil + } + s, err := readScheduling(ctx, tx, project) + if err != nil || !automaticChannelEnabled(s, channel) { + return nil, err + } + scope, err := e.store.ProjectAutomationScope(ctx, tx, project, s.actor, s.AuthorizingWorkerID, s.credential) + if err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Status >= 400 && failure.Status < 500 { + return nil, nil + } + return nil, err + } + c, _, err := readConfiguration(ctx, tx, project) + if err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "reviews_unconfigured" { + return nil, nil + } + return nil, err + } + if c.Paused || !slices.Contains(c.Channels, channel) || e.validateConfiguration(c) != nil || readers[c.CapabilityID] == nil || len(c.Queue) == 0 { + return nil, nil + } + unpaused := false + for _, pull := range c.Queue { + p, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + return nil, err + } + unpaused = unpaused || !p.Paused + } + if !unpaused { + return nil, nil + } + policy, err := readPolicy(ctx, tx, project) + if err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "reviews_policy_unconfigured" { + return nil, nil + } + return nil, err + } + if policy.Revision < 1 || slices.Contains(policy.Policy.PausedChannels, channel) { + return nil, nil + } + var busy bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections WHERE project_id=? AND channel=? AND state IN('queued','selecting')) OR EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND channel=? AND state IN('preparing','posting','active','uncertain'))`, project, channel, project, channel).Scan(&busy); err != nil { + return nil, err + } + if busy { + return nil, nil + } + basis, candidates, err := automaticPlanningBasisChannel(ctx, tx, project, c, "", channel) + if err != nil || !candidates { + return nil, err + } + var seen bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND (basis_sha256=? OR settled_basis_sha256=?))`, project, basis, basis).Scan(&seen); err != nil { + return nil, err + } + plan := &automaticProjectPlan{scheduling: s, scope: scope, basis: basis} + if seen { + plan.retry, err = e.automaticSourceRetryCandidate(ctx, tx, project, basis, s.Revision, time.Now(), channel) + if err != nil || plan.retry == nil { + return nil, err + } + } + return plan, nil +} + +func (e *Engine) generateAutomaticProject(ctx context.Context, project, channel string, readers map[string]TargetReader) (bool, error) { + var candidate *automaticProjectPlan + err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + var err error + candidate, err = e.planAutomaticProject(ctx, tx, project, channel, readers) + return err + }) + if ctx.Err() != nil { + return false, ctx.Err() + } + if err != nil || candidate == nil { + return false, err + } + return e.acceptAutomaticProject(ctx, project, channel, readers, candidate) +} + +func (e *Engine) acceptAutomaticProject(ctx context.Context, project, channel string, readers map[string]TargetReader, candidate *automaticProjectPlan) (bool, error) { + worked := false + err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + current, err := e.planAutomaticProject(ctx, tx, project, channel, readers) + if err != nil || current == nil { + return err + } + if current.basis != candidate.basis || current.scheduling.Revision != candidate.scheduling.Revision || (current.retry == nil) != (candidate.retry == nil) { + return nil + } + if current.retry != nil { + if current.retry.ID != candidate.retry.ID || current.retry.Revision != candidate.retry.Revision { + return nil + } + err = updateRunAt(ctx, tx, *current.retry, "queued", "", "", time.Now()) + } else { + // Same ordinary acceptance path, fully reauthorized in this snapshot. + receipt, enqueueErr := e.enqueueRunTx(ctx, tx, current.scope, RunRequest{Channel: channel}) + if enqueueErr != nil { + var failure *core.Error + if errors.As(enqueueErr, &failure) && (failure.Status == 409 || failure.Code == "overloaded") { + return nil + } + return enqueueErr + } + s := current.scheduling + _, err = tx.ExecContext(ctx, `INSERT INTO review_automatic_selections(selection_id,project_id,scheduling_revision,basis_sha256,actor_id,worker_id,credential_id) VALUES(?,?,?,?,?,?,?)`, receipt.ID, project, s.Revision, current.basis, s.actor, s.AuthorizingWorkerID, s.credential) + } + worked = err == nil + return err + }) + if ctx.Err() != nil { + return worked && err == nil, ctx.Err() + } + return worked && err == nil, err +} diff --git a/internal/reviewexec/scheduling_cli.go b/internal/reviewexec/scheduling_cli.go new file mode 100644 index 000000000..f4ea6f39a --- /dev/null +++ b/internal/reviewexec/scheduling_cli.go @@ -0,0 +1,41 @@ +package reviewexec + +import ( + "context" + "database/sql" +) + +func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]TargetReader) (bool, error) { + var projects []string + if err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, `SELECT project_id FROM review_scheduling WHERE automatic_cli=1 ORDER BY (SELECT lower(repository) FROM projects WHERE id=project_id)<>?,(project_id<=?),project_id LIMIT 100`, preferredCLIRepository, e.automaticCLICursor) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var p string + if err = rows.Scan(&p); err != nil { + return err + } + projects = append(projects, p) + } + return rows.Err() + }); err != nil { + return false, err + } + for _, project := range projects { + e.automaticCLICursor = project + worked, err := e.generateAutomaticProject(ctx, project, "cli", readers) + if automaticProjectRefused(err) { + continue + } + if err != nil { + return false, err + } + if worked { + return true, nil + } + } + return false, nil +} diff --git a/internal/reviewexec/scheduling_cli_priority.go b/internal/reviewexec/scheduling_cli_priority.go new file mode 100644 index 000000000..8650de0fc --- /dev/null +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -0,0 +1,164 @@ +package reviewexec + +import ( + "context" + "database/sql" + "strings" + "time" +) + +const preferredCLIRepository = "benhook1013/firemud" + +type pendingCandidateID struct{ project, operation string } + +// Prefer the exact configured repository identity, never a mutable project name. +// No running review is preempted and no wait deadline or operation is replaced. +func (e *Engine) preferredCLIQueued(ctx context.Context, tx *sql.Tx, o Operation, c Configuration) (bool, error) { + if o.Channel != "cli" || o.State != "queued" { + return false, nil + } + capability, installed := e.capabilities[c.CapabilityID] + if !installed || capability.Fingerprint != o.CapabilityFingerprint { + return false, nil + } + var repository string + if err := tx.QueryRowContext(ctx, `SELECT repository FROM projects WHERE id=?`, o.ProjectID).Scan(&repository); err != nil { + return false, err + } + if strings.EqualFold(repository, preferredCLIRepository) { + return false, nil + } + rows, err := tx.QueryContext(ctx, `SELECT o.project_id,o.id FROM review_operations o JOIN projects p ON p.id=o.project_id WHERE o.channel='cli' AND o.state='queued' AND o.reason<>'cli_draft_wait' AND lower(p.repository)=? AND o.project_id<>? ORDER BY o.created_at,o.id LIMIT 101`, preferredCLIRepository, o.ProjectID) + if err != nil { + return false, err + } + var ids []pendingCandidateID + for rows.Next() { + var id pendingCandidateID + if err = rows.Scan(&id.project, &id.operation); err != nil { + break + } + ids = append(ids, id) + } + if err == nil { + err = rows.Err() + } + closeErr := rows.Close() + if err != nil { + return false, err + } + if closeErr != nil { + return false, closeErr + } +candidates: + for _, id := range ids { + earlier, err := readOperation(ctx, tx, id.project, id.operation) + if err != nil { + if isRetainedOperationDecodeError(err) || automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { + continue candidates + } + return false, err + } + if earlier.Wait != nil && earlier.Wait.Paused { + continue + } + priorConfig, _, err := readConfiguration(ctx, tx, id.project) + if err != nil { + if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { + continue candidates + } + return false, err + } + priorCapability, ok := e.capabilities[priorConfig.CapabilityID] + if !ok || priorCapability.Fingerprint != earlier.CapabilityFingerprint || priorCapability.Provider != capability.Provider || priorCapability.Account != capability.Account { + continue + } + var waiting bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_operation_waits WHERE operation_id=? AND (paused=1 OR (retry_not_before<>'' AND julianday(retry_not_before)>julianday(?))))`, earlier.ID, e.sampleExecutionTime().UTC().Format(time.RFC3339Nano)).Scan(&waiting); err != nil { + return false, err + } + if waiting { + continue + } + valid, err := e.hostedPriorityBinding(ctx, tx, earlier) + if err != nil { + if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { + continue candidates + } + return false, err + } + if valid { + return true, nil + } + } + return e.preferredCLISelection(ctx, tx, o, capability) +} + +// A concurrently selected preferred project gets to finish its bounded source +// check before a competing account claim. Held/finished selections do not block. +// Match ordinary selection capacity: pending operations must be allowed to +// drain when the preferred selection cannot create its child operation. +func (e *Engine) preferredCLISelection(ctx context.Context, tx *sql.Tx, o Operation, capability Capability) (bool, error) { + rows, err := tx.QueryContext(ctx, `SELECT s.project_id,s.id FROM review_selections s JOIN projects p ON p.id=s.project_id WHERE s.channel='cli' AND s.state IN('queued','selecting') AND lower(p.repository)=? AND s.project_id<>? + AND (SELECT count(*) FROM review_operations WHERE state IN ('queued','preparing','posting','active','uncertain')) 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 == "GET" { + 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_quarantine0030_test.go b/internal/reviewexec/scheduling_quarantine0030_test.go new file mode 100644 index 000000000..7f00ce1f5 --- /dev/null +++ b/internal/reviewexec/scheduling_quarantine0030_test.go @@ -0,0 +1,120 @@ +package reviewexec + +import ( + "math" + "testing" +) + +// The choose/finish refusal paths pass the incremented in-memory run rather +// than the normalized SQL claim. Exercise that exact MaxInt64 boundary. +func TestRecovery0030QuarantinesInMemoryMaximumRevision(t *testing.T) { + for _, automatic := range []bool{false, true} { + t.Run(map[bool]string{false: "explicit", true: "automatic"}[automatic], func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + var r Run + if automatic { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r = schedulingLatest(t, f) + } else { + receipt, _ := selectionEnqueue(t, f, "max-claim", "hosted", nil) + r = selectionRead(t, f, receipt.ID) + } + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=? WHERE id=?`, int64(math.MaxInt64), r.ID) + r.State, r.Revision = "selecting", math.MaxInt64 + history := snapshotTable(t, f, "events") + attribution := snapshotTable(t, f, "review_automatic_selections") + waiter := &operationWaiter{changed: make(chan struct{}, 1)} + f.e.operationMu.Lock() + if f.e.operationWaiters == nil { + f.e.operationWaiters = map[string]map[*operationWaiter]struct{}{} + } + f.e.operationWaiters[r.ID] = map[*operationWaiter]struct{}{waiter: {}} + f.e.operationMu.Unlock() + worked, err := f.e.holdRunLocalRefusal(t.Context(), r) + if err != nil || !worked { + t.Fatal("in-memory max revision was not quarantined", worked, err) + } + got := selectionRead(t, f, r.ID) + if got.State != "held" || got.Reason != "local_read_unavailable" || got.Revision != math.MaxInt64 || got.OperationID != "" { + t.Fatal("quarantine rewrote retained evidence", got) + } + select { + case <-waiter.changed: + default: + t.Fatal("waiter not notified") + } + if worked, err = f.e.holdRunLocalRefusal(t.Context(), r); err != nil || worked { + t.Fatal("stale claim mutated quarantine", worked, err) + } + if history != snapshotTable(t, f, "events") || attribution != snapshotTable(t, f, "review_automatic_selections") { + t.Fatal("quarantine fabricated history or replaced authority") + } + }) + } +} + +func TestRecovery0030MaximumRevisionQuarantinePreservesFailuresAndCAS(t *testing.T) { + for _, fault := range []string{"stale-revision", "write-failure"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + receipt, _ := selectionEnqueue(t, f, "max-claim-cas", "hosted", nil) + r := selectionRead(t, f, receipt.ID) + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=? WHERE id=?`, int64(math.MaxInt64), r.ID) + r.State, r.Revision = "selecting", math.MaxInt64 + if fault == "stale-revision" { + r.Revision-- + } else { + admissionSQL(t, f, `CREATE TRIGGER reject_quarantine0030 BEFORE UPDATE ON review_selections WHEN NEW.state='held' BEGIN SELECT RAISE(ABORT,'synthetic failure'); END`) + } + before := snapshotTable(t, f, "review_selections") + worked, err := f.e.holdRunLocalRefusal(t.Context(), r) + if worked || (err != nil) != (fault == "write-failure") { + t.Fatal("lost failure or compare-and-swap", worked, err) + } + if before != snapshotTable(t, f, "review_selections") { + t.Fatal("failed quarantine changed row") + } + }) + } +} + +func TestRecovery0030DamagedPendingClaimIsIsolated(t *testing.T) { + for _, state := range []string{"queued", "selecting"} { + for _, fault := range []string{"revision-type", "maximum-revision", "fingerprint-blob"} { + t.Run(state+"/"+fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + receipt, _ := selectionEnqueue(t, f, "damaged-claim", "hosted", nil) + admissionSQL(t, f, `UPDATE review_selections SET state=? WHERE id=?`, state, receipt.ID) + switch fault { + case "revision-type": + admissionSQL(t, f, `UPDATE review_selections SET revision='broken' WHERE id=?`, receipt.ID) + case "maximum-revision": + admissionSQL(t, f, `UPDATE review_selections SET revision=? WHERE id=?`, int64(math.MaxInt64), receipt.ID) + case "fingerprint-blob": + admissionSQL(t, f, `UPDATE review_selections SET capability_fingerprint=CAST(capability_fingerprint AS BLOB) WHERE id=?`, receipt.ID) + } + reader := &refreshTestReader{} + var err error + if state == "selecting" { + err = f.e.RecoverReviewRuns(t.Context()) + } else { + _, err = f.e.runNext(t.Context(), map[string]TargetReader{"test-capability": reader}) + } + if err != nil { + t.Fatal("damaged pending selection stopped recovery", err) + } + var gotState, reason string + if err = f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=?`, receipt.ID).Scan(&gotState, &reason); err != nil { + t.Fatal(err) + } + if gotState != "held" || reason != "local_read_unavailable" || reader.calls.Load() != 0 { + t.Fatal("damaged selection was not isolated before source I/O", gotState, reason) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("damaged selection created child") + } + }) + } + } +} diff --git a/internal/reviewexec/scheduling_recovery0030_test.go b/internal/reviewexec/scheduling_recovery0030_test.go new file mode 100644 index 000000000..c6d2c04d4 --- /dev/null +++ b/internal/reviewexec/scheduling_recovery0030_test.go @@ -0,0 +1,157 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func recovery0030Claim(t *testing.T, f *attemptFixture, id string) { + t.Helper() + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + r, err := readRun(ctx, tx, attemptProject, id) + if err != nil { + return err + } + return updateRun(ctx, tx, r, "selecting", "", "") + }); err != nil { + t.Fatal(err) + } +} + +func recovery0030EnableBoth(t *testing.T, f *attemptFixture) { + t.Helper() + revision, on := int64(1), true + _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), core.NewID("recovery"), SchedulingRequest{ExpectedRevision: &revision, AutomaticHosted: &on, AutomaticCLI: &on}) + if err != nil { + t.Fatal(err) + } +} + +func TestRecovery0030InterruptedInitialReadKeepsChannelContinuity(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, duringRead := range []bool{false, true} { + for _, interruptions := range []int{1, 2, 4} { + t.Run(channel+"/"+map[bool]string{false: "before-claim", true: "during-read"}[duringRead]+"/"+string(rune('0'+interruptions)), func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + if channel == "hosted" { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + } else { + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + } + original := schedulingLatest(t, f) + for range interruptions { + recovery0030Claim(t, f, original.ID) + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + } + reader := &refreshTestReader{} + if duringRead { + reader.repository = func(context.Context, int64) (reviewprovider.Repository, error) { + recovery0030EnableBoth(t, f) + return reviewprovider.Repository{ID: 801, FullName: "owner/repo", DefaultBranch: "main"}, nil + } + } else { + recovery0030EnableBoth(t, f) + } + selectionNext(t, f, reader) + got := selectionRead(t, f, original.ID) + if got.State != "selected" || got.OperationID == "" || got.ActorID != original.ActorID || got.WorkerID != original.WorkerID || got.Revision != int64(3+2*interruptions) { + t.Fatal("interrupted initial intent lost continuity", got) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 { + t.Fatal("original intent duplicated") + } + }) + } + } + } +} + +func TestRecovery0030CompletedSourceHoldRetainsExactRevisionFence(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, interrupted := range []bool{false, true} { + t.Run(channel+"/"+map[bool]string{false: "queued", true: "interrupted"}[interrupted], func(t *testing.T) { + var f *attemptFixture + var original Run + if channel == "hosted" { + f, original = sourceRetryFixture(t) + } else { + f, original = cliSourceRetryFixture(t) + } + ageSourceRetry(t, f, original.ID) + if channel == "hosted" { + schedulingGenerate(t, f, true) + } else { + schedulingCLIGenerate(t, f, true) + } + if interrupted { + recovery0030Claim(t, f, original.ID) + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + } + recovery0030EnableBoth(t, f) + reader := &refreshTestReader{} + selectionNext(t, f, reader) + got := selectionRead(t, f, original.ID) + if got.State != "held" || got.Reason != "automation_authorization_changed" || got.OperationID != "" || reader.calls.Load() != 0 { + t.Fatal("completed hold lost exact revision fence", got) + } + }) + } + } +} + +func TestRecovery0030InitialReadRequiresCompleteTransitionEvidence(t *testing.T) { + for _, fault := range []string{"missing", "malformed", "held", "duplicate", "storage"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + recovery0030Claim(t, f, r.ID) + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + recovery0030Claim(t, f, r.ID) + r = selectionRead(t, f, r.ID) + recovery0030EnableBoth(t, f) + switch fault { + case "missing": + admissionSQL(t, f, `DELETE FROM events WHERE resource_id=? AND event_type='review.selection_updated' AND revision=2`, r.ID) + case "malformed": + admissionSQL(t, f, `UPDATE events SET payload_json='null' WHERE resource_id=? AND event_type='review.selection_updated' AND revision=2`, r.ID) + case "held": + admissionSQL(t, f, `UPDATE events SET payload_json='{"state":"held","reason":"source_fetch_timeout"}' WHERE resource_id=? AND event_type='review.selection_updated' AND revision=2`, r.ID) + case "duplicate": + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return core.AppendEvent(ctx, tx, core.Scope{ProjectID: r.ProjectID, PrincipalID: r.ActorID, WorkerID: r.WorkerID}, "review.selection_updated", r.ID, 2, map[string]any{"state": "selecting", "reason": ""}) + }); err != nil { + t.Fatal(err) + } + case "storage": + admissionSQL(t, f, `ALTER TABLE events RENAME TO unavailable_events`) + } + var reason string + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + reason, err = automaticSourceRecoveryFence(ctx, tx, r) + return err + }) + if fault == "storage" { + if err == nil { + t.Fatal("shared storage failure suppressed") + } + } else if err != nil || reason != "automation_authorization_changed" { + t.Fatal("unproven initial history permitted continuity", reason, err) + } + }) + } +} diff --git a/internal/reviewexec/scheduling_recovery_regression_test.go b/internal/reviewexec/scheduling_recovery_regression_test.go new file mode 100644 index 000000000..7dba32550 --- /dev/null +++ b/internal/reviewexec/scheduling_recovery_regression_test.go @@ -0,0 +1,989 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func cliSourceRetryFixture(t *testing.T) (*attemptFixture, Run) { + t.Helper() + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, context.DeadlineExceeded + }}) + r := schedulingLatest(t, f) + if r.Channel != "cli" || r.State != "held" || r.Revision != 3 || r.OperationID != "" { + t.Fatal(r) + } + return f, r +} + +func TestAutomaticCLISourceRetryKeepsOriginalIntentAndBudget(t *testing.T) { + for _, mode := range []string{"success", "budget"} { + t.Run(mode, func(t *testing.T) { + f, original := cliSourceRetryFixture(t) + schedulingCLIGenerate(t, f, false) + for _, revision := range []int64{6, 9} { + ageSourceRetry(t, f, original.ID) + restarted, err := New(f.store, attemptCapabilities) + if err != nil { + t.Fatal(err) + } + f.e = restarted + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + schedulingCLIGenerate(t, f, true) + r := schedulingLatest(t, f) + if r.ID != original.ID || r.ActorID != original.ActorID || r.WorkerID != original.WorkerID || r.ConfigurationRevision != original.ConfigurationRevision || r.PolicyRevision != original.PolicyRevision { + t.Fatal("recovery replaced intent", r) + } + schedulingCLIGenerate(t, f, false) + reader := &refreshTestReader{} + if mode == "budget" { + reader.repository = func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, context.DeadlineExceeded + } + } + selectionNext(t, f, reader) + r = schedulingLatest(t, f) + if r.Revision != revision { + t.Fatal(r) + } + if mode == "success" { + if r.State != "selected" || r.OperationID == "" { + t.Fatal(r) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 { + t.Fatal("recovery duplicated child") + } + break + } + if r.State != "held" || r.OperationID != "" { + t.Fatal(r) + } + } + ageSourceRetry(t, f, original.ID) + schedulingCLIGenerate(t, f, false) + if attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 { + t.Fatal("recovery manufactured intent or provider work") + } + }) + } +} + +func TestAutomaticCLISourceRetrySafetyFences(t *testing.T) { + for _, mode := range []string{"revoked", "disabled", "pause", "restore", "later-cli", "later-hosted", "rate-limited", "configuration"} { + t.Run(mode, func(t *testing.T) { + f, r := cliSourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + switch mode { + case "revoked": + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) + case "disabled": + schedulingCLIEnable(t, f, 1, false) + case "pause": + schedulingPause(t, f, 2, 0, true) + case "restore": + admissionSQL(t, f, `INSERT INTO metadata VALUES('restore:provider_state','held')`) + case "later-cli", "later-hosted": + channel := "cli" + if mode == "later-hosted" { + channel = "hosted" + } + later, _ := selectionEnqueue(t, f, "later-recovery-fence", channel, nil) + // A later settled intent must still prevent revival of the old one. + admissionSQL(t, f, `UPDATE review_selections SET state='held',reason='selection_changed',revision=revision+1 WHERE id=?`, later.ID) + case "rate-limited": + admissionSQL(t, f, `UPDATE review_selections SET reason='source_rate_limited' WHERE id=?`, r.ID) + case "configuration": + f.configure(t, attemptProject, "other-account", 1, false) + } + if mode == "pause" || mode == "restore" { + schedulingCLIGenerate(t, f, false) + if got := selectionRead(t, f, r.ID); got.State != "held" || got.Revision != r.Revision { + t.Fatal("coordinator safety hold revived selection", got) + } + return + } + // Deliberate control changes can authorize a new semantic intent; inspect only + // whether this exact retained source hold may be recovered under its authority. + var worked bool + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var basis string + if err := tx.QueryRowContext(ctx, `SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, r.ID).Scan(&basis); err != nil { + return err + } + s, err := readScheduling(ctx, tx, r.ProjectID) + if err != nil { + return err + } + worked, err = f.e.retryAutomaticSourceChannelTx(ctx, tx, r.ProjectID, basis, s.Revision, time.Now(), "cli") + return err + }) + if err != nil { + t.Fatal(err) + } + if worked != (mode == "later-hosted") { + t.Fatalf("%s: recovery=%v", mode, worked) + } + }) + } +} + +func TestAutomaticGeneratorsIsolateRetainedParentCycle(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + t.Run(channel, func(t *testing.T) { + f := schedulingFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=json_set(body_json,'$.mode','stacked') WHERE project_id=?`, attemptProject) + now, sha := stamp(), strings.Repeat("a", 40) + prefix := []frontPull{{Number: 2, State: "open", HeadSHA: sha, BaseSHA: sha, BaseRef: "four", ParentPullNumber: 4, ParentSHA: sha, ObservedAt: now}, {Number: 4, State: "open", HeadSHA: sha, BaseSHA: sha, BaseRef: "two", ParentPullNumber: 2, ParentSHA: sha, ObservedAt: now}} + raw, err := json.Marshal(prefix) + if err != nil { + t.Fatal(err) + } + admissionSQL(t, f, `INSERT INTO review_front_frames VALUES(?,?,801,1,?,?,1,'',?)`, attemptProject, channel, now, now, string(raw)) + // Prove the fixture reaches the narrow cycle error, not generic corruption. + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + _, err := automaticDependenciesChannel(ctx, tx, attemptProject, 2, channel) + return err + }) + if !errors.Is(err, errAutomaticParentCycle) { + t.Fatal("invalid cycle fixture", err) + } + for _, project := range []string{attemptProject, otherAttemptProject} { + zero := int64(0) + hosted, cli := channel == "hosted", channel == "cli" + _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, project, f.admin, "write"), core.NewID("enable"), SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &hosted, AutomaticCLI: &cli}) + if err != nil { + t.Fatal(err) + } + } + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}} + generate := f.e.generateAutomaticHosted + if channel == "cli" { + generate = f.e.generateAutomaticCLI + } + worked, err := generate(t.Context(), readers) + if err != nil || !worked { + t.Fatal("project cycle stopped healthy project", worked, err) + } + var project string + if err := f.store.DB().QueryRow(`SELECT project_id FROM review_automatic_selections`).Scan(&project); err != nil || project != otherAttemptProject { + t.Fatal(project, err) + } + // Shared storage failure must still reach the coordinator rather than being hidden. + admissionSQL(t, f, `ALTER TABLE review_front_frames RENAME TO missing_front_frames`) + if _, err := generate(t.Context(), readers); err == nil { + t.Fatal("shared storage failure was swallowed") + } + }) + } +} + +func TestAutomaticCLISourceRetryRechecksFencesAfterSourceIO(t *testing.T) { + for _, mode := range []string{"cancelled-operation", "scheduling", "configuration", "policy"} { + t.Run(mode, func(t *testing.T) { + f, r := cliSourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + schedulingCLIGenerate(t, f, true) + var once sync.Once + reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + once.Do(func() { + switch mode { + case "cancelled-operation": + raw, err := f.e.Enqueue(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "during-source", Request{ExpectedConfigurationRevision: 1, PullNumber: 2, HeadSHA: strings.Repeat("a", 40), Channel: "cli"}) + if err != nil { + t.Fatal(err) + } + var receipt Receipt + if err = json.Unmarshal(raw, &receipt); err != nil { + t.Fatal(err) + } + _, err = f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-during-source", receipt.ID, OperationControl{ExpectedRevision: 1, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + case "scheduling": + schedulingCLIEnable(t, f, 1, true) + case "configuration": + f.configure(t, attemptProject, "test-capability", 1, false) + case "policy": + assessmentPolicy(t, f, 1, []string{"cli"}, []string{}) + } + }) + return reviewprovider.Repository{ID: 801, FullName: "owner/repo", DefaultBranch: "main"}, nil + }} + selectionNext(t, f, reader) + got := selectionRead(t, f, r.ID) + if got.State != "held" || got.OperationID != "" { + t.Fatal("changed authority or cancelled successor ignored", got) + } + expected := 0 + if mode == "cancelled-operation" { + expected = 1 + if got.Reason != "selection_superseded" { + t.Fatal(got) + } + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != expected { + t.Fatal("retry created a child after its fence changed") + } + }) + } +} + +func TestAutomaticCoordinatorIsolatesProjectState(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, fault := range []string{"configuration-type", "configuration-body-type", "policy", "policy-type", "scheduling", "scheduling-type", "pull-scheduling", "pull-scheduling-type", "front", "oversized-front", "oversized-basis", "retry-selection"} { + t.Run(channel+"/"+fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + for _, project := range []string{attemptProject, otherAttemptProject} { + zero, on := int64(0), true + if _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, project, f.admin, "write"), core.NewID("enable"), SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { + t.Fatal(err) + } + } + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}} + generate := f.e.generateAutomaticHosted + if channel == "cli" { + generate = f.e.generateAutomaticCLI + } + switch fault { + case "configuration-type": + admissionSQL(t, f, `UPDATE review_execution_config SET revision='malformed' WHERE project_id=?`, attemptProject) + case "configuration-body-type": + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=CAST(body_json AS BLOB) WHERE project_id=?`, attemptProject) + case "policy", "policy-type": + if fault == "policy" { + admissionSQL(t, f, `UPDATE review_policy_config SET body_json='not-json' WHERE project_id=?`, attemptProject) + } else { + admissionSQL(t, f, `UPDATE review_policy_config SET revision='malformed' WHERE project_id=?`, attemptProject) + } + case "scheduling": + admissionSQL(t, f, `UPDATE review_scheduling SET updated_at='malformed' WHERE project_id=?`, attemptProject) + case "scheduling-type": + admissionSQL(t, f, `UPDATE review_scheduling SET revision='malformed' WHERE project_id=?`, attemptProject) + case "pull-scheduling-type": + admissionSQL(t, f, `INSERT INTO review_pull_scheduling VALUES(?,2,'malformed',0,'','actor',?)`, attemptProject, stamp()) + case "pull-scheduling": + admissionSQL(t, f, `INSERT INTO review_pull_scheduling VALUES(?,2,1,0,'unexpected reason','actor',?)`, attemptProject, stamp()) + case "front", "oversized-front": + body := "not-json" + if fault == "oversized-front" { + body = strings.Repeat(" ", maxFrontPrefixBytes+1) + } + admissionSQL(t, f, `INSERT INTO review_front_frames VALUES(?,?,801,1,?,'',0,'',?)`, attemptProject, channel, stamp(), body) + case "oversized-basis": + // The basis reads only these three columns; a private synthetic table + // keeps this bound test independent of route creation workflows. + admissionSQL(t, f, `ALTER TABLE review_finding_routes RENAME TO saved_finding_routes`) + admissionSQL(t, f, `CREATE TABLE review_finding_routes(project_id TEXT,id TEXT,revision INTEGER,state TEXT,disposition TEXT,has_fix INTEGER,source_pull_number INTEGER,target_pull_number INTEGER)`) + admissionSQL(t, f, `WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10001) INSERT INTO review_finding_routes SELECT ?,printf('route-%d',x),1,'active','accepted',0,2,4 FROM n`, attemptProject) + case "retry-selection": + if worked, err := generate(t.Context(), readers); err != nil || !worked { + t.Fatal(worked, err) + } + selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, context.DeadlineExceeded + }}) + r := schedulingLatest(t, f) + admissionSQL(t, f, `UPDATE review_selections SET updated_at='malformed' WHERE id=?`, r.ID) + // Ensure the bad project is considered before the healthy one again. + f.e.automaticCursor, f.e.automaticCLICursor = "", "" + } + worked, err := generate(t.Context(), readers) + if err != nil || !worked { + t.Fatal("project-local state stopped the healthy project", worked, err) + } + if got := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections a JOIN review_selections s ON s.id=a.selection_id WHERE a.project_id=? AND s.channel=?`, otherAttemptProject, channel); got != 1 { + t.Fatal("healthy project not selected", got) + } + // A corrupt Hosted project must not prevent the independent CLI pass. + if worked, err = f.e.coordinateAutomaticHosted(t.Context(), readers); err != nil || !worked { + t.Fatal("project-local state stopped the other channel", worked, err) + } + otherChannel := "cli" + if channel == "cli" { + otherChannel = "hosted" + } + if got := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections a JOIN review_selections s ON s.id=a.selection_id WHERE s.channel=?`, otherChannel); got < 1 { + t.Fatal("other channel was suppressed", got) + } + }) + } + } +} + +func TestAutomaticCoordinatorPreservesStorageFailuresAndCancellation(t *testing.T) { + for _, fault := range []string{"front-table", "scheduling-table", "write-rollback", "cancelled", "cancelled-throttled"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + switch fault { + case "front-table": + admissionSQL(t, f, `ALTER TABLE review_front_frames RENAME TO missing_front_frames`) + case "scheduling-table": + admissionSQL(t, f, `ALTER TABLE review_scheduling RENAME TO missing_scheduling`) + case "write-rollback": + admissionSQL(t, f, `CREATE TRIGGER fail_automatic_attribution BEFORE INSERT ON review_automatic_selections BEGIN SELECT RAISE(ABORT, 'synthetic attribution failure'); END`) + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if strings.HasPrefix(fault, "cancelled") { + cancel() + if fault == "cancelled-throttled" { + f.e.automaticNext = time.Now().Add(time.Minute) + } + } + before := selectionCounts(t, f) + worked, err := f.e.coordinateAutomaticHosted(ctx, map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err == nil || worked || automaticProjectRefused(err) { + t.Fatal("storage/cancellation error was suppressed", worked, err) + } + if strings.HasPrefix(fault, "cancelled") && !errors.Is(err, context.Canceled) { + t.Fatal("parent cancellation lost", err) + } + if before != selectionCounts(t, f) || attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections`) != 0 { + t.Fatal("failed transaction retained partial intent") + } + }) + } + for _, err := range []error{core.Fail("storage_unavailable", "Shared storage failed", 503), core.Fail("storage_unavailable", "Shared storage failed", 500), core.Fail("overloaded", "Shared writer busy", 503), core.Fail("unrelated", "Unknown refusal", 403), context.Canceled, sql.ErrTxDone} { + if automaticProjectRefused(err) { + t.Fatal("public error code alone was classified project-local", err) + } + } +} + +func TestAutomaticMalformedProjectDoesNotStopExplicitSelectionWorkers(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + schedulingEnable(t, f, 0, true) + admissionSQL(t, f, `UPDATE review_scheduling SET updated_at='malformed' WHERE project_id=?`, attemptProject) + raw, err := f.e.EnqueueRun(t.Context(), selectionScope(t, f, otherAttemptProject, f.admin, "write"), "healthy-explicit", RunRequest{Channel: "cli"}) + if err != nil { + t.Fatal(err) + } + var receipt Receipt + if err = json.Unmarshal(raw, &receipt); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + reader := &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{Number: number, RepositoryID: 802, State: "open", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }} + done, err := f.e.StartReviewRuns(ctx, map[string]TargetReader{"test-capability": reader}) + if err != nil { + t.Fatal(err) + } + defer func() { + cancel() + if err := <-done; err != nil { + t.Error("selection workers failed", err) + } + }() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + var state string + if err := f.store.DB().QueryRow(`SELECT state FROM review_selections WHERE id=?`, receipt.ID).Scan(&state); err != nil { + t.Fatal(err) + } + if state == "selected" { + return + } + if state == "held" || state == "empty" { + t.Fatal("healthy explicit request not selected", state) + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("healthy explicit selection did not finish") +} + +func TestAutomaticSupervisorIsolatesSchedulingRefusals(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, fault := range []string{"automatic", "automatic-revision", "pull", "pending-prefix"} { + t.Run(channel+"/"+fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4}) + f.configure(t, otherAttemptProject, "other-account", 0, false) + var bad string + if fault == "automatic" || fault == "automatic-revision" { + if channel == "hosted" { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + } else { + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + } + selectionNext(t, f, &refreshTestReader{}) + bad = schedulingLatest(t, f).OperationID + if fault == "automatic-revision" { + admissionSQL(t, f, `UPDATE review_automatic_selections SET scheduling_revision='malformed' WHERE project_id=?`, attemptProject) + } else { + admissionSQL(t, f, `UPDATE review_scheduling SET updated_at='malformed' WHERE project_id=?`, attemptProject) + } + } else { + bad = f.enqueue(t, attemptProject, "bad", channel, 2, 1).ID + if fault == "pending-prefix" { + f.enqueue(t, attemptProject, "bad-later", channel, 4, 1) + } + admissionSQL(t, f, `INSERT INTO review_pull_scheduling VALUES(?,2,1,0,'invalid unpaused reason','actor',?)`, attemptProject, stamp()) + } + healthy := f.enqueue(t, otherAttemptProject, "healthy", channel, 2, 1) + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + if o.ID != healthy.ID { + t.Error("wrong candidate reached provider", o.ID) + } + return Preparation{}, sourceHold("synthetic_stop") + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver, "other-account": driver}); err != nil { + t.Fatal("local scheduling refusal stopped supervisor", err) + } + if driver.prepares.Load() != 1 || driver.calls.Load() != 0 { + t.Fatal("healthy candidate not reached", driver.prepares.Load()) + } + if got := cliWaitRead(t, f, bad); got.State != "queued" || got.AttemptID != "" { + t.Fatal("corrupt candidate changed", got) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts WHERE project_id=?`, attemptProject) != 0 { + t.Fatal("corrupt project reserved attempt") + } + }) + } + } +} + +func TestAutomaticSelectionSettlementRefusalIsAtomicAndLocal(t *testing.T) { + for _, fault := range []string{"basis-cap", "front-after-child", "sql-after-child", "hold-write"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=2 WHERE id=?`, r.ID) + r = selectionRead(t, f, r.ID) + var c Configuration + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + c, _, err = readConfiguration(ctx, tx, r.ProjectID) + return err + }); err != nil { + t.Fatal(err) + } + choice, err := f.e.chooseRun(t.Context(), r, 801, c, &refreshTestReader{}) + if err != nil || choice.state != "selected" { + t.Fatal("invalid selected fixture", choice, err) + } + if fault == "basis-cap" { + admissionSQL(t, f, `ALTER TABLE review_finding_routes RENAME TO saved_finding_routes`) + admissionSQL(t, f, `CREATE TABLE review_finding_routes(project_id TEXT,id TEXT,revision INTEGER,state TEXT,disposition TEXT,has_fix INTEGER,source_pull_number INTEGER,target_pull_number INTEGER)`) + admissionSQL(t, f, `WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10001) INSERT INTO review_finding_routes SELECT ?,printf('route-%d',x),1,'active','accepted',0,2,4 FROM n`, attemptProject) + choice = runChoice{state: "held", reason: "source_fetch_timeout", sourceReason: "source_fetch_timeout"} + } else { + if fault == "sql-after-child" { + admissionSQL(t, f, `CREATE TRIGGER fail_basis BEFORE UPDATE ON review_automatic_selections BEGIN SELECT RAISE(ABORT,'synthetic settlement write failure'); END`) + } else { + admissionSQL(t, f, `CREATE TRIGGER corrupt_basis AFTER INSERT ON review_operations BEGIN UPDATE review_front_frames SET prefix_json='not-json' WHERE project_id=NEW.project_id; END`) + if fault == "hold-write" { + admissionSQL(t, f, `CREATE TRIGGER fail_local_hold BEFORE UPDATE ON review_selections WHEN NEW.reason='automatic_scheduling_unavailable' BEGIN SELECT RAISE(ABORT,'synthetic local hold failure'); END`) + } + } + } + attribution := snapshotTable(t, f, "review_automatic_selections") + frames := snapshotTable(t, f, "review_front_frames") + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + _, err = f.e.finishRunChoice(ctx, r, 801, nil, choice) + fatal := fault == "sql-after-child" || fault == "hold-write" + if fatal { + if err == nil || automaticProjectRefused(err) { + t.Fatal("real persistence failure suppressed", err) + } + } else if err != nil { + t.Fatal("local basis refusal escaped or retried", err) + } + got := selectionRead(t, f, r.ID) + if fatal { + if got.State != "selecting" || got.Revision != 2 { + t.Fatal("failed transaction changed selection", got) + } + } else if got.State != "held" || got.Reason != "automatic_scheduling_unavailable" || got.Revision != 3 || got.OperationID != "" { + t.Fatal("local hold not retained", got) + } + if attribution != snapshotTable(t, f, "review_automatic_selections") || frames != snapshotTable(t, f, "review_front_frames") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("settlement failure retained partial child, frame or basis") + } + if fatal { + return + } + if fault == "basis-cap" { + admissionSQL(t, f, `DELETE FROM review_finding_routes`) + } else { + admissionSQL(t, f, `DROP TRIGGER corrupt_basis`) + } + restarted, err := New(f.store, attemptCapabilities) + if err != nil { + t.Fatal(err) + } + f.e = restarted + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + schedulingGenerate(t, f, false) + if got := selectionRead(t, f, r.ID); got.State != "held" || got.Reason != "automatic_scheduling_unavailable" { + t.Fatal("restart reopened refusal", got) + } + // The same worker can still select an independent explicit channel. + healthy, _ := selectionEnqueue(t, f, "healthy-cli", "cli", nil) + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, healthy.ID); got.State != "selected" { + t.Fatal("healthy channel did not progress", got) + } + }) + } +} + +func TestAutomaticSelectionRetryNeverRetriesTypedRefusal(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 250*time.Millisecond) + defer cancel() + calls := 0 + refusal := automaticProjectStateFailure("overloaded", "Retained basis limit", 503) + err := retryRunSelectionLocal(ctx, func() error { calls++; return refusal }) + if err != refusal || calls != 1 { + t.Fatal("deterministic refusal entered transient retry", calls, err) + } +} + +func TestSelectionLocalRefusalKeepsExplicitAttribution(t *testing.T) { + for _, automatic := range []bool{false, true} { + name := "explicit" + if automatic { + name = "automatic" + } + t.Run(name, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + var r Run + if automatic { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r = schedulingLatest(t, f) + } else { + receipt, _ := selectionEnqueue(t, f, "explicit-attribution", "hosted", nil) + r = selectionRead(t, f, receipt.ID) + } + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=2 WHERE id=?`, r.ID) + r = selectionRead(t, f, r.ID) + admissionSQL(t, f, `UPDATE review_execution_config SET body_json='not-json' WHERE project_id=?`, r.ProjectID) + before := snapshotTable(t, f, "review_selections") + frames := snapshotTable(t, f, "review_front_frames") + _, err := f.e.finishRunChoice(t.Context(), r, 801, nil, runChoice{state: "held", reason: "source_fetch_timeout", sourceReason: "source_fetch_timeout"}) + if automatic { + if err != nil { + t.Fatal("automatic refusal escaped", err) + } + var state, reason string + if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=?`, r.ID).Scan(&state, &reason); err != nil || state != "held" || reason != "automatic_scheduling_unavailable" { + t.Fatal("automatic hold missing", state, reason, err) + } + } else if !automaticProjectRefused(err) || before != snapshotTable(t, f, "review_selections") { + t.Fatal("explicit request became an automatic hold instead of preserving its error path", err) + } + if frames != snapshotTable(t, f, "review_front_frames") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("refusal retained source or child writes") + } + }) + } +} + +func TestAutomaticParentReadersIsolateRetainedCorruption(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, fault := range []string{"proof", "round-body", "round-type", "route", "adoption"} { + t.Run(channel+"/"+fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + now, sha := stamp(), strings.Repeat("a", 40) + prefix := []frontPull{{Number: 2, State: "open", HeadSHA: sha, BaseSHA: sha, BaseRef: "four", ParentPullNumber: 4, ParentSHA: sha, ObservedAt: now}, {Number: 4, State: "open", HeadSHA: sha, BaseSHA: sha, BaseRef: "main", ObservedAt: now}} + raw, err := json.Marshal(prefix) + if err != nil { + t.Fatal(err) + } + admissionSQL(t, f, `INSERT INTO review_front_frames VALUES(?,?,801,1,?,?,1,'',?)`, attemptProject, channel, now, now, string(raw)) + switch fault { + case "proof": + // Isolate the bounded proof reader from unrelated evidence construction. + admissionSQL(t, f, `ALTER TABLE review_comparison_proofs RENAME TO saved_comparison_proofs`) + admissionSQL(t, f, `CREATE TABLE review_comparison_proofs(project_id TEXT,pull_number INTEGER,channel TEXT,state TEXT,repository_id INTEGER)`) + admissionSQL(t, f, `INSERT INTO review_comparison_proofs VALUES(?,4,?,'dirty',801)`, attemptProject, channel) + case "round-body", "round-type": + roundGrant(t, f, 4, channel, 0, 1, 2, "parent-grant") + if fault == "round-body" { + admissionSQL(t, f, `UPDATE review_round_changes SET body_json='not-json' WHERE project_id=?`, attemptProject) + } else { + admissionSQL(t, f, `UPDATE review_round_controls SET updated_at=123 WHERE project_id=?`, attemptProject) + } + case "adoption": + integrationImportHold(t, f, 4) + admissionSQL(t, f, `DROP TRIGGER review_adoption_originals_immutable`) + admissionSQL(t, f, `UPDATE review_adoption_obligations SET original_json='not-json' WHERE project_id=?`, attemptProject) + case "route": + admissionSQL(t, f, `INSERT INTO review_route_policy_invalidations VALUES(?,4,'broken-route')`, attemptProject) + } + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + _, err := automaticDependenciesChannel(ctx, tx, attemptProject, 2, channel) + return err + }) + if !automaticProjectRefused(err) { + t.Fatal("retained corruption not classified", err) + } + for _, project := range []string{attemptProject, otherAttemptProject} { + zero := int64(0) + hosted, cli := channel == "hosted", channel == "cli" + if _, err = f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, project, f.admin, "write"), core.NewID("enable"), SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &hosted, AutomaticCLI: &cli}); err != nil { + t.Fatal(err) + } + } + generate := f.e.generateAutomaticHosted + if channel == "cli" { + generate = f.e.generateAutomaticCLI + } + worked, err := generate(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err != nil || !worked { + t.Fatal("corruption stopped healthy project", worked, err) + } + if n := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections WHERE project_id=?`, otherAttemptProject); n != 1 { + t.Fatal("healthy project not selected", n) + } + }) + } + } +} + +func TestAutomaticSharedReadersPreserveSQLFailures(t *testing.T) { + for _, table := range []string{"review_policy_config", "review_comparison_proofs", "review_round_controls", "review_route_policy_invalidations", "review_adoption_obligations"} { + t.Run(table, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + admissionSQL(t, f, `ALTER TABLE `+table+` RENAME TO unavailable_retained_table`) + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + switch table { + case "review_policy_config": + _, err = readPolicy(ctx, tx, attemptProject) + case "review_comparison_proofs": + _, err = channelProgress(ctx, tx, attemptProject, 801, 4, "hosted") + case "review_round_controls": + _, err = readRoundRecord(ctx, tx, attemptProject, 4, "hosted") + case "review_route_policy_invalidations": + _, err = pendingIncomingRoutes(ctx, tx, attemptProject, 4) + case "review_adoption_obligations": + _, err = sourceObligationCount(ctx, tx, attemptProject, 4) + } + return err + }) + if err == nil || automaticProjectRefused(err) { + t.Fatal("SQL failure hidden as project-local refusal", err) + } + }) + } +} + +func TestSelectionWorkerIsolatesRetainedRefusalsAtEveryStage(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, automatic := range []bool{false, true} { + for _, stage := range []string{"claim", "retained-revision", "choose", "finish"} { + if stage == "retained-revision" && !automatic { + continue // This attribution exists only for automatic requests. + } + name := channel + "/explicit/" + stage + if automatic { + name = channel + "/automatic/" + stage + } + t.Run(name, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "other-account", 0, false) + var bad Run + if automatic { + if channel == "hosted" { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + } else { + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + } + bad = schedulingLatest(t, f) + } else { + r, _ := selectionEnqueue(t, f, "bad", channel, nil) + bad = selectionRead(t, f, r.ID) + } + switch stage { + case "retained-revision": + admissionSQL(t, f, `UPDATE review_automatic_selections SET scheduling_revision='malformed' WHERE project_id=?`, attemptProject) + case "claim": + if automatic { + admissionSQL(t, f, `UPDATE review_scheduling SET updated_at='malformed' WHERE project_id=?`, attemptProject) + } else { + admissionSQL(t, f, `UPDATE review_policy_config SET body_json='not-json' WHERE project_id=?`, attemptProject) + } + case "choose": + admissionSQL(t, f, `INSERT INTO review_pull_scheduling VALUES(?,2,1,0,'invalid unpaused reason','actor',?)`, attemptProject, stamp()) + case "finish": + admissionSQL(t, f, `CREATE TRIGGER corrupt_selection_finish AFTER INSERT ON review_front_frames BEGIN INSERT INTO review_pull_scheduling VALUES(NEW.project_id,2,1,0,'invalid unpaused reason','actor',NEW.checked_at); END`) + } + beforeFrames := snapshotTable(t, f, "review_front_frames") + worked, err := f.e.runNext(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err != nil || !worked { + t.Fatal("local failure stopped worker", worked, err) + } + got := selectionRead(t, f, bad.ID) + reason := "local_read_unavailable" + if automatic { + reason = "automatic_scheduling_unavailable" + } + if got.State != "held" || got.Reason != reason || got.OperationID != "" { + t.Fatal("incorrect refusal attribution", got) + } + if beforeFrames != snapshotTable(t, f, "review_front_frames") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("partial source or child retained") + } + if stage == "finish" { + admissionSQL(t, f, `DROP TRIGGER corrupt_selection_finish`) + } + raw, err := f.e.EnqueueRun(t.Context(), selectionScope(t, f, otherAttemptProject, f.admin, "write"), "healthy", RunRequest{Channel: channel}) + if err != nil { + t.Fatal(err) + } + var healthy Receipt + if err = json.Unmarshal(raw, &healthy); err != nil { + t.Fatal(err) + } + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}, "other-account": &refreshTestReader{pull: func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{Number: n, RepositoryID: 802, State: "open", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }}} + if worked, err = f.e.runNext(t.Context(), readers); err != nil || !worked { + t.Fatal("healthy project stopped", worked, err) + } + var state string + if err = f.store.DB().QueryRow(`SELECT state FROM review_selections WHERE id=?`, healthy.ID).Scan(&state); err != nil || state != "selected" { + t.Fatal("healthy project not selected", state, err) + } + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + if got = selectionRead(t, f, bad.ID); got.State != "held" { + t.Fatal("restart reopened poison selection", got) + } + }) + } + } + } +} + +func TestSelectionWorkerLocalHoldPreservesPersistenceFailuresAndRaces(t *testing.T) { + for _, fault := range []string{"hold-write", "concurrent-transition", "canceled"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + receipt, _ := selectionEnqueue(t, f, "local-hold", "cli", nil) + r := selectionRead(t, f, receipt.ID) + switch fault { + case "hold-write": + admissionSQL(t, f, `CREATE TRIGGER fail_local_hold BEFORE UPDATE ON review_selections WHEN NEW.reason='local_read_unavailable' BEGIN SELECT RAISE(ABORT,'synthetic persistence failure'); END`) + case "concurrent-transition": + admissionSQL(t, f, `UPDATE review_selections SET state='held',reason='configuration_changed',revision=revision+1 WHERE id=?`, r.ID) + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if fault == "canceled" { + cancel() + } + before := snapshotTable(t, f, "review_selections") + worked, err := f.e.holdRunLocalRefusal(ctx, r) + if worked { + t.Fatal("failed or stale hold reported progress") + } + if fault == "concurrent-transition" { + if err != nil { + t.Fatal(err) + } + } else if err == nil || automaticProjectRefused(err) { + t.Fatal("real failure hidden", err) + } + if before != snapshotTable(t, f, "review_selections") { + t.Fatal("failed or stale hold changed selection") + } + }) + } +} + +func TestStartupIsolatesDamagedFrontCacheButSnapshotsRejectIt(t *testing.T) { + for _, fault := range []string{"json", "oversized", "timestamp", "type"} { + t.Run(fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + for _, project := range []string{attemptProject, otherAttemptProject} { + zero := int64(0) + on := true + if _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, project, f.admin, "write"), core.NewID("enable"), SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { + t.Fatal(err) + } + } + now := stamp() + admissionSQL(t, f, `INSERT INTO review_front_frames VALUES(?,'hosted',801,1,?,'',0,'','[]')`, attemptProject, now) + switch fault { + case "json": + admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json='not-json'`) + case "oversized": + admissionSQL(t, f, `UPDATE review_front_frames SET prefix_json=?`, strings.Repeat(" ", maxFrontPrefixBytes+1)) + case "timestamp": + admissionSQL(t, f, `UPDATE review_front_frames SET checked_at='not-time'`) + case "type": + admissionSQL(t, f, `UPDATE review_front_frames SET repository_id='bad'`) + } + before := snapshotTable(t, f, "review_front_frames") + if err := EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal("one cache row blocked startup", err) + } + if before != snapshotTable(t, f, "review_front_frames") { + t.Fatal("startup rewrote retained cache") + } + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return ValidateFrontSnapshot(ctx, tx) }) + if err == nil { + t.Fatal("backup validation accepted damaged cache") + } + worked, err := f.e.generateAutomaticHosted(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err != nil || !worked { + t.Fatal("healthy project blocked after restart", worked, err) + } + if n := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections WHERE project_id=?`, otherAttemptProject); n != 1 { + t.Fatal("healthy project not selected", n) + } + }) + } +} + +func TestStartupStillRejectsSharedFrontSchemaDamage(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + admissionSQL(t, f, `CREATE INDEX unexpected_front_index ON review_front_frames(repository_id)`) + if err := EnsureFrontSchema(t.Context(), f.store); err == nil { + t.Fatal("shared physical schema damage accepted") + } +} + +func TestDamagedPendingSelectionQuarantinesWithoutStoppingOtherProjects(t *testing.T) { + for _, state := range []string{"queued", "selecting"} { + for _, fault := range []string{"time", "revision-type", "revision-limit", "fingerprint-type", "write-failure"} { + t.Run(state+"/"+fault, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + f.configure(t, otherAttemptProject, "other-account", 0, false) + bad, _ := selectionEnqueue(t, f, "damaged", "cli", nil) + admissionSQL(t, f, `UPDATE review_selections SET state=? WHERE id=?`, state, bad.ID) + switch fault { + case "revision-type": + admissionSQL(t, f, `UPDATE review_selections SET revision='broken' WHERE id=?`, bad.ID) + case "revision-limit": + admissionSQL(t, f, `UPDATE review_selections SET revision=9223372036854775807 WHERE id=?`, bad.ID) + case "fingerprint-type": + admissionSQL(t, f, `UPDATE review_selections SET capability_fingerprint=CAST(capability_fingerprint AS BLOB) WHERE id=?`, bad.ID) + default: + admissionSQL(t, f, `UPDATE review_selections SET updated_at='broken' WHERE id=?`, bad.ID) + } + if fault == "write-failure" { + admissionSQL(t, f, `CREATE TRIGGER refuse_quarantine BEFORE UPDATE ON review_selections WHEN NEW.state='held' BEGIN SELECT RAISE(ABORT,'synthetic failure'); END`) + } + before := snapshotTable(t, f, "review_selections") + var err error + if state == "selecting" { + err = f.e.RecoverReviewRuns(t.Context()) + } else { + _, err = f.e.runNext(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + } + if fault == "write-failure" { + if err == nil || automaticProjectRefused(err) || before != snapshotTable(t, f, "review_selections") { + t.Fatal("persistence failure suppressed or partially committed", err) + } + return + } + if err != nil { + t.Fatal("damaged row stopped workers", err) + } + var got, reason string + if err = f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=?`, bad.ID).Scan(&got, &reason); err != nil || got != "held" || reason != "local_read_unavailable" { + t.Fatal(got, reason, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("damaged row created child") + } + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal("restart failed", err) + } + raw, err := f.e.EnqueueRun(t.Context(), selectionScope(t, f, otherAttemptProject, f.admin, "write"), "healthy", RunRequest{Channel: "cli"}) + if err != nil { + t.Fatal(err) + } + var receipt Receipt + json.Unmarshal(raw, &receipt) + reader := &refreshTestReader{pull: func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { + return reviewprovider.Pull{Number: n, RepositoryID: 802, State: "open", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }} + if worked, err := f.e.runNext(t.Context(), map[string]TargetReader{"other-account": reader}); err != nil || !worked { + t.Fatal("healthy request blocked", worked, err) + } + if err = f.store.DB().QueryRow(`SELECT state FROM review_selections WHERE id=?`, receipt.ID).Scan(&got); err != nil || got != "selected" { + t.Fatal("healthy request not selected", got, err) + } + }) + } + } +} + +// These digests were captured from the previous per-pull reader. Reusing a +// transaction's shared reads must not rearm existing automatic selections. +func TestSchedulingPlanningDigestCompatibility(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + golden := map[string]string{ + "hosted": "6fb77710b10a99e847fcc73888722a511b59d9e66bc6973a295f34df6a5251ab", + "cli": "652c41394ef250db0e52f95df26f1b8e2badb766d25273f184e4e81a41d0dcf1", + } + check := func(changed bool) { + t.Helper() + err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + for _, channel := range []string{"hosted", "cli"} { + shared, err := readAutomaticBasis(ctx, tx, attemptProject, channel) + if err != nil { + return err + } + for _, pull := range []int64{2, 4} { + got, err := automaticPullBasisWithRead(ctx, tx, attemptProject, pull, channel, shared) + if err != nil { + return err + } + if (got != golden[channel]) != (changed && channel == "hosted") { + t.Fatalf("digest compatibility/freshness: %s %d %s changed=%v", channel, pull, got, changed) + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + check(false) + // A later transaction must refresh shared control facts, not reuse a cache + // from the prior planning pass, even for an unchanged PR queue. + schedulingEnable(t, f, 1, true) + check(true) +} diff --git a/internal/reviewexec/scheduling_revision_validation_test.go b/internal/reviewexec/scheduling_revision_validation_test.go new file mode 100644 index 000000000..baedc5529 --- /dev/null +++ b/internal/reviewexec/scheduling_revision_validation_test.go @@ -0,0 +1,74 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "testing" +) + +func TestAutomaticRetainedRevisionValidation(t *testing.T) { + for _, tc := range []struct { + name string + value any + }{ + {"text", "malformed"}, {"fraction", 1.5}, {"blob", []byte("1")}, {"null", nil}, {"zero", int64(0)}, {"negative", int64(-1)}, {"overflow", "9223372036854775808"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + // Remove physical constraints to model damaged retained data, including + // values SQLite's normal column constraints would have rejected. + admissionSQL(t, f, `ALTER TABLE review_automatic_selections RENAME TO saved_automatic_selections`) + admissionSQL(t, f, `CREATE TABLE review_automatic_selections AS SELECT * FROM saved_automatic_selections`) + admissionSQL(t, f, `UPDATE review_automatic_selections SET scheduling_revision=?`, tc.value) + err := continuityGuard(t, f, r) + if !automaticProjectRefused(err) { + t.Fatalf("malformed revision not isolated: %v", err) + } + }) + } +} + +func TestAutomaticRetainedRevisionPreservesQueryErrors(t *testing.T) { + for _, mode := range []string{"sql", "cancelled", "transaction"} { + t.Run(mode, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + ctx := t.Context() + switch mode { + case "sql": + if _, err := tx.Exec(`DROP TABLE review_automatic_selections`); err != nil { + t.Fatal(err) + } + case "cancelled": + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + cancel() + case "transaction": + if err := tx.Rollback(); err != nil { + t.Fatal(err) + } + } + err = f.e.requireAutomaticRun(ctx, tx, r) + if err == nil || automaticProjectRefused(err) { + t.Fatalf("real failure suppressed: %v", err) + } + if mode == "cancelled" && !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + if mode == "transaction" && !errors.Is(err, sql.ErrTxDone) { + t.Fatal(err) + } + }) + } +} diff --git a/internal/reviewexec/scheduling_schema.go b/internal/reviewexec/scheduling_schema.go new file mode 100644 index 000000000..63db42f98 --- /dev/null +++ b/internal/reviewexec/scheduling_schema.go @@ -0,0 +1,32 @@ +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()) +} + +func schedulingV2MigrationSQL() []string { + return []string{`ALTER TABLE review_scheduling ADD COLUMN automatic_cli INTEGER NOT NULL DEFAULT 0 CHECK(automatic_cli IN(0,1))`} +} + +// SchedulingSchemaV2SQL is the canonical physical shape after the additive migration. +func SchedulingSchemaV2SQL() []string { + statements := SchedulingSchemaSQL() + statements[0] = statements[0][:len(statements[0])-1] + ", automatic_cli INTEGER NOT NULL DEFAULT 0 CHECK(automatic_cli IN(0,1)))" + return statements +} diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go new file mode 100644 index 000000000..0d3c4a950 --- /dev/null +++ b/internal/reviewexec/scheduling_snapshot.go @@ -0,0 +1,159 @@ +package reviewexec + +import ( + "context" + "database/sql" + "strings" + + "github.com/benhook1013/FireController/internal/core" +) + +// 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 + } + 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 + } + for rows.Next() { + var s PullScheduling + if err = scanSchedulingSnapshot(rows, &s.ProjectID, &s.PullNumber, &s.Revision, &s.Paused, &s.Reason, &s.ActorID, &s.UpdatedAt); err != nil { + break + } + if !identifier.MatchString(s.ProjectID) || s.PullNumber < 1 || s.PullNumber > 2147483647 || s.Revision < 1 || !identifier.MatchString(s.ActorID) || !roundTime(s.UpdatedAt) || !validSchedulingReason(s.Reason) || !s.Paused && s.Reason != "" { + err = schedulingUnavailable() + break + } + } + if err == nil { + err = rows.Err() + } + closeErr = rows.Close() + if err != nil { + return err + } + if closeErr != nil { + return closeErr + } + 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() + } + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections a LEFT JOIN review_selections s ON s.id=a.selection_id LEFT JOIN review_scheduling c ON c.project_id=a.project_id LEFT JOIN review_operations o ON o.id=s.operation_id WHERE s.id IS NULL OR s.project_id<>a.project_id OR s.channel NOT IN(`+channels+`) OR s.actor_id<>a.actor_id OR s.worker_id<>a.worker_id OR c.project_id IS NULL OR a.scheduling_revision>c.revision OR (a.pull_number=0 AND (a.pull_basis_sha256<>'' OR s.state='selected')) OR (a.pull_number<>0 AND (s.state<>'selected' OR o.id IS NULL OR o.pull_number<>a.pull_number OR o.project_id<>a.project_id OR o.channel<>s.channel OR o.actor_id<>a.actor_id OR o.worker_id<>a.worker_id)))`).Scan(&bad) + if err != nil { + return err + } + if bad { + return schedulingUnavailable() + } + rows, err = tx.QueryContext(ctx, `SELECT selection_id,project_id,scheduling_revision,basis_sha256,settled_basis_sha256,pull_number,pull_basis_sha256,actor_id,worker_id,credential_id FROM review_automatic_selections`) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var selection, project, basis, settled, pullBasis, actor, worker, credential string + var revision, pull int64 + if err = scanSchedulingSnapshot(rows, &selection, &project, &revision, &basis, &settled, &pull, &pullBasis, &actor, &worker, &credential); err != nil { + return err + } + if !validRunID(selection) || !identifier.MatchString(project) || revision < 1 || !hash.MatchString(basis) || settled != "" && !hash.MatchString(settled) || pull < 0 || pull > 2147483647 || pull > 0 && !hash.MatchString(pullBasis) || !identifier.MatchString(actor) || !identifier.MatchString(worker) || !identifier.MatchString(credential) { + return core.Fail("storage_unavailable", "Stored automatic review attribution is unavailable.", 503) + } + } + if err = rows.Err(); err != nil { + return err + } + return rows.Close() +} + +// Preserve SQLite storage types before checking control and attribution values. +// database/sql otherwise accepts conversions (notably BLOB to string) that the +// live control readers deliberately reject. Genuine scan/query errors propagate. +func scanSchedulingSnapshot(row interface{ Scan(...any) error }, destinations ...any) error { + values := make([]any, len(destinations)) + pointers := make([]any, len(values)) + for i := range values { + pointers[i] = &values[i] + } + if err := row.Scan(pointers...); err != nil { + return err + } + for i, destination := range destinations { + switch target := destination.(type) { + case *string: + value, ok := values[i].(string) + if !ok { + return schedulingUnavailable() + } + *target = value + case *int64: + value, ok := values[i].(int64) + if !ok { + return schedulingUnavailable() + } + *target = value + case *bool: + value, ok := values[i].(int64) + if !ok || value < 0 || value > 1 { + return schedulingUnavailable() + } + *target = value == 1 + default: + return schedulingUnavailable() + } + } + return nil +} diff --git a/internal/reviewexec/scheduling_snapshot0030_test.go b/internal/reviewexec/scheduling_snapshot0030_test.go new file mode 100644 index 000000000..95b97b0e4 --- /dev/null +++ b/internal/reviewexec/scheduling_snapshot0030_test.go @@ -0,0 +1,56 @@ +package reviewexec + +import ( + "errors" + "testing" +) + +type schedulingSnapshot0030Row struct { + values []any + err error +} + +func (r schedulingSnapshot0030Row) Scan(destinations ...any) error { + if r.err != nil { + return r.err + } + for i, value := range r.values { + *destinations[i].(*any) = value + } + return nil +} + +func TestSchedulingSnapshot0030PreservesStoredTypes(t *testing.T) { + var text string + var revision int64 + var enabled bool + if err := scanSchedulingSnapshot(schedulingSnapshot0030Row{values: []any{"reason", int64(1), int64(1)}}, &text, &revision, &enabled); err != nil || text != "reason" || revision != 1 || !enabled { + t.Fatal("valid stored values refused", text, revision, enabled, err) + } + for _, tc := range []struct { + name string + value any + destination any + }{ + {"blob-string", []byte("reason"), &text}, + {"number-string", int64(1), &text}, + {"null-string", nil, &text}, + {"text-revision", "1", &revision}, + {"real-revision", float64(1), &revision}, + {"blob-revision", []byte("1"), &revision}, + {"null-revision", nil, &revision}, + {"text-enabled", "true", &enabled}, + {"real-enabled", float64(1), &enabled}, + {"invalid-enabled", int64(2), &enabled}, + {"negative-enabled", int64(-1), &enabled}, + {"null-enabled", nil, &enabled}, + } { + t.Run(tc.name, func(t *testing.T) { + attemptCode(t, scanSchedulingSnapshot(schedulingSnapshot0030Row{values: []any{tc.value}}, tc.destination), "storage_unavailable") + }) + } + failure := errors.New("synthetic query failure") + if got := scanSchedulingSnapshot(schedulingSnapshot0030Row{err: failure}, &text); got != failure { + t.Fatal("query failure reclassified as retained data", got) + } +} diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go new file mode 100644 index 000000000..c5d290824 --- /dev/null +++ b/internal/reviewexec/scheduling_source_retry.go @@ -0,0 +1,158 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "time" +) + +const automaticSourceRetryDelay = 30 * time.Second + +// The selection's retained monotonic revision is a conservative transition +// budget, not a retry counter. An ordinary failure is revision 3; each complete +// requeue/claim/failure costs three more revisions. Allowing only revisions <= 6 +// permits at most two delayed retries of completed source holds. Restart +// recovery consumes this budget too, never replenishes it. Existing backup/restore retains both the +// revision and updated_at, so neither process restarts nor restore reset it. +func transientAutomaticSourceHold(r Run) bool { + if !validChannel(r.Channel) || r.State != "held" || r.OperationID != "" || r.Revision < 3 || r.Revision > 6 { + return false + } + switch r.Reason { + case "source_budget_exhausted", "source_fetch_timeout", "source_provider_unavailable": + return true + } + return false +} + +// retryAutomaticSourceTx only requeues a previously accepted read-only intent. +// It is called after the normal coordinator's restore, authorizer, pause and +// active-operation checks, and only for an already suppressed semantic basis. +// No operation, attempt, grant or new selection is created here. +func (e *Engine) retryAutomaticSourceTx(ctx context.Context, tx *sql.Tx, project, basis string, schedulingRevision int64, now time.Time) (bool, error) { + return e.retryAutomaticSourceChannelTx(ctx, tx, project, basis, schedulingRevision, now, "hosted") +} + +func (e *Engine) retryAutomaticSourceChannelTx(ctx context.Context, tx *sql.Tx, project, basis string, schedulingRevision int64, now time.Time, channel string) (bool, error) { + r, err := e.automaticSourceRetryCandidate(ctx, tx, project, basis, schedulingRevision, now, channel) + if err != nil || r == nil { + return false, err + } + if err = updateRunAt(ctx, tx, *r, "queued", "", "", now); err != nil { + return false, err + } + return true, nil +} + +// This read-only check is shared by preflight and writer revalidation. +func (e *Engine) automaticSourceRetryCandidate(ctx context.Context, tx *sql.Tx, project, basis string, schedulingRevision int64, now time.Time, channel string) (*Run, error) { + if !validChannel(channel) { + return nil, schedulingUnavailable() + } + var id string + err := tx.QueryRowContext(ctx, `SELECT s.id FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id AND a.project_id=s.project_id WHERE s.project_id=? AND s.channel=? AND s.state='held' AND s.operation_id IS NULL AND s.revision BETWEEN 3 AND 6 AND a.scheduling_revision=? AND (a.basis_sha256=? OR a.settled_basis_sha256=?) ORDER BY s.created_at DESC,s.id LIMIT 1`, project, channel, schedulingRevision, basis, basis).Scan(&id) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + r, err := readRun(ctx, tx, project, id) + if err != nil { + return nil, err + } + if !transientAutomaticSourceHold(r) { + return nil, nil + } + updated, err := time.Parse(time.RFC3339Nano, r.UpdatedAt) + if err != nil { + return nil, runUnavailable() + } + if now.Before(updated.Add(automaticSourceRetryDelay)) { + return nil, nil + } + superseded, err := automaticSourceSuperseded(ctx, tx, r) + if err != nil || superseded { + return nil, err + } + _, _, reason, err := e.runBinding(ctx, tx, r) + if err != nil || reason != "" { + return nil, err + } + return &r, nil +} + +// Recheck recovery fences during every admission snapshot, including after +// source I/O. Interrupted initial reads retain ordinary authorization continuity. +// Completed source holds require the exact accepted scheduling revision even +// after further interrupted reads; incomplete transition evidence is conservative. +func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (string, error) { + if !validChannel(r.Channel) || r.Revision < 4 { + return "", nil + } + var accepted, current int64 + err := tx.QueryRowContext(ctx, `SELECT a.scheduling_revision,s.revision FROM review_automatic_selections a JOIN review_scheduling s ON s.project_id=a.project_id WHERE a.project_id=? AND a.selection_id=?`, r.ProjectID, r.ID).Scan(&accepted, ¤t) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + if err != nil { + return "", err + } + if accepted != current { + initial, err := automaticSourceInitialRead(ctx, tx, r) + if err != nil { + return "", err + } + if !initial { + return "automation_authorization_changed", nil + } + } + superseded, err := automaticSourceSuperseded(ctx, tx, r) + if err != nil { + return "", err + } + if superseded { + return "selection_superseded", nil + } + return "", nil +} + +// A revision alone cannot distinguish restart recovery from a completed hold. +// Prove every retained transition was an unfinished read before relaxing the +// exact-revision fence. A held event (whatever its reason), missing/duplicate +// revision or malformed payload keeps that fence. Aggregate in SQL rather than +// copying an unbounded event history into each admission snapshot. +func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, error) { + var count, distinct, first, last, invalid int64 + err := tx.QueryRowContext(ctx, `SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( + CASE WHEN typeof(revision)='integer' AND json_valid(payload_json) THEN + CASE WHEN json_extract(payload_json,'$.state') IN ('queued','selecting') AND json_extract(payload_json,'$.reason')='' THEN 0 ELSE 1 END + ELSE 1 END),0) + FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' AND revision BETWEEN 2 AND ?`, r.ProjectID, r.ID, r.Revision).Scan(&count, &distinct, &first, &last, &invalid) + if err != nil { + return false, err + } + return count == r.Revision-1 && distinct == count && first == 2 && last == r.Revision && invalid == 0, nil +} + +func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, error) { + // Any later or simultaneous same-channel intent supersedes this recovery, even if + // that intent was cancelled, denied, held or completed. A directly submitted + // operation is also a fence; never recover behind its cancellation/uncertainty. + // Compare parsed times, not RFC3339 text with variable fractional precision. + // Millisecond ties conservatively fence rather than ordering by random IDs. + // Event sequence is the durable acceptance order even if the wall clock + // moves backwards. Missing acceptance evidence is not permission to retry. + var accepted int64 + err := tx.QueryRowContext(ctx, `SELECT sequence FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_requested' AND revision=1 ORDER BY sequence DESC LIMIT 1`, r.ProjectID, r.ID).Scan(&accepted) + if errors.Is(err, sql.ErrNoRows) { + return true, nil + } + if err != nil { + return false, err + } + var superseded bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections WHERE project_id=? AND channel=? AND id<>? AND julianday(created_at)>=julianday(?)) OR EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND channel=? AND julianday(created_at)>=julianday(?)) OR EXISTS(SELECT 1 FROM events e JOIN review_selections s ON s.project_id=e.project_id AND s.id=e.resource_id WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.selection_requested' AND 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 o.channel=?)`, r.ProjectID, r.Channel, r.ID, r.CreatedAt, r.ProjectID, r.Channel, r.CreatedAt, r.ProjectID, accepted, r.Channel, r.ProjectID, accepted, r.Channel).Scan(&superseded) + return superseded, err +} diff --git a/internal/reviewexec/scheduling_source_retry_test.go b/internal/reviewexec/scheduling_source_retry_test.go new file mode 100644 index 000000000..f693fa843 --- /dev/null +++ b/internal/reviewexec/scheduling_source_retry_test.go @@ -0,0 +1,379 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "strings" + "sync" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func sourceRetryFixture(t *testing.T) (*attemptFixture, Run) { + t.Helper() + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, context.DeadlineExceeded + }}) + r := schedulingLatest(t, f) + if r.State != "held" || r.Revision != 3 || r.OperationID != "" { + t.Fatal(r) + } + return f, r +} +func ageSourceRetry(t *testing.T, f *attemptFixture, id string) { + t.Helper() + at := time.Now().Add(-time.Minute).UTC().Format(time.RFC3339Nano) + if _, err := f.store.DB().Exec(`UPDATE review_selections SET created_at=?,updated_at=? WHERE id=?`, at, at, id); err != nil { + t.Fatal(err) + } +} +func retrySourceDirect(t *testing.T, f *attemptFixture, r Run, now time.Time) bool { + t.Helper() + var worked bool + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var basis string + if err := tx.QueryRowContext(ctx, `SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, r.ID).Scan(&basis); err != nil { + return err + } + s, err := readScheduling(ctx, tx, r.ProjectID) + if err != nil { + return err + } + worked, err = f.e.retryAutomaticSourceTx(ctx, tx, r.ProjectID, basis, s.Revision, now) + return err + }) + if err != nil { + t.Fatal(err) + } + return worked +} +func TestAutomaticSourceRetryDelayedSameIntentSingleChild(t *testing.T) { + f, original := sourceRetryFixture(t) + schedulingGenerate(t, f, false) + if got := schedulingLatest(t, f); got.Revision != original.Revision { + t.Fatal(got) + } + ageSourceRetry(t, f, original.ID) + schedulingGenerate(t, f, true) + got := schedulingLatest(t, f) + if got.ID != original.ID || got.State != "queued" || got.Revision != 4 || got.ActorID != original.ActorID || got.WorkerID != original.WorkerID || got.ConfigurationRevision != original.ConfigurationRevision || got.PolicyRevision != original.PolicyRevision { + t.Fatal(got) + } + schedulingGenerate(t, f, false) + selectionNext(t, f, &refreshTestReader{}) + got = schedulingLatest(t, f) + if got.State != "selected" || got.OperationID == "" || got.ID != original.ID { + t.Fatal(got) + } + schedulingGenerate(t, f, false) + if attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 { + t.Fatal("retry duplicated intent or started provider work") + } +} +func TestAutomaticSourceRetryBudgetSurvivesEngineRestart(t *testing.T) { + f, original := sourceRetryFixture(t) + reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, context.DeadlineExceeded + }} + for _, expected := range []int64{6, 9} { + ageSourceRetry(t, f, original.ID) + restarted, err := New(f.store, attemptCapabilities) + if err != nil { + t.Fatal(err) + } + f.e = restarted + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + schedulingGenerate(t, f, true) + selectionNext(t, f, reader) + if got := schedulingLatest(t, f); got.ID != original.ID || got.Revision != expected || got.State != "held" { + t.Fatal(got) + } + } + ageSourceRetry(t, f, original.ID) + for range 3 { + schedulingGenerate(t, f, false) + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + } + if reader.calls.Load() != 2 || attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("retry budget reset") + } +} +func TestAutomaticSourceRetryReasonAllowlist(t *testing.T) { + for _, reason := range []string{"source_budget_exhausted", "source_fetch_timeout", "source_provider_unavailable", "source_rate_limited", "source_unauthorized", "source_not_found", "source_response_invalid", "source_unavailable", "restore_abandoned", "selection_changed", "provider_unavailable", "cancelled", "source_reader_unavailable"} { + t.Run(reason, func(t *testing.T) { + f, r := sourceRetryFixture(t) + if _, err := f.store.DB().Exec(`UPDATE review_selections SET reason=? WHERE id=?`, reason, r.ID); err != nil { + t.Fatal(err) + } + want := reason == "source_budget_exhausted" || reason == "source_fetch_timeout" || reason == "source_provider_unavailable" + if got := retrySourceDirect(t, f, r, time.Now().Add(time.Minute)); got != want { + t.Fatal(reason, got) + } + }) + } +} +func TestAutomaticSourceRetryFences(t *testing.T) { + for _, mode := range []string{"configuration", "policy", "authorization", "worker", "scheduling", "newer-intent", "explicit", "budget", "capability"} { + t.Run(mode, func(t *testing.T) { + f, r := sourceRetryFixture(t) + switch mode { + case "configuration": + f.configure(t, attemptProject, "test-capability", 1, false) + case "policy": + assessmentPolicy(t, f, 1, []string{"cli"}, []string{}) + case "authorization": + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) + case "worker": + admissionSQL(t, f, `DELETE FROM workers WHERE project_id='`+attemptProject+`' AND id='selection-worker'`) + case "scheduling": + schedulingEnable(t, f, 1, true) + case "newer-intent": + selectionEnqueue(t, f, "later-intent", "hosted", nil) + case "explicit": + admissionSQL(t, f, `DELETE FROM review_automatic_selections WHERE selection_id='`+r.ID+`'`) + case "budget": + admissionSQL(t, f, `UPDATE review_selections SET revision=9 WHERE id='`+r.ID+`'`) + case "capability": + admissionSQL(t, f, `UPDATE review_selections SET capability_fingerprint='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' WHERE id='`+r.ID+`'`) + } + if mode == "explicit" { + ageSourceRetry(t, f, r.ID) + // Direct helper cannot find a retained automatic intent for this selection. + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + worked, err := f.e.retryAutomaticSourceTx(ctx, tx, attemptProject, "unused", 1, time.Now()) + if worked { + t.Error("explicit intent retried") + } + return err + }) + if err != nil { + t.Fatal(err) + } + } else if retrySourceDirect(t, f, r, time.Now().Add(time.Minute)) { + t.Fatal("fence ignored", mode) + } + }) + } +} +func TestAutomaticSourceRetryConcurrentTicks(t *testing.T) { + f, r := sourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + var wg sync.WaitGroup + results := make(chan bool, 2) + failures := make(chan error, 2) + for range 2 { + wg.Go(func() { + worked, err := f.e.coordinateAutomaticHosted(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + results <- worked + failures <- err + }) + } + wg.Wait() + close(results) + close(failures) + count := 0 + for worked := range results { + if worked { + count++ + } + } + for err := range failures { + if err != nil { + t.Fatal(err) + } + } + if count != 1 || schedulingLatest(t, f).Revision != 4 { + t.Fatal("concurrent ticks duplicated recovery", count) + } +} + +func TestAutomaticSourceRetryInterruptedClaimConsumesBudget(t *testing.T) { + f, r := sourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + schedulingGenerate(t, f, true) + // Crash after claiming this recovery but before completing its source read. + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + current, err := readRun(ctx, tx, r.ProjectID, r.ID) + if err != nil { + return err + } + return updateRun(ctx, tx, current, "selecting", "", "") + }); err != nil { + t.Fatal(err) + } + restarted, err := New(f.store, attemptCapabilities) + if err != nil { + t.Fatal(err) + } + f.e = restarted + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + if got := schedulingLatest(t, f); got.Revision != 6 || got.State != "queued" { + t.Fatal(got) + } + selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, context.DeadlineExceeded + }}) + if got := schedulingLatest(t, f); got.Revision != 8 || got.State != "held" { + t.Fatal(got) + } + ageSourceRetry(t, f, r.ID) + schedulingGenerate(t, f, false) +} + +func TestAutomaticSourceRetryFencedByLaterOperation(t *testing.T) { + for _, state := range []string{"queued", "uncertain", "cancelled", "held", "completed"} { + t.Run(state, func(t *testing.T) { + f, r := sourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + raw, err := f.e.Enqueue(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "new-direct-operation", Request{ExpectedConfigurationRevision: 1, PullNumber: 2, HeadSHA: strings.Repeat("a", 40), Channel: "hosted"}) + if err != nil { + t.Fatal(err) + } + var receipt Receipt + if err = json.Unmarshal(raw, &receipt); err != nil { + t.Fatal(err) + } + if state == "cancelled" { + _, err = f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-later-intent", receipt.ID, OperationControl{ExpectedRevision: 1, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + } else if state != "queued" { + admissionSQL(t, f, `UPDATE review_operations SET state=? WHERE id=?`, state, receipt.ID) + } + if retrySourceDirect(t, f, r, time.Now()) { + t.Fatal("later operation ignored", state) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 { + t.Fatal("operation duplicated") + } + }) + } +} + +func TestAutomaticSourceRetryTransactionRollbackDoesNotConsumeBudget(t *testing.T) { + f, r := sourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + admissionSQL(t, f, `CREATE TRIGGER retry_failure BEFORE INSERT ON events WHEN NEW.event_type='review.selection_updated' AND json_extract(NEW.payload_json,'$.state')='queued' BEGIN SELECT RAISE(ABORT,'synthetic failure'); END`) + worked, err := f.e.generateAutomaticHosted(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err == nil || worked { + t.Fatal("failed transaction appeared successful", worked, err) + } + if got := schedulingLatest(t, f); got.State != "held" || got.Revision != 3 { + t.Fatal(got) + } + admissionSQL(t, f, `DROP TRIGGER retry_failure`) + schedulingGenerate(t, f, true) + if got := schedulingLatest(t, f); got.ID != r.ID || got.Revision != 4 { + t.Fatal(got) + } +} + +func TestAutomaticSourceRetryCoordinatorSafetyHolds(t *testing.T) { + for _, mode := range []string{"disabled", "paused", "restore", "inactive"} { + t.Run(mode, func(t *testing.T) { + f, r := sourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + switch mode { + case "disabled": + schedulingEnable(t, f, 1, false) + case "paused": + schedulingPause(t, f, 2, 0, true) + case "restore": + admissionSQL(t, f, `INSERT INTO metadata(key,value) VALUES('restore:provider_state','held')`) + case "inactive": + admissionSQL(t, f, `INSERT INTO metadata(key,value) VALUES('restore:state','inactive')`) + } + schedulingGenerate(t, f, false) + if got := schedulingLatest(t, f); got.ID != r.ID || got.State != "held" || got.Revision != r.Revision { + t.Fatal(got) + } + }) + } +} + +func TestAutomaticSourceRetryTimestampPrecisionFence(t *testing.T) { + f, r := sourceRetryFixture(t) + at := time.Now().Add(-time.Minute).Truncate(time.Second) + admissionSQL(t, f, `UPDATE review_selections SET created_at=?,updated_at=? WHERE id=?`, at.Format(time.RFC3339Nano), at.Format(time.RFC3339Nano), r.ID) + later, _ := selectionEnqueue(t, f, "later-fractional-time", "hosted", nil) + admissionSQL(t, f, `UPDATE review_selections SET created_at=?,updated_at=? WHERE id=?`, at.Add(time.Millisecond).Format(time.RFC3339Nano), at.Add(time.Millisecond).Format(time.RFC3339Nano), later.ID) + if retrySourceDirect(t, f, r, time.Now()) { + t.Fatal("variable timestamp precision lost newer-intent fence") + } +} + +func TestAutomaticSourceRetryRechecksFencesAfterSourceIO(t *testing.T) { + for _, mode := range []string{"cancelled-operation", "scheduling", "configuration", "policy"} { + t.Run(mode, func(t *testing.T) { + f, r := sourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + schedulingGenerate(t, f, true) + var once sync.Once + reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + once.Do(func() { + switch mode { + case "cancelled-operation": + raw, err := f.e.Enqueue(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "during-source", Request{ExpectedConfigurationRevision: 1, PullNumber: 2, HeadSHA: strings.Repeat("a", 40), Channel: "hosted"}) + if err != nil { + t.Fatal(err) + } + var receipt Receipt + if err = json.Unmarshal(raw, &receipt); err != nil { + t.Fatal(err) + } + _, err = f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-during-source", receipt.ID, OperationControl{ExpectedRevision: 1, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + case "scheduling": + schedulingEnable(t, f, 1, true) + case "configuration": + f.configure(t, attemptProject, "test-capability", 1, false) + case "policy": + assessmentPolicy(t, f, 1, []string{"cli"}, []string{}) + } + }) + return reviewprovider.Repository{ID: 801, FullName: "owner/repo", DefaultBranch: "main"}, nil + }} + selectionNext(t, f, reader) + got := selectionRead(t, f, r.ID) + if got.State != "held" || got.OperationID != "" { + t.Fatal("changed authority or cancelled successor ignored", got) + } + expected := 0 + if mode == "cancelled-operation" { + expected = 1 + if got.Reason != "selection_superseded" { + t.Fatal(got) + } + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != expected { + t.Fatal("retry created a child after its fence changed") + } + }) + } +} + +func TestAutomaticSourceRetryAcceptanceOrderSurvivesClockRollback(t *testing.T) { + f, r := sourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + later, _ := selectionEnqueue(t, f, "later-with-clock-rollback", "hosted", nil) + at := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano) + admissionSQL(t, f, `UPDATE review_selections SET created_at=?,updated_at=? WHERE id=?`, at, at, later.ID) + if retrySourceDirect(t, f, r, time.Now()) { + t.Fatal("wall-clock rollback erased a later accepted intent") + } +} diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go new file mode 100644 index 000000000..a355a5fca --- /dev/null +++ b/internal/reviewexec/scheduling_test.go @@ -0,0 +1,1427 @@ +package reviewexec + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewprovider" + "github.com/benhook1013/FireController/internal/reviews" + "net/http" + "net/http/httptest" + "reflect" + "strconv" + "strings" + "testing" + "time" +) + +func schedulingFixture(t *testing.T) *attemptFixture { + return schedulingFixtureWithQueue(t, []int64{2, 4}) +} +func schedulingFixtureWithQueue(t *testing.T, queue []int64) *attemptFixture { + f := selectionFixtureWithQueue(t, queue) + admissionSQL(t, f, `UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'`) + mux := http.NewServeMux() + f.e.Register(mux) + f.handler = mux + return f +} +func schedulingEnable(t *testing.T, f *attemptFixture, revision int64, on bool) { + t.Helper() + _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "automatic-"+core.NewID("key"), SchedulingRequest{ExpectedRevision: &revision, AutomaticHosted: &on}) + if err != nil { + t.Fatal(err) + } +} +func schedulingPause(t *testing.T, f *attemptFixture, pull, revision int64, paused bool) { + t.Helper() + _, err := f.e.ConfigurePullScheduling(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), core.NewID("pause"), pull, PullSchedulingRequest{ExpectedRevision: &revision, Paused: &paused, Reason: "Fix in progress"}) + if err != nil { + t.Fatal(err) + } +} +func schedulingGenerate(t *testing.T, f *attemptFixture, want bool) { + t.Helper() + worked, err := f.e.generateAutomaticHosted(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err != nil || worked != want { + t.Fatalf("automatic selection worked=%v want=%v: %v", worked, want, err) + } +} +func schedulingLatest(t *testing.T, f *attemptFixture) Run { + t.Helper() + var id string + if err := f.store.DB().QueryRow(`SELECT selection_id FROM review_automatic_selections ORDER BY rowid DESC LIMIT 1`).Scan(&id); err != nil { + t.Fatal(err) + } + return selectionRead(t, f, id) +} +func TestSchedulingHTTPDefaultsStrictCASAndPermissions(t *testing.T) { + f := schedulingFixture(t) + call := func(method, path, token, key, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, "/api/v1/projects/"+attemptProject+"/reviews/"+path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+token) + r.Header.Set("X-FC-Worker", "selection-worker") + if key != "" { + r.Header.Set("Idempotency-Key", key) + } + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + return w + } + w := call("GET", "scheduling", f.reader, "", "") + if w.Code != 200 || strings.TrimSpace(w.Body.String()) != `{"paused_pulls":[],"project_id":"exec-project-one","revision":0,"automatic_cli":false,"automatic_hosted":false}` { + t.Fatal(w.Code, w.Body.String()) + } + w = call("GET", "pulls/2/scheduling", f.reader, "", "") + var p PullScheduling + if json.Unmarshal(w.Body.Bytes(), &p) != nil || p.Paused || p.Revision != 0 || p.Reason != "" { + t.Fatal(w.Code, w.Body.String()) + } + for _, body := range []string{`{}`, `{"expected_revision":0}`, `{"expected_revision":0,"automatic_hosted":null}`, `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":null}`, `{"expected_revision":0,"automatic_hosted":true,"token":"private"}`, `{"expected_revision":0,"automatic_hosted":true,"automatic_hosted":false}`} { + if w = call("POST", "scheduling", f.writer, core.NewID("key"), body); w.Code != 400 { + t.Fatal(w.Code, w.Body.String()) + } + } + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + if w = call("POST", "scheduling", f.writer, "permission", `{"expected_revision":0,"automatic_hosted":true}`); w.Code != 403 { + t.Fatal(w.Code, w.Body.String()) + } + admissionSQL(t, f, `UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'`) + w = call("POST", "scheduling", f.writer, "enable", `{"expected_revision":0,"automatic_hosted":true}`) + if w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + original := append([]byte(nil), w.Body.Bytes()...) + if w = call("POST", "scheduling", f.writer, "stale", `{"expected_revision":0,"automatic_hosted":false}`); w.Code != 409 { + t.Fatal(w.Code) + } + if w = call("POST", "scheduling", f.writer, "enable", `{"expected_revision":0,"automatic_hosted":true}`); w.Code != 200 || !bytes.Equal(w.Body.Bytes(), original) { + t.Fatal(w.Code, w.Body.String()) + } + w = call("GET", "scheduling", f.reader, "", "") + if strings.Contains(w.Body.String(), "credential") || strings.Contains(w.Body.String(), "principal") || !strings.Contains(w.Body.String(), `"authorizing_worker_id":"selection-worker"`) { + t.Fatal(w.Body.String()) + } + for _, body := range []string{`{"expected_revision":0,"paused":null}`, `{"expected_revision":0,"paused":true,"reason":null}`, `{"expected_revision":0,"paused":true,"reason":"\n"}`} { + if w = call("POST", "pulls/2/scheduling", f.writer, core.NewID("key"), body); w.Code != 400 { + t.Fatal(w.Code, w.Body.String()) + } + } + if w = call("POST", "pulls/2/scheduling", f.writer, "pause", `{"expected_revision":0,"paused":true,"reason":"Fixing"}`); w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + if w = call("POST", "pulls/2/scheduling", f.writer, "resume", `{"expected_revision":1,"paused":false,"reason":"discarded"}`); w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + w = call("GET", "pulls/2/scheduling", f.reader, "", "") + if json.Unmarshal(w.Body.Bytes(), &p) != nil || p.Paused || p.Reason != "" || p.Revision != 2 { + t.Fatal(w.Body.String()) + } + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + if w = call("POST", "scheduling", f.writer, "enable", `{"expected_revision":0,"automatic_hosted":true}`); w.Code != 403 { + t.Fatal("replay bypassed current management", w.Code) + } +} +func TestSchedulingPausedBothChannelsPreservesQueuedIdentityAndOperationPause(t *testing.T) { + f := schedulingFixture(t) + r := f.enqueue(t, attemptProject, "existing", "cli", 2, 1) + schedulingPause(t, f, 2, 0, true) + before := roundTables(t, f) + for _, channel := range []string{"cli", "hosted"} { + _, err := f.e.Enqueue(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), core.NewID("key"), Request{ExpectedConfigurationRevision: 1, PullNumber: 2, HeadSHA: strings.Repeat("a", 40), Channel: channel}) + attemptCode(t, err, "pull_scheduling_paused") + } + a, err := f.e.StartAttempt(t.Context(), attemptProject, r.ID) + if err != nil || a.ID != "" { + t.Fatal(a, err) + } + if roundTables(t, f) != before { + t.Fatal("paused admission changed retained state") + } + schedulingPause(t, f, 2, 1, false) + a, err = f.e.StartAttempt(t.Context(), attemptProject, r.ID) + if err != nil || a.ID == "" { + t.Fatal(a, err) + } + schedulingPause(t, f, 2, 2, true) + _, err = f.e.ExecutionContext(t.Context(), attemptProject, r.ID) + attemptCode(t, err, "pull_scheduling_paused") + // A separate operation pause is not cleared by resuming PR scheduling. + other := f.enqueue(t, attemptProject, "other", "hosted", 4, 1) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + _, err = f.e.ControlOperation(t.Context(), scope, "operation-pause", other.ID, OperationControl{ExpectedRevision: 1, Action: "pause"}) + if err != nil { + t.Fatal(err) + } + schedulingPause(t, f, 4, 0, true) + schedulingPause(t, f, 4, 1, false) + op, err := f.e.ReadOperation(t.Context(), scope, other.ID) + if err != nil || op.Wait == nil || !op.Wait.Paused { + t.Fatal(op, err) + } +} +func TestSchedulingAutomaticDefaultOffCancellationAndRestart(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingGenerate(t, f, false) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + if r.Channel != "hosted" || r.ActorID != "exec-writer-principal" || r.WorkerID != "selection-worker" { + t.Fatal(r) + } + selectionNext(t, f, &refreshTestReader{}) + r = schedulingLatest(t, f) + if r.State != "selected" { + t.Fatal(r) + } + _, err := f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-auto", r.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + counts := selectionCounts(t, f) + schedulingGenerate(t, f, false) + restarted, err := New(f.store, attemptCapabilities) + if err != nil { + t.Fatal(err) + } + f.e = restarted + if err = f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + schedulingGenerate(t, f, false) + if selectionCounts(t, f) != counts { + t.Fatal("cancelled intent regenerated") + } + // A deliberate scheduling revision authorizes a new semantic intent, not a tick. + schedulingEnable(t, f, 1, true) + schedulingGenerate(t, f, true) +} +func TestSchedulingAutomaticAuthorizerWithdrawalAndRestoreHold(t *testing.T) { + for _, kind := range []string{"management", "revoked", "retired", "disabled", "restore"} { + t.Run(kind, func(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + switch kind { + case "management": + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + case "revoked": + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) + case "retired": + admissionSQL(t, f, `INSERT INTO worker_retirements VALUES(?,'selection-worker',?,'synthetic-actor')`, attemptProject, stamp()) + case "disabled": + schedulingEnable(t, f, 1, false) + case "restore": + admissionSQL(t, f, `INSERT INTO metadata VALUES('restore:provider_state','held')`) + } + schedulingGenerate(t, f, false) + if attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 0 { + t.Fatal("withdrawn authority generated selection") + } + }) + } + // Authorization is also checked after a selection has created its child. + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + a, err := f.e.StartAttempt(t.Context(), attemptProject, r.OperationID) + if err != nil || a.ID != "" { + t.Fatal("withdrawn manager claimed attempt", a, err) + } +} +func TestSchedulingPausedFrontSkipsIndependentButNotDependency(t *testing.T) { + f := schedulingFixture(t) + schedulingPause(t, f, 2, 0, true) + r, _ := selectionEnqueue(t, f, "independent-paused", "hosted", nil) + selectionNext(t, f, &refreshTestReader{}) + got := selectionRead(t, f, r.ID) + if got.State != "selected" { + t.Fatal(got) + } + op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), got.OperationID) + if err != nil || op.PullNumber != 4 { + t.Fatal(op, err) + } + // The same evaluator cannot turn a paused parent into earned completion. + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + base := strings.Repeat("b", 40) + head := strings.Repeat("a", 40) + plans := []SourcePlan{{Pull: schedulingPull(2), ParentSHA: base}, {Pull: schedulingPull(4), ParentPullNumber: 2, ParentSHA: head}} + for i := range plans { + plans[i].Repository.ID = 801 + } + plans[1].Pull.BaseSHA = head + front, reason, err := f.e.runFront(ctx, tx, Run{ProjectID: attemptProject, Channel: "hosted"}, 801, plans) + if err != nil { + return err + } + if front != 0 || reason != "pull_scheduling_paused" { + t.Fatalf("dependent PR passed paused parent: %d %s", front, reason) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func schedulingPull(n int64) reviewprovider.Pull { + return reviewprovider.Pull{RepositoryID: 801, Number: n, State: "open", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1} +} + +func TestSchedulingCooldownPauseKeepsOriginalTimerAndCollectionContinues(t *testing.T) { + f, a, in, now := queuedCooldown(t) + scope := f.scope(t, attemptProject, f.writer, false) + pause := true + zero := int64(0) + if _, err := f.e.ConfigurePullScheduling(t.Context(), scope, "pr-pause", 2, PullSchedulingRequest{ExpectedRevision: &zero, Paused: &pause}); err != nil { + t.Fatal(err) + } + original := snapshotTable(t, f, "review_operation_waits") + snapshotTable(t, f, "review_hosted_preflight") + snapshotTable(t, f, "review_hosted_allowance_queries") + snapshotTable(t, f, "review_hosted_observations") + *now = in.Observation.RetryNotBefore + pending, err := f.e.pending(t.Context()) + if err != nil || len(pending) != 0 { + t.Fatal(pending, err) + } + next, err := f.e.StartAttempt(t.Context(), attemptProject, a.OperationID) + if err != nil || next.ID != "" { + t.Fatal(next, err) + } + pause = false + one := int64(1) + if _, err = f.e.ConfigurePullScheduling(t.Context(), scope, "pr-resume", 2, PullSchedulingRequest{ExpectedRevision: &one, Paused: &pause}); err != nil { + t.Fatal(err) + } + if original != snapshotTable(t, f, "review_operation_waits")+snapshotTable(t, f, "review_hosted_preflight")+snapshotTable(t, f, "review_hosted_allowance_queries")+snapshotTable(t, f, "review_hosted_observations") { + t.Fatal("PR pause rewrote original cooldown") + } + next, err = f.e.StartAttempt(t.Context(), attemptProject, a.OperationID) + if err != nil || next.ID == "" || next.OperationID != a.OperationID || next.ID == a.ID { + t.Fatal(next, err) + } + // A pause after issuance never prevents retaining/settling the original result. + g, active, capture := hostedPublicationFixture(t, true) + if _, err = g.e.ConfigurePullScheduling(t.Context(), g.scope(t, attemptProject, g.writer, false), "pause-issued", 2, PullSchedulingRequest{ExpectedRevision: &zero, Paused: func() *bool { v := true; return &v }()}); err != nil { + t.Fatal(err) + } + retained, err := g.e.RecordReviewEvidence(t.Context(), attemptProject, active.ID, capture) + if err != nil || retained.ID == "" { + t.Fatal(retained, err) + } + if _, err = g.e.Advance(t.Context(), attemptProject, active.ID, active.Revision, "completed", "captured_original_result", active.ExternalID); err != nil { + t.Fatal(err) + } + if count := attemptCount(t, g.store, `SELECT count(*) FROM review_execution_evidence`); count != 1 { + t.Fatal(count) + } +} +func TestSchedulingFinalActionPauseRaceAndAuthorizerRecheck(t *testing.T) { + f, a, _ := hostedActionFixture(t) + if err := f.e.VerifyAction(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal("fixture was not dispatchable", err) + } + zero := int64(0) + paused := true + _, err := f.e.ConfigurePullScheduling(t.Context(), f.scope(t, attemptProject, f.writer, false), "pause-final-race", 2, PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused}) + if err != nil { + t.Fatal(err) + } + before := attemptState(t, f, a) + err = f.e.VerifyAction(t.Context(), attemptProject, a.ID, a.Revision) + attemptCode(t, err, "pull_scheduling_paused") + if attemptState(t, f, a) != before { + t.Fatal("final guard changed journal") + } + g := schedulingFixture(t) + schedulingEnable(t, g, 0, true) + schedulingGenerate(t, g, true) + selectionNext(t, g, &refreshTestReader{}) + r := schedulingLatest(t, g) + claimed := g.start(t, attemptProject, Receipt{ID: r.OperationID}) + schedulingEnable(t, g, 1, false) + _, err = g.e.ExecutionContext(t.Context(), attemptProject, r.OperationID) + attemptCode(t, err, "automation_authorization_changed") + // The exact automatic child is still retained, not cancelled/replaced. + current, err := g.e.ReadOperation(t.Context(), selectionScope(t, g, attemptProject, g.writer, "read"), r.OperationID) + if err != nil || current.AttemptID != claimed.ID || current.State != "preparing" { + t.Fatal(current, err) + } +} +func TestSchedulingProjectionRefreshDoesNotRegenerateAndValidatorPreservesRevocation(t *testing.T) { + f := frontFixture(t) + one := int64(1) + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "projected-one-pr", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}}); err != nil { + t.Fatal(err) + } + admissionSQL(t, f, `UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'`) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + _, err := f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-projected", r.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + schedulingGenerate(t, f, false) + // Refreshing a source timestamp, or another projection revision, is not a + // deliberate new review intent. Source facts remain the same exact values. + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + c, _, err := readConfiguration(ctx, tx, attemptProject) + if err != nil { + return err + } + before, _, err := automaticPlanningBasis(ctx, tx, attemptProject, c, "") + if err != nil { + return err + } + frame, found, err := readFrontFrame(ctx, tx, attemptProject, "hosted") + if err != nil { + return err + } + if !found { + t.Fatal("missing genuine source frame") + } + at := stamp() + for i := range frame.prefix { + frame.prefix[i].ObservedAt = at + } + body, err := json.Marshal(frame.prefix) + if err != nil { + return err + } + if _, err = tx.ExecContext(ctx, `UPDATE review_front_frames SET checked_at=?,source_observed_at=?,prefix_json=? WHERE project_id=?`, at, at, string(body), attemptProject); err != nil { + return err + } + after, _, err := automaticPlanningBasis(ctx, tx, attemptProject, c, "") + if err != nil { + return err + } + if before != after { + t.Fatal("timestamp changed semantic basis") + } + return ValidateSchedulingSnapshot(ctx, tx) + }) + if err != nil { + t.Fatal(err) + } + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) + if err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return ValidateSchedulingSnapshot(ctx, tx) }); err != nil { + t.Fatal("valid revoked history refused", err) + } + schedulingGenerate(t, f, false) +} +func TestSchedulingAutomaticIndependentProgressAcrossRetainedEvidence(t *testing.T) { + for _, dependent := range []bool{false, true} { + t.Run(map[bool]string{false: "independent", true: "dependent"}[dependent], func(t *testing.T) { + f, a, capture := hostedPublicationFixture(t, false) + admissionSQL(t, f, `INSERT INTO workers VALUES(?,'selection-worker','Selector')`, attemptProject) + admissionSQL(t, f, `UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'`) + if _, err := f.e.RecordReviewEvidence(t.Context(), attemptProject, a.ID, capture); err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "completed", "captured_native_result", a.ExternalID); err != nil { + t.Fatal(err) + } + if dependent { + one := int64(1) + _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "stacked", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "stacked", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}}) + if err != nil { + t.Fatal(err) + } + } + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + reader := &refreshTestReader{} + if dependent { + reader.pull = func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { + p := schedulingPull(n) + p.HeadRef = "branch-two" + if n == 4 { + p.BaseRef = "branch-two" + p.BaseSHA = strings.Repeat("a", 40) + } + return p, nil + } + reader.parents = map[string]reviewprovider.Pull{"branch-two": func() reviewprovider.Pull { p := schedulingPull(2); p.HeadRef = "branch-two"; return p }()} + } + selectionNext(t, f, reader) + r := schedulingLatest(t, f) + if dependent { + if r.State != "held" || r.OperationID != "" { + t.Fatal("dependency bypassed", r) + } + } else { + if r.State != "selected" { + t.Fatal(r) + } + op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), r.OperationID) + if err != nil || op.PullNumber != 4 { + t.Fatal(op, err) + } + } + schedulingGenerate(t, f, false) + }) + } +} +func TestSchedulingSnapshotRejectsForgedAttribution(t *testing.T) { + for _, sqlText := range []string{ + `UPDATE review_scheduling SET credential_id='missing-credential'`, + `UPDATE review_scheduling SET worker_id='foreign-worker'`, + `UPDATE review_automatic_selections SET credential_id='exec-reader-cred'`, + `UPDATE review_automatic_selections SET actor_id='exec-reader-principal'`, + `UPDATE review_automatic_selections SET pull_number=4`, + `UPDATE review_automatic_selections SET settled_basis_sha256='not-a-digest'`, + } { + t.Run(sqlText, func(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + admissionSQL(t, f, sqlText) + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { return ValidateSchedulingSnapshot(ctx, tx) }) + attemptCode(t, err, "storage_unavailable") + }) + } +} +func TestSchedulingCancelledExactIntentLetsIndependentPeerProceed(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + first := schedulingLatest(t, f) + _, err := f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-first-only", first.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + second := schedulingLatest(t, f) + op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), second.OperationID) + if err != nil || op.PullNumber != 4 || second.ID == first.ID { + t.Fatal("independent peer did not progress", second, op, err) + } + old, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), first.OperationID) + if err != nil || old.State != "cancelled" { + t.Fatal("cancelled intent was replaced", old, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations WHERE pull_number=2`) != 1 { + t.Fatal("same intent recreated") + } +} +func TestSchedulingAutomaticUsesExistingWorkerLifecycle(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done, err := f.e.StartReviewRuns(ctx, map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err != nil { + t.Fatal(err) + } + joined := false + defer func() { + cancel() + if !joined { + select { + case err := <-done: + if err != nil { + t.Error(err) + } + case <-time.After(3 * time.Second): + t.Error("selection worker did not join") + } + } + }() + deadline := time.NewTimer(3 * time.Second) + defer deadline.Stop() + tick := time.NewTicker(10 * time.Millisecond) + defer tick.Stop() + for { + var selected int + if err = f.store.DB().QueryRow(`SELECT count(*) FROM review_selections WHERE state='selected' AND channel='hosted'`).Scan(&selected); err != nil { + t.Fatal(err) + } + if selected == 1 { + break + } + select { + case <-deadline.C: + t.Fatal("automatic coordinator never handed off to normal selection worker") + case <-tick.C: + } + } + cancel() + select { + case err = <-done: + joined = true + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("selection worker leaked") + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 0 { + t.Fatal("automatic selection created duplicate child or bypassed supervisor") + } +} +func TestSchedulingPauseBeforeAnyIntentBulkReadAndUnenrolledIsolation(t *testing.T) { + f := schedulingFixture(t) + schedulingPause(t, f, 4, 0, true) + schedulingPause(t, f, 99, 0, true) + schedulingPause(t, f, 2, 0, true) + scope := selectionScope(t, f, attemptProject, f.writer, "read") + view, err := f.e.ReadScheduling(t.Context(), scope) + if err != nil || len(view.PausedPulls) != 2 || view.PausedPulls[0].PullNumber != 2 || view.PausedPulls[1].PullNumber != 4 { + t.Fatal("bulk pauses lost queue order or leaked unenrolled PR", view, err) + } + p, err := f.e.ReadPullScheduling(t.Context(), scope, 99) + if err != nil || !p.Paused { + t.Fatal("pause before enrollment was lost", p, err) + } + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, false) + if attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("paused PRs created automatic intent") + } + schedulingPause(t, f, 4, 1, false) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + op, err := f.e.ReadOperation(t.Context(), scope, r.OperationID) + if err != nil || op.PullNumber != 4 { + t.Fatal(op, err) + } +} + +func TestSchedulingCancelledHostedIgnoresCleanCLIRound(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + _, err := f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-before-cli", r.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + a, id := roundCapture(t, f, 74, false) + roundFinalize(t, f, a, id, 74, false) + schedulingGenerate(t, f, false) + if attemptCount(t, f.store, `SELECT count(*) FROM review_operations WHERE channel='hosted'`) != 1 { + t.Fatal("clean CLI round recreated cancelled Hosted intent") + } +} +func schedulingCleanHosted(t *testing.T, f *attemptFixture, revision, n int64) { + t.Helper() + r := f.enqueue(t, attemptProject, core.NewID("hosted-clean"), "hosted", 2, revision) + a := f.start(t, attemptProject, r) + anchor := attemptAnchor(attemptProject, 2) + anchor.ParentSHA = anchor.BaseSHA + intent, err := reviewprovider.HostedTriggerBody(reviewprovider.HostedTriggerIntent{OperationID: a.OperationID, AttemptID: a.ID, HeadSHA: anchor.CandidateSHA}) + if err != nil { + t.Fatal(err) + } + a, err = f.e.Admit(t.Context(), attemptProject, a.ID, a.Revision, anchor, intent) + if err != nil { + t.Fatal(err) + } + external := strconv.FormatInt(100+n, 10) + a, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "active", "synthetic_original_post", external) + if err != nil { + t.Fatal(err) + } + h, _, parsed := hostedEvidenceMetadataFixture() + h.PublicationID = fmt.Sprintf("%08x-1111-1111-1111-111111111111", n) + h.ProviderAttemptID = fmt.Sprintf("%08x-2222-2222-2222-222222222222", n) + h.TriggerCommentID = 100 + n + h.ReviewIDs = []int64{200 + n} + h.ObservedBaseSHA = anchor.ParentSHA + h.Sources = []HostedFindingSource{} + parsed.Findings = []reviewprovider.ParsedFinding{} + parsed.ReportedFindings = 0 + digest := fmt.Sprintf("%064x", n+200) + in := ReviewEvidenceInput{CaptureID: "review_capture_" + digest[:32], CaptureSHA256: digest, CaptureBytes: 1024, StartedAt: stamp(), FinishedAt: stamp(), ExpectedAnchor: anchor, Review: parsed, Hosted: h} + captured, err := f.e.RecordReviewEvidence(t.Context(), attemptProject, a.ID, in) + if err != nil { + t.Fatal(err) + } + _, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "completed", "synthetic_original_complete", external) + if err != nil { + t.Fatal(err) + } + zero := int64(0) + _, err = f.e.FinalizeReviewEvidence(t.Context(), f.scope(t, attemptProject, f.writer, false), core.NewID("finalize"), captured.ID, FinalizeReviewRequest{ExpectedRevision: &zero}) + if err != nil { + t.Fatal(err) + } + roundCompleteHook(t, f, a.OperationID) +} +func schedulingStackReader() *refreshTestReader { + r := &refreshTestReader{} + r.pull = func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { + p := schedulingPull(n) + p.HeadRef = "branch-two" + if n == 4 { + p.HeadSHA = strings.Repeat("e", 40) + p.HeadRef = "branch-four" + p.BaseRef = "branch-two" + p.BaseSHA = strings.Repeat("a", 40) + } + return p, nil + } + r.parents = map[string]reviewprovider.Pull{"branch-two": func() reviewprovider.Pull { p := schedulingPull(2); p.HeadRef = "branch-two"; return p }()} + return r +} +func TestSchedulingDependentHeldChildReleasesAfterParentTapersAtSameHead(t *testing.T) { + f := schedulingFixture(t) + schedulingCleanHosted(t, f, 1, 81) + one := int64(1) + _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "stack-for-dependency", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "stacked", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}}) + if err != nil { + t.Fatal(err) + } + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + reader := schedulingStackReader() + selectionNext(t, f, reader) + first := schedulingLatest(t, f) + child, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), first.OperationID) + if err != nil || child.PullNumber != 4 { + t.Fatal("fixture did not select dependent child", first, child, err) + } + // Parent is deliberately reopened after selection but before final dispatch. + // Its comparison and B's binding stay unchanged throughout this scenario. + roundGrant(t, f, 2, "hosted", 0, 1, 2, "parent-needs-one-more") + retainHistoricalRoundTaper(t, f, 2, "hosted") + a := f.start(t, attemptProject, Receipt{ID: child.ID}) + anchor := attemptAnchor(attemptProject, 4) + anchor.CandidateSHA = strings.Repeat("e", 40) + anchor.BaseSHA = strings.Repeat("a", 40) + anchor.ParentSHA = anchor.BaseSHA + anchor.ParentPullNumber = 2 + anchor.BaseRef = "branch-two" + parent := SourcePlan{Repository: reviewprovider.Repository{ID: 801, FullName: "owner/repo", DefaultBranch: "main"}, Pull: schedulingPull(2), ParentSHA: strings.Repeat("b", 40), ObservedAt: stamp()} + parent.Pull.HeadRef = "branch-two" + err = f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + op, err := readOperation(ctx, tx, attemptProject, child.ID) + if err != nil { + return err + } + current, err := f.e.currentExecutionContext(ctx, tx, op) + if err != nil { + return err + } + return verifyPredecessors(ctx, tx, attemptProject, current, anchor, []SourcePlan{parent}) + }) + attemptCode(t, err, "review_held") + var failure *core.Error + if !errors.As(err, &failure) { + t.Fatal(err) + } + details, ok := failure.Details.(map[string]string) + if !ok || details["reason"] != "predecessor_unfinished" { + t.Fatal("not the genuine dependency hold", failure) + } + if _, err = f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "predecessor_unfinished", ""); err != nil { + t.Fatal(err) + } + schedulingCleanHosted(t, f, 2, 82) + control := roundRead(t, f, 2, "hosted") + if !control.Tapered || control.Used != 1 { + t.Fatal("parent did not actually taper", control) + } + schedulingGenerate(t, f, true) + selectionNext(t, f, reader) + next := schedulingLatest(t, f) + if next.State != "selected" || next.OperationID == child.ID { + t.Fatal("dependent child remained suppressed after genuine parent completion", next) + } + op, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), next.OperationID) + if err != nil || op.PullNumber != 4 || op.HeadSHA != child.HeadSHA || op.ConfigurationRevision != child.ConfigurationRevision { + t.Fatal(op, err) + } + old, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), child.ID) + if err != nil || old.State != "held" || old.Reason != "predecessor_unfinished" { + t.Fatal("old dependency hold was rewritten", old, err) + } + +} + +func TestSchedulingPrepareControlRaceFinalVerificationKeepsSupervisorHealthy(t *testing.T) { + for _, change := range []string{"pause", "disable", "withdraw"} { + t.Run(change, func(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + cli := f.enqueue(t, attemptProject, "independent-cli-after-control-race", "cli", 4, 1) + externalHosted := 0 + completedCLI := 0 + verified := false + driver := &controlledDriver{} + driver.prepare = func(ctx context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + anchor := attemptAnchor(o.ProjectID, o.PullNumber) + anchor.ParentSHA = anchor.BaseSHA + if o.Channel == "cli" { + return Preparation{Anchor: anchor}, nil + } + // This exact control mutation commits after the supervisor claimed and + // prepared the original operation, before it admits/dispatches that action. + switch change { + case "pause": + schedulingPause(t, f, 2, 0, true) + case "disable": + schedulingEnable(t, f, 1, false) + case "withdraw": + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + } + intent, err := reviewprovider.HostedTriggerBody(reviewprovider.HostedTriggerIntent{OperationID: o.ID, AttemptID: a.ID, HeadSHA: o.HeadSHA}) + return Preparation{Anchor: anchor, Intent: intent}, err + } + driver.dispatch = func(ctx context.Context, o Operation, a Attempt, _ func(context.Context, string) error) (Result, error) { + if o.Channel == "cli" { + completedCLI++ + return Result{State: "completed", Reason: "synthetic_independent_result"}, nil + } + err := f.e.VerifyAction(ctx, o.ProjectID, a.ID, a.Revision) + expected := "automation_authorization_changed" + if change == "pause" { + expected = "pull_scheduling_paused" + } + if err != nil { + attemptCode(t, err, expected) + verified = true + return Result{State: "failed", Reason: "admission_changed"}, nil + } + externalHosted++ + return Result{State: "failed", Reason: "synthetic_unexpected_external_action"}, nil + } + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal("control race stopped supervisor", err) + } + if !verified || externalHosted != 0 { + t.Fatal("final verification admitted external action", verified, externalHosted) + } + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal("independent CLI work could not continue", err) + } + scope := selectionScope(t, f, attemptProject, f.writer, "read") + hosted, err := f.e.ReadOperation(t.Context(), scope, r.OperationID) + if err != nil || hosted.State != "failed" || hosted.Reason != "admission_changed" { + t.Fatal(hosted, err) + } + other, err := f.e.ReadOperation(t.Context(), scope, cli.ID) + if err != nil || other.State != "completed" || completedCLI != 1 { + t.Fatal("sibling did not continue", other, completedCLI, err) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_round_completions`) != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("aborted dispatch invented evidence/credit or leaked reservation") + } + }) + } +} + +func frontFixture(t *testing.T) *attemptFixture { + t.Helper() + f := attemptProjectionFixture(t, true) + admissionSQL(t, f, `INSERT INTO workers(project_id,id,name) VALUES(?,'selection-worker','Selector')`, attemptProject) + return f +} +func frontMergedPull() reviews.PullInput { p := projectionPull(1); p.State = "merged"; return p } + +func TestSchedulingAutomaticWorkspaceBasisUsesTargetFirstCurrentReferences(t *testing.T) { + f := frontFixture(t) + for _, query := range []string{automaticCurrentRunsBasisQuery, automaticCurrentFindingsBasisQuery} { + if automaticBasisQuery(query, false) != query { + t.Fatal("ordinary query text changed") + } + rows, err := f.store.DB().QueryContext(t.Context(), "EXPLAIN QUERY PLAN "+automaticBasisQuery(query, true), attemptProject, 2) + if err != nil { + t.Fatal(err) + } + var plan []string + for rows.Next() { + var id, parent, unused int + var detail string + if err = rows.Scan(&id, &parent, &unused, &detail); err != nil { + t.Fatal(err) + } + plan = append(plan, detail) + } + err = rows.Err() + rows.Close() + if err != nil { + t.Fatal(err) + } + joined := strings.Join(plan, "\n") + if !strings.Contains(joined, "SEARCH c USING INDEX") || !strings.Contains(plan[0], "project_id=? AND pull_number=?") { + t.Fatal("basis starts from project-wide history instead of selected current PR", plan) + } + for _, detail := range plan { + if (strings.Contains(detail, "SEARCH v ") || strings.Contains(detail, "SEARCH f ")) && strings.HasSuffix(detail, "(project_id=?)") { + t.Fatal("basis walks unrelated historical versions", plan) + } + } + } +} + +func TestSchedulingAutomaticHistoryChurnPreservesFactsAndDedupe(t *testing.T) { + f := frontFixture(t) + one := int64(1) + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "one-target", Configuration{ExpectedRevision: &one, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}}); err != nil { + t.Fatal(err) + } + admissionSQL(t, f, `UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'`) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + selected := schedulingLatest(t, f) + if _, err := f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-original", selected.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}); err != nil { + t.Fatal(err) + } + basis := func() string { + t.Helper() + var sum string + err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + sum, err = automaticPullBasis(ctx, tx, attemptProject, 2) + return err + }) + if err != nil { + t.Fatal(err) + } + return sum + } + before := basis() + observe := func(target reviews.PullInput, unrelated reviews.PullInput, key string) { + t.Helper() + var revision int64 + if err := f.store.DB().QueryRow(`SELECT revision FROM review_workspace WHERE project_id=?`, attemptProject).Scan(&revision); err != nil { + t.Fatal(err) + } + request := reviews.ObservationRequest{ExpectedRevision: &revision, RepositoryID: 801, Source: "unrelated-history", ObservedAt: stamp(), Queue: []reviews.PullInput{frontMergedPull(), target, unrelated}} + response := f.request("POST", "/api/v1/projects/"+attemptProject+"/reviews/observations", f.admin, key, encoded(request)) + if response.Code != 201 { + t.Fatal("history observation", response.Code, response.Body.String()) + } + } + for n := 0; n < 8; n++ { + other := projectionPull(4) + other.Runs = []reviews.RunInput{{SourceRunID: fmt.Sprintf("unrelated-%d", n), Channel: "hosted", HeadSHA: other.HeadSHA, Reviewer: "Historical reviewer", Scope: "Retained comparison", Outcome: "completed", Attributable: true, Complete: true, StartedAt: "2026-01-01T00:00:00Z", FinishedAt: "2026-01-01T00:01:00Z", Found: 1, Findings: []reviews.Finding{{SourceFindingID: "original", Title: "Retained finding", Detail: "Historical source detail", Severity: "low", Disposition: "unadjudicated"}}}} + observe(projectionPull(2), other, fmt.Sprintf("history-%d", n)) + } + if attemptCount(t, f.store, `SELECT count(*) FROM review_run_versions WHERE project_id=?`, attemptProject) < 8 || attemptCount(t, f.store, `SELECT count(*) FROM review_finding_versions WHERE project_id=?`, attemptProject) < 8 { + t.Fatal("fixture did not retain run/finding history") + } + if after := basis(); after != before { + t.Fatal("unrelated historical versions changed selected source basis") + } + schedulingGenerate(t, f, false) + changed := projectionPull(2) + changed.HeadSHA = strings.Repeat("c", 40) + observe(changed, projectionPull(4), "changed-current-head") + if basis() == before { + t.Fatal("actual selected source change did not change basis") + } + schedulingGenerate(t, f, true) +} + +func TestAutomaticIdlePlanningDoesNotEnterWriter(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, idle := range []string{"paused", "pending", "cancelled", "held-source-not-due"} { + t.Run(channel+"/"+idle, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + on, zero := true, int64(0) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + if _, err := f.e.ConfigureScheduling(t.Context(), scope, "idle-enable", SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { + t.Fatal(err) + } + reader := &refreshTestReader{} + readers := map[string]TargetReader{"test-capability": reader} + generate := f.e.generateAutomaticHosted + if channel == "cli" { + generate = f.e.generateAutomaticCLI + } + if idle == "paused" { + schedulingPause(t, f, 2, 0, true) + } else { + if worked, err := generate(t.Context(), readers); err != nil || !worked { + t.Fatal(worked, err) + } + if idle == "cancelled" { + selectionNext(t, f, reader) + r := schedulingLatest(t, f) + if _, err := f.e.ControlOperation(t.Context(), scope, "cancel-idle", r.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}); err != nil { + t.Fatal(err) + } + } else if idle == "held-source-not-due" { + selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, context.DeadlineExceeded + }}) + } + } + beforeCalls := reader.calls.Load() + entered, release := make(chan struct{}), make(chan struct{}) + done := make(chan error, 1) + go func() { + done <- f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `UPDATE projects SET name='writer held' WHERE id=?`, attemptProject); err != nil { + return err + } + close(entered) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + }() + defer func() { + close(release) + if err := <-done; err != nil { + t.Error(err) + } + }() + select { + case <-entered: + case <-time.After(time.Second): + t.Fatal("writer not held") + } + ctx, cancel := context.WithTimeout(t.Context(), 150*time.Millisecond) + defer cancel() + worked, err := generate(ctx, readers) + if err != nil || worked || ctx.Err() != nil { + t.Fatal("idle scheduler waited for writer", worked, err, ctx.Err()) + } + if reader.calls.Load() != beforeCalls { + t.Fatal("local planning contacted provider") + } + }) + } + } +} + +func TestAutomaticWriterRechecksReadPlan(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, change := range []string{"unchanged", "restore", "revoked", "scheduling", "configuration", "policy", "pull-pause", "basis", "competing-selection"} { + t.Run(channel+"/"+change, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + on, zero := true, int64(0) + if _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "writer-enable", SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { + t.Fatal(err) + } + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}} + var candidate *automaticProjectPlan + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + candidate, err = f.e.planAutomaticProject(ctx, tx, attemptProject, channel, readers) + return err + }); err != nil || candidate == nil { + t.Fatal("candidate not nominated", candidate, err) + } + // Deterministic interleaving: commit a competing change after the exact + // read preflight, then run the same writer path used by the generator. + switch change { + case "restore": + admissionSQL(t, f, `INSERT INTO metadata VALUES('restore:provider_state','held')`) + case "revoked": + admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) + case "scheduling": + schedulingEnable(t, f, 1, true) + case "configuration": + f.configure(t, attemptProject, "test-capability", 1, false) + case "policy": + assessmentPolicy(t, f, 1, []string{"cli", "hosted"}, []string{channel}) + case "pull-pause": + schedulingPause(t, f, 2, 0, true) + case "basis": + admissionSQL(t, f, `INSERT INTO review_pull_scheduling VALUES(?,2,1,0,'','actor',?)`, attemptProject, stamp()) + case "competing-selection": + selectionEnqueue(t, f, "competing-explicit", channel, nil) + } + worked, err := f.e.acceptAutomaticProject(t.Context(), attemptProject, channel, readers, candidate) + if err != nil || worked != (change == "unchanged") { + t.Fatal("writer accepted stale or refused unchanged plan", worked, err) + } + want := 0 + if change == "unchanged" { + want = 1 + // The same nominated plan cannot admit a second selection. + if worked, err = f.e.acceptAutomaticProject(t.Context(), attemptProject, channel, readers, candidate); err != nil || worked { + t.Fatal("repeated plan created duplicate intent", worked, err) + } + } + if got := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections`); got != want { + t.Fatal("unexpected automatic attribution", got) + } + }) + } + } +} + +func TestAutomaticConcurrentProjectPlansAcceptOnce(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + t.Run(channel, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + on, zero := true, int64(0) + if _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "concurrent-enable", SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { + t.Fatal(err) + } + start := make(chan struct{}) + type result struct { + worked bool + err error + } + results := make(chan result, 2) + for range 2 { + go func() { + <-start + worked, err := f.e.generateAutomaticProject(t.Context(), attemptProject, channel, map[string]TargetReader{"test-capability": &refreshTestReader{}}) + results <- result{worked, err} + }() + } + close(start) + accepted := 0 + for range 2 { + r := <-results + if r.err != nil { + t.Fatal(r.err) + } + if r.worked { + accepted++ + } + } + if accepted != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_selections`) != 1 { + t.Fatal("concurrent preflights did not serialize one acceptance", accepted) + } + }) + } +} + +func TestSchedulingPreparationGuardRetainsOperation(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, change := range []string{"pause", "disable", "withdraw"} { + t.Run(channel+"/"+change, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + on := true + revision := int64(0) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + _, err := f.e.ConfigureScheduling(t.Context(), scope, "enable-both", SchedulingRequest{ExpectedRevision: &revision, AutomaticHosted: &on, AutomaticCLI: &on}) + if err != nil { + t.Fatal(err) + } + // Select the requested automatic channel through the normal scheduler. + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}} + if channel == "cli" { + _, err = f.e.generateAutomaticCLI(t.Context(), readers) + } else { + _, err = f.e.generateAutomaticHosted(t.Context(), readers) + } + if err != nil { + t.Fatal(err) + } + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + if r.OperationID == "" || r.Channel != channel { + t.Fatal(r) + } + deadline := "" + admissionSQL(t, f, `INSERT INTO review_operation_waits(operation_id,baseline_attempt_id,retry_not_before,paused) VALUES(?,NULL,?,0)`, r.OperationID, deadline) + before, err := f.e.ReadOperation(t.Context(), scope, r.OperationID) + if err != nil { + t.Fatal(err) + } + expected := "automation_authorization_changed" + if change == "pause" { + expected = "pull_scheduling_paused" + } + var original Attempt + driver := &controlledDriver{prepare: func(ctx context.Context, o Operation, _ Configuration, a Attempt) (Preparation, error) { + original = a + switch change { + case "pause": + schedulingPause(t, f, 2, 0, true) + case "disable": + off, rev := false, int64(1) + _, err := f.e.ConfigureScheduling(ctx, scope, "disable-both", SchedulingRequest{ExpectedRevision: &rev, AutomaticHosted: &off, AutomaticCLI: &off}) + if err != nil { + t.Fatal(err) + } + case "withdraw": + admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + } + _, err := f.e.ExecutionContext(ctx, o.ProjectID, o.ID) + attemptCode(t, err, expected) + return Preparation{}, err + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal(err) + } + after, err := f.e.ReadOperation(t.Context(), scope, r.OperationID) + if err != nil { + t.Fatal(err) + } + if after.State != "queued" || after.Reason != expected || after.AttemptID != "" { + t.Fatalf("guard lost retained request: %+v", after) + } + if after.ID != before.ID || after.ActorID != before.ActorID || after.WorkerID != before.WorkerID || after.HeadSHA != before.HeadSHA || after.ConfigurationRevision != before.ConfigurationRevision || !reflect.DeepEqual(after.Wait, before.Wait) { + t.Fatal("changed original binding or wait", before, after) + } + if driver.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("dispatched or leaked reservation") + } + var state, reason string + if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_execution_transitions WHERE attempt_id=? AND revision=2`, original.ID).Scan(&state, &reason); err != nil || state != "held" || reason != expected { + t.Fatal(state, reason, err) + } + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil || driver.prepares.Load() != 1 { + t.Fatal("blocked operation prepared again", err) + } + if change == "pause" { + schedulingPause(t, f, 2, 1, false) + retry, err := f.e.StartAttempt(t.Context(), attemptProject, after.ID) + if err != nil || retry.ID == "" || retry.ID == original.ID || retry.OperationID != before.ID { + t.Fatal("same operation could not resume", retry, err) + } + } + }) + } + } +} + +func TestSchedulingQueuedPauseDiagnosticPrecedence(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, wait := range []string{"scheduler", "queue", "draft"} { + t.Run(channel+"/"+wait, func(t *testing.T) { + f := schedulingFixture(t) + pull := int64(2) + if wait == "queue" { + f.enqueue(t, attemptProject, "earlier", channel, 2, 1) + pull = 4 + } + r := f.enqueue(t, attemptProject, "queued-pause", channel, pull, 1) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + deadline := "" + + admissionSQL(t, f, `INSERT INTO review_operation_waits(operation_id,baseline_attempt_id,retry_not_before,paused) VALUES(?,NULL,?,0)`, r.ID, deadline) + if wait == "draft" { + admissionSQL(t, f, `UPDATE review_operations SET reason=? WHERE id=?`, cliDraftWait, r.ID) + } + schedulingPause(t, f, pull, 0, true) + check := func(want string) { + t.Helper() + if got := f.e.queuedDiagnostic(t.Context(), scope, r.ID, r.Revision); got != want { + t.Fatalf("diagnostic=%q want=%q", got, want) + } + } + check("pull_scheduling_paused") + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=json_set(body_json,'$.paused',json('true')) WHERE project_id=?`, attemptProject) + check("project_paused") + admissionSQL(t, f, `UPDATE review_operation_waits SET paused=1 WHERE operation_id=?`, r.ID) + check("operation_paused") + }) + } + } +} + +func TestSchedulingPausePreservesRetainedCooldown(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + var f *attemptFixture + var a Attempt + var now *time.Time + if channel == "cli" { + f, a, _, now = cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + } else { + f, a, _, now = queuedCooldown(t) + } + scope := f.scope(t, attemptProject, f.writer, false) + pause := func(revision int64, paused bool) { + _, err := f.e.ConfigurePullScheduling(t.Context(), scope, "timer-pause-"+time.Now().Format("150405.000000000"), 2, PullSchedulingRequest{ExpectedRevision: &revision, Paused: &paused}) + if err != nil { + t.Fatal(err) + } + } + before := cliWaitRead(t, f, a.OperationID) + pause(0, true) + if got := f.e.queuedDiagnostic(t.Context(), scope, before.ID, before.Revision); got != "pull_scheduling_paused" { + t.Fatal("quota/cooldown hid PR pause", got) + } + pause(1, false) + *now = cliWaitDue(t, before).Add(time.Second) + driver := &controlledDriver{prepare: func(ctx context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + pause(2, true) + _, err := f.e.ExecutionContext(ctx, o.ProjectID, o.ID) + return Preparation{}, err + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil { + t.Fatal(err) + } + after := cliWaitRead(t, f, a.OperationID) + if driver.prepares.Load() != 1 || driver.calls.Load() != 0 || after.State != "queued" || after.Reason != "pull_scheduling_paused" || !reflect.DeepEqual(after.Wait, before.Wait) { + t.Fatal("lost original cooldown", before, after) + } + assertCLIWaitSnapshot(t, f) + if attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("leaked reservation") + } + }) + } +} + +func TestSchedulingPreparationGuardCannotRequeueAdmittedAttempt(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed"} { + t.Run(channel+"/"+reason, func(t *testing.T) { + f := supervisorFixture(t) + r := f.enqueue(t, attemptProject, "admitted-guard", channel, 2, 1) + a := f.start(t, attemptProject, r) + intent := "" + if channel == "hosted" { + intent = "synthetic-trigger" + } + admitted, err := f.e.Admit(t.Context(), attemptProject, a.ID, a.Revision, attemptAnchor(attemptProject, 2), intent) + if err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, admitted.Revision, "held", reason, ""); err == nil { + t.Fatal("admitted attempt accepted a preparation hold") + } + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, admitted.Revision, "failed", reason, ""); err != nil { + t.Fatal(err) + } + after := cliWaitRead(t, f, r.ID) + if after.State != "failed" || after.AttemptID != a.ID { + t.Fatal("admitted action silently requeued", after) + } + }) + } + } +} + +func TestSchedulingDetachedGuardHistoryRejectsCorruption(t *testing.T) { + for _, corrupt := range []string{"anchor", "intent", "external", "state", "revision", "reason"} { + t.Run(corrupt, func(t *testing.T) { + f := schedulingFixture(t) + r := f.enqueue(t, attemptProject, "detached-guard", "hosted", 2, 1) + a := f.start(t, attemptProject, r) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "pull_scheduling_paused", ""); err != nil { + t.Fatal(err) + } + assertCLIWaitSnapshot(t, f) + o := cliWaitRead(t, f, r.ID) + current, err := readAttempt(t.Context(), f.store.DB(), attemptProject, a.ID) + if err != nil { + t.Fatal(err) + } + switch corrupt { + case "anchor": + anchor := attemptAnchor(attemptProject, 2) + current.Anchor = &anchor + case "intent": + current.Intent = "possible-post" + case "external": + current.ExternalID = "trigger" + case "state": + current.State = "active" + case "revision": + current.Revision = 1 + case "reason": + admissionSQL(t, f, `UPDATE review_execution_transitions SET reason='preparation_failed' WHERE attempt_id=? AND revision=2`, a.ID) + } + _, recognized, err := historicalUnusedPreparationOperation(t.Context(), f.store.DB(), o, current, true) + if err == nil && recognized { + t.Fatal("accepted corrupt detached attempt", corrupt) + } + }) + } +} + +func TestSchedulingDetachedGuardProjectsOriginalAttempt(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed"} { + t.Run(reason, func(t *testing.T) { + f := attemptProjectionFixture(t, true) + r := f.enqueue(t, attemptProject, "guard-projection", "hosted", 2, 1) + a := f.start(t, attemptProject, r) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, ""); err != nil { + t.Fatal(err) + } + _, projected := projectedAttempt(t, f, a) + if projected.State != "held" || projected.Reason != reason { + t.Fatal(projected) + } + assertCLIWaitSnapshot(t, f) + o := cliWaitRead(t, f, r.ID) + if _, err := f.e.ControlOperation(t.Context(), f.scope(t, attemptProject, f.writer, false), "cancel-guard", o.ID, OperationControl{ExpectedRevision: o.Revision, Action: "cancel"}); err != nil { + t.Fatal(err) + } + assertCLIWaitSnapshot(t, f) + if _, err := f.e.PublishAttempt(t.Context(), attemptProject, a.ID, nil); err != nil { + t.Fatal("historical projection after cancellation", err) + } + }) + } +} + +func validateSchedulingSnapshotForTest(t *testing.T, f *attemptFixture) error { + t.Helper() + return f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return ValidateSchedulingSnapshot(ctx, tx) + }) +} + +func TestValidateSchedulingSnapshotAcceptsSupportedVersions(t *testing.T) { + for _, tc := range []struct { + name string + version string + legacyPhysical bool + }{ + {name: "legacy-v1", version: "1", legacyPhysical: true}, + {name: "current-v2", version: "2"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + if tc.legacyPhysical { + admissionSQL(t, f, `ALTER TABLE review_scheduling DROP COLUMN automatic_cli`) + } + admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_scheduling'`, tc.version) + if err := validateSchedulingSnapshotForTest(t, f); err != nil { + t.Fatalf("valid schema version %s rejected: %v", tc.version, err) + } + }) + } +} + +func TestValidateSchedulingSnapshotRejectsMalformedAndFutureVersions(t *testing.T) { + for _, tc := range []struct { + name string + version string + }{ + {name: "malformed", version: "not-a-version"}, + {name: "future", version: "3"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := schedulingFixture(t) + admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_scheduling'`, tc.version) + attemptCode(t, validateSchedulingSnapshotForTest(t, f), "storage_unavailable") + }) + } +} + +func TestValidateSchedulingSnapshotRequiresPresentDomainMetadata(t *testing.T) { + f := schedulingFixture(t) + admissionSQL(t, f, `DELETE FROM metadata WHERE key='schema:review_scheduling'`) + if err := validateSchedulingSnapshotForTest(t, f); !errors.Is(err, sql.ErrNoRows) { + t.Fatalf("missing optional domain metadata should not be mistaken for a schema version: %v", err) + } +} diff --git a/internal/reviewexec/schema.go b/internal/reviewexec/schema.go index f820d7361..1545ce31e 100644 --- a/internal/reviewexec/schema.go +++ b/internal/reviewexec/schema.go @@ -91,7 +91,13 @@ func EnsureSchema(ctx context.Context, store *core.Store) error { if err := ensureRoutePolicySchema(ctx, store); err != nil { return err } - return EnsureSelectionSchema(ctx, store) + if err := EnsureSelectionSchema(ctx, store); err != nil { + return err + } + if err := EnsureFrontSchema(ctx, store); err != nil { + return err + } + return EnsureSchedulingSchema(ctx, store) } // Execution migration nine rebuilds attempts independently of the comparison diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index ed4b22cc0..fc9a66762 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -156,7 +156,7 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) ([]Oper JOIN review_execution_config c ON c.project_id=o.project_id AND c.revision=o.configuration_revision JOIN projects p ON p.id=o.project_id LEFT JOIN installed i ON i.id=CASE WHEN json_valid(c.body_json) THEN json_extract(c.body_json,'$.capability_id') END AND i.fingerprint=o.capability_fingerprint - WHERE o.state='queued'` + draftFilter + ` + WHERE o.state='queued'` + draftFilter + ` AND NOT EXISTS (SELECT 1 FROM review_pull_scheduling s WHERE s.project_id=o.project_id AND s.pull_number=o.pull_number AND s.paused=1) AND NOT EXISTS (SELECT 1 FROM review_operation_waits w WHERE w.operation_id=o.id AND (w.paused=1 OR (w.retry_not_before<>'' AND julianday(w.retry_not_before)>julianday(?)))) AND NOT EXISTS (SELECT 1 FROM review_execution_config latest WHERE latest.project_id=o.project_id AND latest.revision=(SELECT MAX(revision) FROM review_execution_config WHERE project_id=o.project_id) AND json_valid(latest.body_json) AND json_extract(latest.body_json,'$.paused')=1) AND NOT EXISTS (SELECT 1 FROM review_execution_reservations r WHERE r.provider=i.provider AND r.account=i.account AND r.action_class=o.channel AND (o.channel='cli' OR r.repository_id=p.github_repository_id)) @@ -194,7 +194,7 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) ([]Oper for _, i := range ids { o, err := readOperation(ctx, tx, i.project, i.operation) if err != nil { - if e.skipUnavailableWait(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableWait(ctx, o, err) { continue } return nil, err @@ -204,6 +204,9 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) ([]Oper if !ok { c, revision, err := readConfiguration(ctx, tx, o.ProjectID) if err != nil { + if automaticProjectRefused(err) { + continue + } return nil, err } configuration = configurationSnapshot{c, revision} @@ -212,7 +215,7 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) ([]Oper c, revision := configuration.configuration, configuration.revision earlier, err := e.earlierQueuedReviewIntentInSnapshot(ctx, tx, o, c, revision, emptyPredecessors) if err != nil { - if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { continue } return nil, err @@ -254,7 +257,7 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) ([]Oper 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 { @@ -355,7 +358,7 @@ func (e *Engine) processNextForWorker(ctx context.Context, drivers map[string]Dr if ctx.Err() != nil { return nil } - if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { continue } var refusal *core.Error @@ -376,7 +379,7 @@ func (e *Engine) processNextForWorker(ctx context.Context, drivers map[string]Dr if ctx.Err() != nil { return nil } - if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { continue } var failure *core.Error @@ -439,6 +442,11 @@ func (e *Engine) processNextForWorker(ctx context.Context, drivers map[string]Dr return e.finishPreparation(a, "cancelled", "supervisor_stopping") } var refusal *core.Error + if errors.As(err, &refusal) && (refusal.Code == "pull_scheduling_paused" || refusal.Code == "automation_authorization_changed") { + // Admit recorded no intent. Release only this unused attempt and + // retain the queued operation's original identity and wait state. + return e.finishPreparation(a, "held", refusal.Code) + } if errors.As(err, &refusal) && refusal.Code == "review_held" { reason := preparationReason(err) if reason == "source_obligations_pending" || reason == "repository_changed" { diff --git a/internal/reviewexec/types.go b/internal/reviewexec/types.go index 5afc2cb8d..37d486704 100644 --- a/internal/reviewexec/types.go +++ b/internal/reviewexec/types.go @@ -112,6 +112,10 @@ type Attempt struct { } type Engine struct { + automaticCursor string + automaticCLICursor string + automaticMu sync.Mutex + automaticNext time.Time runSourceBudget time.Duration schedulingNow func() time.Time configurationFailureMu sync.Mutex diff --git a/tools/packagedsmoke/project_management_test.go b/tools/packagedsmoke/project_management_test.go index ccbc38ea7..a7b1cda40 100644 --- a/tools/packagedsmoke/project_management_test.go +++ b/tools/packagedsmoke/project_management_test.go @@ -113,6 +113,18 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { var owner client.ProjectCredentialReceipt decode(t, cli(adminProfile, "admin", "credentials", "grant", "--credential-file", managerFile, "--permission", "manage", "--key", "grant-manager"), &owner) managerProfile := profile("manager", managerFile) + // Scheduling configuration is independent of execution configuration and keeps + // exact control identities across native CLI/MCP and restart. + var scheduling client.ReviewScheduling + decode(t, cli(managerProfile, "manager", "reviews", "scheduling"), &scheduling) + if scheduling.Revision != 0 || scheduling.AutomaticHosted || scheduling.AutomaticCLI { + t.Fatal("new scheduling is not off", scheduling) + } + configured := cli(managerProfile, "manager", "reviews", "scheduling", "configure", "--automatic-hosted", "false", "--automatic-cli", "false", "--expect-revision", "0", "--key", "scheduling-off") + if !bytes.Equal(configured, cli(managerProfile, "manager", "reviews", "scheduling", "configure", "--automatic-hosted", "false", "--automatic-cli", "false", "--expect-revision", "0", "--key", "scheduling-off")) { + t.Fatal("scheduling exact replay changed") + } + var grant client.ProjectCredentialReceipt decode(t, cli(managerProfile, "manager", "credentials", "grant", "--credential-file", readerFile, "--permission", "read", "--key", "grant-reader"), &grant) permissionFile := filepath.Join(private, "permissions.json") @@ -155,6 +167,13 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { t.Fatal("missing MCP text") return nil } + + call("review_pull_scheduling_update", map[string]any{"pull_number": 42, "paused": true, "reason": "Synthetic scheduling hold", "expected_revision": 0, "idempotency_key": "scheduling-pause"}) + var paused client.ReviewPullScheduling + decode(t, call("review_pull_scheduling_read", map[string]any{"pull_number": 42}), &paused) + if !paused.Paused || paused.Revision != 1 { + t.Fatal("MCP pause not retained", paused) + } call("inbox_ack", map[string]any{"message_id": message.ID, "worker_id": target.ID, "idempotency_key": "peer-ack"}) var retired client.WorkerRetirementReceipt decode(t, call("worker_retire", map[string]any{"worker_id": target.ID, "idempotency_key": "retire"}), &retired) @@ -178,6 +197,24 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { daemon.stop(t) daemon = startDaemon(t, ctx, filepath.Join(bin, "fcd"), data, env) managerProfile = profile("manager-restarted", managerFile) + decode(t, cli(managerProfile, "manager-restarted", "reviews", "scheduling", "read", "--pr", "42"), &paused) + if !paused.Paused || paused.Revision != 1 || paused.Reason != "Synthetic scheduling hold" { + t.Fatal("restart changed paused scheduling control", paused) + } + cli(managerProfile, "manager-restarted", "reviews", "scheduling", "resume", "--pr", "42", "--expect-revision", "1", "--key", "scheduling-resume") + daemon.stop(t) + daemon = startDaemon(t, ctx, filepath.Join(bin, "fcd"), data, env) + managerProfile = profile("manager-restarted", managerFile) + var resumed client.ReviewPullScheduling + decode(t, cli(managerProfile, "manager-restarted", "reviews", "scheduling", "read", "--pr", "42"), &resumed) + if resumed.Paused || resumed.Revision != 2 || resumed.Reason != "" { + t.Fatal("restart changed scheduling control", resumed) + } + decode(t, cli(managerProfile, "manager-restarted", "reviews", "scheduling"), &scheduling) + if scheduling.Revision != 1 || scheduling.AutomaticHosted || scheduling.AutomaticCLI { + t.Fatal("restart changed default-off control", scheduling) + } + var replay client.WorkerRetirementReceipt decode(t, cli(managerProfile, "manager-restarted", "workers", "retire", target.ID, "--key", "retire"), &replay) if replay != retired { diff --git a/tools/packagedsmoke/run_selection_test.go b/tools/packagedsmoke/run_selection_test.go index 0d2b37ea4..8315de58f 100644 --- a/tools/packagedsmoke/run_selection_test.go +++ b/tools/packagedsmoke/run_selection_test.go @@ -11,6 +11,7 @@ import ( "crypto/tls" "crypto/x509" "crypto/x509/pkix" + "database/sql" "encoding/hex" "encoding/json" "encoding/pem" @@ -335,8 +336,15 @@ func TestPackagedRunSelectionSmoke(t *testing.T) { daemon.stop(t) firstObserver.awaitCancelled(t, ctx) beforeRestart := readUpgradeState(t, ctx, data) + assertRunSelectionFrontFrame(t, ctx, data, project) + if initial.counts["review_front_frames"] != 0 || beforeRestart.counts["review_front_frames"] != 1 { + t.Fatal("selection did not retain exactly its one channel source frame") + } seedRunSelectionConfiguration(t, ctx, data, catalogPath, project, worker, strings.TrimSpace(string(admin)), 1, []int64{3, 2}, false) afterConfig := readUpgradeState(t, ctx, data) + if afterConfig.tables["review_front_frames"] != beforeRestart.tables["review_front_frames"] { + t.Fatal("configuration changed retained source frame") + } secondObserver := provider.holdNextObserver(t) restarted := startSelectionDaemon(t, ctx, binaries["fcd"], data, env, "--review-catalog", catalogPath) secondObserver.awaitStarted(t, ctx) @@ -366,7 +374,7 @@ func TestPackagedRunSelectionSmoke(t *testing.T) { if !reflect.DeepEqual(final, afterConfig) { t.Fatal("restart/recovery/read altered retained tables") } - changed := map[string]bool{"review_selections": true, "review_operations": true, "review_execution_attempts": true, "review_execution_transitions": true, "review_execution_reservations": true, "review_round_operation_bindings": true, "events": true, "receipts": true, "sqlite_sequence": true} + changed := map[string]bool{"review_selections": true, "review_operations": true, "review_execution_attempts": true, "review_execution_transitions": true, "review_execution_reservations": true, "review_round_operation_bindings": true, "review_front_frames": true, "events": true, "receipts": true, "sqlite_sequence": true} for _, name := range []string{"review_snapshots", "review_workspace", "review_current_pulls", "review_pull_versions", "review_pull_memberships", "review_current_attempts", "review_attempt_versions", "review_attempt_memberships", "review_current_totals", "review_current_attempt_order"} { changed[name] = true } @@ -399,6 +407,46 @@ func TestPackagedRunSelectionSmoke(t *testing.T) { t.Logf("packaged one-call selection passed: total=%s enqueue=%s cli_calls=%d mcp_calls=%d application_http=%d loopback_github_gets=%d selection_source_gets=%d lookahead_gets=%d held_observer_gets=4 git_stub_calls=1 cli_review_calls=0 native_operations=1 owned_processes=0", time.Since(started).Round(time.Millisecond), enqueueDuration.Round(time.Millisecond), calls, mcpCalls, appHTTP.Load(), 11+lookaheadGETs, 7+lookaheadGETs, lookaheadGETs) } +// Explicit selection retains only its bounded acquired prefix for provider-free +// front evaluation. The last selection expected PR2, so it must replace the +// previous full frame with PR2 alone, never invent PR3 or claim a complete scan. +func assertRunSelectionFrontFrame(t *testing.T, ctx context.Context, data, project string) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, stepTimeout) + defer cancel() + u := url.URL{Scheme: "file", Path: filepath.ToSlash(filepath.Join(data, "firecontroller.sqlite")), RawQuery: "mode=ro"} + db, err := sql.Open("sqlite", u.String()) + if err != nil { + t.Fatal("selection source frame snapshot unavailable") + } + defer db.Close() + db.SetMaxOpenConns(1) + if err = reviewexec.ValidateFrontSnapshot(ctx, db); err != nil { + t.Fatal("selection retained an invalid source frame") + } + var retainedProject, channel, checked, observed, reason, body string + var repository, configuration, complete int64 + if err = db.QueryRowContext(ctx, `SELECT project_id,channel,repository_id,configuration_revision,checked_at,source_observed_at,complete,source_reason,prefix_json FROM review_front_frames`).Scan(&retainedProject, &channel, &repository, &configuration, &checked, &observed, &complete, &reason, &body); err != nil { + t.Fatal("selection source frame unreadable") + } + if retainedProject != project || channel != "cli" || repository != 991 || configuration != 1 || complete != 0 || reason != "" { + t.Fatal("selection source frame changed scope or completeness") + } + checkedAt, checkedErr := time.Parse(time.RFC3339Nano, checked) + observedAt, observedErr := time.Parse(time.RFC3339Nano, observed) + if checkedErr != nil || observedErr != nil || checkedAt.Before(observedAt) { + t.Fatal("selection source frame has invalid source timing") + } + var prefix []map[string]any + if err = json.Unmarshal([]byte(body), &prefix); err != nil { + t.Fatal("selection source frame prefix invalid") + } + want := []map[string]any{{"number": float64(2), "visible_at_acquisition": true, "state": "open", "merged": false, "head_sha": strings.Repeat("a", 40), "base_sha": strings.Repeat("b", 40), "base_ref": "main", "parent_pull_number": float64(0), "parent_sha": strings.Repeat("b", 40), "observed_at": observed}} + if !reflect.DeepEqual(prefix, want) { + t.Fatal("selection source frame differs from its bounded acquired prefix") + } +} + func runSelectionShellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" } From e04e00cf5d9e9681886b883cd6d086dd79b3ba72 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 13 Nov 2026 10:05:02 +1300 Subject: [PATCH 02/41] Validate retained scheduling continuity and clarify held review guidance --- internal/cli/review_scheduling_help.go | 2 +- internal/client/review_agent_output.go | 3 +++ internal/mcpadapter/review_scheduling_test.go | 2 +- internal/reviewexec/queued_diagnostic.go | 1 + .../reviewexec/scheduling_authorization_continuity.go | 11 +++++++---- .../scheduling_authorization_continuity_test.go | 6 +++++- internal/reviewexec/scheduling_source_retry_test.go | 9 ++++++++- tools/packagedsmoke/project_management_test.go | 8 ++++---- 8 files changed, 30 insertions(+), 12 deletions(-) diff --git a/internal/cli/review_scheduling_help.go b/internal/cli/review_scheduling_help.go index 15042837d..4bc9c00a8 100644 --- a/internal/cli/review_scheduling_help.go +++ b/internal/cli/review_scheduling_help.go @@ -5,7 +5,7 @@ func operationHelp(operation string) (operationHelpResponse, bool) { out := operationHelpResponse{Required: []string{}, Optional: []string{}} switch operation { case "reviews scheduling": - out.Usage = " reviews scheduling [--pr N] | configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY | pause|resume --pr N --expect-revision N --key KEY [--reason TEXT]" + out.Usage = " reviews scheduling [--pr N] | configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY | pause --pr N --expect-revision N --key KEY [--reason TEXT] | resume --pr N --expect-revision N --key KEY" out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)", "configure --automatic-hosted true|false (project manager; authorizes future automatic Hosted requests)", "pause|resume --pr N (writer; holds new/undispatched reviews without changing rounds)", "--reason TEXT (optional with pause, at most 256 UTF-8 bytes)"} out.Optional = append(out.Optional, "reviews scheduling read --help", "reviews scheduling configure --help", "reviews scheduling pause --help", "reviews scheduling resume --help") out.Semantics = []string{"Automation defaults off. Enabling requires this connection's active bound worker and current project-management authority; CLI automation is separately opt-in via --automatic-cli; omission preserves its current value. Existing grants and taper remain unchanged.", "Pause can precede any intent. Existing provider review collection continues, and separate operation pauses remain in effect. Read the current revision; mutations require an explicit key and preserve original-key recovery.", "No live provider request is needed to read or change a PR pause. Enabling project automation authorizes later Hosted or CLI selection under all existing comparison, obligation, round and provider guards."} diff --git a/internal/client/review_agent_output.go b/internal/client/review_agent_output.go index 0da3bbc4c..1513415c5 100644 --- a/internal/client/review_agent_output.go +++ b/internal/client/review_agent_output.go @@ -21,6 +21,9 @@ func draftReadinessDiagnostic() *ReviewOperationDiagnostic { } func selectionSourceDiagnostic(reason string) *ReviewOperationDiagnostic { + if reason == "automation_authorization_changed" { + return &ReviewOperationDiagnostic{"This selection stopped before it created a review operation because its scheduling authorization no longer applies.", "Read review_scheduling_read / reviews scheduling. A project manager can authorize future automatic selections through an active bound worker. The retained selection records the refusal."} + } if hint := schedulingDiagnostic(reason); hint != nil { return hint } diff --git a/internal/mcpadapter/review_scheduling_test.go b/internal/mcpadapter/review_scheduling_test.go index 253178de7..bd155a266 100644 --- a/internal/mcpadapter/review_scheduling_test.go +++ b/internal/mcpadapter/review_scheduling_test.go @@ -104,7 +104,7 @@ func TestSchedulingSDKBoundControlsAndDiscovery(t *testing.T) { } seen++ write := tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update" - if tool.Annotations == nil || tool.Annotations.ReadOnlyHint == write || tool.Annotations.OpenWorldHint == nil || *tool.Annotations.OpenWorldHint != (tool.Name == "review_scheduling_configure") { + if tool.Annotations == nil || tool.Annotations.ReadOnlyHint == write || tool.Annotations.OpenWorldHint == nil || *tool.Annotations.OpenWorldHint != (tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update") { t.Fatal("unsafe annotations", tool.Name) } } diff --git a/internal/reviewexec/queued_diagnostic.go b/internal/reviewexec/queued_diagnostic.go index 52e88588b..1e689a8ab 100644 --- a/internal/reviewexec/queued_diagnostic.go +++ b/internal/reviewexec/queued_diagnostic.go @@ -128,6 +128,7 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, cause = "awaiting_scheduler" capability, ok := e.capabilities[original.CapabilityID] if !ok || capability.Fingerprint != op.CapabilityFingerprint { + cause = "" return nil } reservation, err = queuedReservationHolder(ctx, tx, op, capability, repositoryID) diff --git a/internal/reviewexec/scheduling_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go index 3804a5709..8e41cb112 100644 --- a/internal/reviewexec/scheduling_authorization_continuity.go +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -4,6 +4,8 @@ import ( "context" "database/sql" "encoding/json" + + "github.com/benhook1013/FireController/internal/strictjson" ) // A configuration owner change governs new selections. It need not replace an @@ -40,20 +42,21 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision defer rows.Close() expected := revision for rows.Next() { - var recorded int64 + var retainedRevision any var actor string var payload []byte - if err = rows.Scan(&recorded, &actor, &payload); err != nil { + if err = rows.Scan(&retainedRevision, &actor, &payload); err != nil { return false, err } - if recorded != expected || recorded == revision && actor != originalActor || recorded == current.Revision && actor != current.actor { + recorded, validRevision := retainedRevision.(int64) + if !validRevision || recorded != expected || recorded == revision && actor != originalActor || recorded == current.Revision && actor != current.actor { return false, nil } var settings struct { Hosted *bool `json:"automatic_hosted"` CLI *bool `json:"automatic_cli"` } - if len(payload) > 4096 || json.Unmarshal(payload, &settings) != nil { + if len(payload) > 4096 || strictjson.Validate(payload) != nil || json.Unmarshal(payload, &settings) != nil { return false, nil } enabled := settings.Hosted diff --git a/internal/reviewexec/scheduling_authorization_continuity_test.go b/internal/reviewexec/scheduling_authorization_continuity_test.go index fc1a9becb..84ecf2b8c 100644 --- a/internal/reviewexec/scheduling_authorization_continuity_test.go +++ b/internal/reviewexec/scheduling_authorization_continuity_test.go @@ -75,7 +75,7 @@ func TestRetainedAutomaticAuthorizationSurvivesUnrelatedLaneToggle(t *testing.T) func TestRetainedAutomaticAuthorizationRequiresCompleteAuthorityAndHistory(t *testing.T) { for _, channel := range []string{"hosted", "cli"} { - for _, fault := range []string{"lane-disabled", "lane-off-on", "missing-initial", "missing-middle", "missing-current", "duplicate-revision", "original-actor", "current-actor", "malformed-payload", "null-lane", "revoked-original", "lost-manage", "retired-original", "revoked-current", "mismatched-child", "unselected"} { + for _, fault := range []string{"lane-disabled", "lane-off-on", "missing-initial", "missing-middle", "missing-current", "duplicate-revision", "original-actor", "current-actor", "malformed-payload", "duplicate-channel", "fractional-revision", "null-lane", "revoked-original", "lost-manage", "retired-original", "revoked-current", "mismatched-child", "unselected"} { t.Run(channel+"/"+fault, func(t *testing.T) { f, r := continuityFixture(t, channel, fault != "unselected") switch fault { @@ -105,6 +105,10 @@ func TestRetainedAutomaticAuthorizationRequiresCompleteAuthorityAndHistory(t *te admissionSQL(t, f, `UPDATE events SET actor_id='forged-actor' WHERE event_type='review.scheduling_updated' AND revision=2`) case "malformed-payload": admissionSQL(t, f, `UPDATE events SET payload_json='{}' WHERE event_type='review.scheduling_updated' AND revision=2`) + case "duplicate-channel": + admissionSQL(t, f, `UPDATE events SET payload_json='{"automatic_hosted":false,"automatic_hosted":true,"automatic_cli":false,"automatic_cli":true}' WHERE event_type='review.scheduling_updated' AND revision=2`) + case "fractional-revision": + admissionSQL(t, f, `UPDATE events SET revision=1.5 WHERE event_type='review.scheduling_updated' AND revision=2`) case "null-lane": admissionSQL(t, f, `UPDATE events SET payload_json='{"automatic_hosted":null,"automatic_cli":null}' WHERE event_type='review.scheduling_updated' AND revision=2`) case "revoked-original": diff --git a/internal/reviewexec/scheduling_source_retry_test.go b/internal/reviewexec/scheduling_source_retry_test.go index f693fa843..c96e74f4e 100644 --- a/internal/reviewexec/scheduling_source_retry_test.go +++ b/internal/reviewexec/scheduling_source_retry_test.go @@ -126,6 +126,8 @@ func TestAutomaticSourceRetryFences(t *testing.T) { for _, mode := range []string{"configuration", "policy", "authorization", "worker", "scheduling", "newer-intent", "explicit", "budget", "capability"} { t.Run(mode, func(t *testing.T) { f, r := sourceRetryFixture(t) + var basis string + var schedulingRevision int64 switch mode { case "configuration": f.configure(t, attemptProject, "test-capability", 1, false) @@ -140,6 +142,9 @@ func TestAutomaticSourceRetryFences(t *testing.T) { case "newer-intent": selectionEnqueue(t, f, "later-intent", "hosted", nil) case "explicit": + if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256,scheduling_revision FROM review_automatic_selections WHERE selection_id=?`, r.ID).Scan(&basis, &schedulingRevision); err != nil { + t.Fatal(err) + } admissionSQL(t, f, `DELETE FROM review_automatic_selections WHERE selection_id='`+r.ID+`'`) case "budget": admissionSQL(t, f, `UPDATE review_selections SET revision=9 WHERE id='`+r.ID+`'`) @@ -150,7 +155,7 @@ func TestAutomaticSourceRetryFences(t *testing.T) { ageSourceRetry(t, f, r.ID) // Direct helper cannot find a retained automatic intent for this selection. err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - worked, err := f.e.retryAutomaticSourceTx(ctx, tx, attemptProject, "unused", 1, time.Now()) + worked, err := f.e.retryAutomaticSourceTx(ctx, tx, attemptProject, basis, schedulingRevision, time.Now()) if worked { t.Error("explicit intent retried") } @@ -309,6 +314,8 @@ func TestAutomaticSourceRetryTimestampPrecisionFence(t *testing.T) { at := time.Now().Add(-time.Minute).Truncate(time.Second) admissionSQL(t, f, `UPDATE review_selections SET created_at=?,updated_at=? WHERE id=?`, at.Format(time.RFC3339Nano), at.Format(time.RFC3339Nano), r.ID) later, _ := selectionEnqueue(t, f, "later-fractional-time", "hosted", nil) + // Exercise the time fallback independently of event acceptance order. + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.selection_requested' AND resource_id=?`, later.ID) admissionSQL(t, f, `UPDATE review_selections SET created_at=?,updated_at=? WHERE id=?`, at.Add(time.Millisecond).Format(time.RFC3339Nano), at.Add(time.Millisecond).Format(time.RFC3339Nano), later.ID) if retrySourceDirect(t, f, r, time.Now()) { t.Fatal("variable timestamp precision lost newer-intent fence") diff --git a/tools/packagedsmoke/project_management_test.go b/tools/packagedsmoke/project_management_test.go index a7b1cda40..99770b3f3 100644 --- a/tools/packagedsmoke/project_management_test.go +++ b/tools/packagedsmoke/project_management_test.go @@ -204,19 +204,19 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { cli(managerProfile, "manager-restarted", "reviews", "scheduling", "resume", "--pr", "42", "--expect-revision", "1", "--key", "scheduling-resume") daemon.stop(t) daemon = startDaemon(t, ctx, filepath.Join(bin, "fcd"), data, env) - managerProfile = profile("manager-restarted", managerFile) + managerProfile = profile("manager-resumed", managerFile) var resumed client.ReviewPullScheduling - decode(t, cli(managerProfile, "manager-restarted", "reviews", "scheduling", "read", "--pr", "42"), &resumed) + decode(t, cli(managerProfile, "manager-resumed", "reviews", "scheduling", "read", "--pr", "42"), &resumed) if resumed.Paused || resumed.Revision != 2 || resumed.Reason != "" { t.Fatal("restart changed scheduling control", resumed) } - decode(t, cli(managerProfile, "manager-restarted", "reviews", "scheduling"), &scheduling) + decode(t, cli(managerProfile, "manager-resumed", "reviews", "scheduling"), &scheduling) if scheduling.Revision != 1 || scheduling.AutomaticHosted || scheduling.AutomaticCLI { t.Fatal("restart changed default-off control", scheduling) } var replay client.WorkerRetirementReceipt - decode(t, cli(managerProfile, "manager-restarted", "workers", "retire", target.ID, "--key", "retire"), &replay) + decode(t, cli(managerProfile, "manager-resumed", "workers", "retire", target.ID, "--key", "retire"), &replay) if replay != retired { t.Fatal("restart changed retirement receipt") } From 5028a24ccdfac73fd313fdb0835ee571585748df Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 19:21:52 +1300 Subject: [PATCH 03/41] Preserve typed operation isolation through scheduling carry --- internal/reviewexec/scheduling_cli_priority.go | 2 +- internal/reviewexec/supervisor.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/reviewexec/scheduling_cli_priority.go b/internal/reviewexec/scheduling_cli_priority.go index 88985783a..ed1fb0788 100644 --- a/internal/reviewexec/scheduling_cli_priority.go +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -54,7 +54,7 @@ candidates: for _, id := range ids { earlier, err := readOperation(ctx, tx, id.project, id.operation) if err != nil { - if isRetainedOperationDecodeError(err) || isWaitUnavailable(err) || automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { + if isStoredUnavailable(err, storedOperationIdentity) || isRetainedOperationDecodeError(err) || isWaitUnavailable(err) || automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { continue candidates } return false, err diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index b52a75e2b..c948a61a3 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -470,7 +470,7 @@ func (e *Engine) skipUnavailableConfiguration(ctx context.Context, o Operation, // Invalid retained identity flags refuse only their operation. Storage and // context errors must still fail the scan rather than masquerade as corruption. func (e *Engine) skipUnavailableOperation(ctx context.Context, o Operation, err error) bool { - if !isStoredUnavailable(err, storedOperationIdentity) { + if !isStoredUnavailable(err, storedOperationIdentity) && !isRetainedOperationDecodeError(err) { return false } now := e.sampleExecutionTime() From 994e822e4fdf0b5a4eacd037870f1ed26e6ffbc4 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 15 Nov 2026 03:14:20 +1300 Subject: [PATCH 04/41] Keep malformed retained operation flags local during recovery --- internal/reviewexec/attempts.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 6ac26a8c3..322aae26e 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -527,7 +527,7 @@ func (e *Engine) recoverInterruptedSelected(ctx context.Context, skipped, select if err != nil { // Corrupt authority stays reserved; it cannot prevent unrelated // projects from recovering or authorize a replacement attempt. - if isStoredUnavailable(err, storedOperationIdentity) || isWaitUnavailable(err) { + if isStoredUnavailable(err, storedOperationIdentity) || isRetainedOperationDecodeError(err) || isWaitUnavailable(err) { slog.WarnContext(ctx, "Interrupted operation authority unavailable", "operation_id", a.OperationID, "attempt_id", a.ID) continue } From 30382d84f50b29a862aaf67f2402d072c8da53ee Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 15 Nov 2026 07:10:22 +1300 Subject: [PATCH 05/41] Preserve progress and restore validation for corrupt scheduling holds --- docs/review-scheduling.md | 2 +- .../adoption_holds_integration_test.go | 31 +++++++++++++++++++ internal/reviewexec/hosted_wait_validation.go | 2 +- internal/reviewexec/supervisor.go | 5 ++- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index 67297f033..0773b778a 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -8,7 +8,7 @@ Projects can independently opt in to automatic new Hosted or CLI requests. Both ## Automatic Hosted requests -A project manager enables scheduling through CLI or MCP. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. The HTTP contract also permits an authorized browser manager to explicitly select the authorizing worker while retaining the human session identity. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. Across an authorizer change, only an already selected operation can continue, and both authorizers must remain valid. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. +A project manager enables scheduling through CLI or MCP. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. The HTTP contract also permits an authorized browser manager to explicitly select the authorizing worker while retaining the human session identity. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected queued intent may continue after an A-to-B-to-A authorizer sequence when the current authorizer again matches its original authorizer and complete history proves its channel stayed enabled throughout. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. The scheduler uses the existing configured queue and ordinary durable selection/operation path. It checks eligible work at most once per five-second coordinator interval; this is not a promised start time or another GitHub polling loop. Source, dependency, publication, findings, routes, imported obligations, round limits, taper and provider guards still apply. Independent PRs can proceed while another awaits fixes; real dependencies retain predecessor guards. Retained scheduling validation failures prevent planning for the affected project; malformed shared scheduling state or unavailable shared authorization can affect both channels. Channel-front and source-retry selection validation failures, a retained parent cycle, or a planning basis above its row limit remain local to the affected project and channel. Independent projects continue, and channel-specific failures do not block the other channel. The execution supervisor skips these typed project-local refusals, and a damaged competing priority candidate cannot block a healthy project’s account claim. A deterministic basis refusal during selection settlement rolls back source and child writes and holds the original selection as `automatic_scheduling_unavailable`; it is not transient contention and does not enter the writer retry loop. The accepted basis remains available for duplicate suppression across ticks and restart. Startup validates the shared front-cache table definition without scanning optional cache rows. Damaged rows remain isolated by project/channel readers; backup and restore still validate the complete retained snapshot. Shared storage and transaction failures remain errors rather than being suppressed; arbitrary SQL failures are not classified as project-local corruption. Automatic requests never inherit out-of-order or file-limit overrides. Each project first plans in a bounded read-only snapshot. Only a candidate for a new intent or a due retained source retry enters the writer, which repeats authorization, configuration, policy, pause, busy and basis checks before ordinary atomic acceptance or retry. A changed plan waits for a later pass. diff --git a/internal/reviewexec/adoption_holds_integration_test.go b/internal/reviewexec/adoption_holds_integration_test.go index 5197557b9..98e288766 100644 --- a/internal/reviewexec/adoption_holds_integration_test.go +++ b/internal/reviewexec/adoption_holds_integration_test.go @@ -638,6 +638,37 @@ func TestAdoptionHoldsIntegrationSupervisorSettlesRepositoryChangeDuringPrepare( if driver.calls.Load() != 0 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { t.Fatal("corrupt retained source reached dispatch or leaked reservation") } + // Detached corruption holds must remain covered by restore validation. + tx, txErr := f.store.DB().BeginTx(t.Context(), nil) + if txErr != nil { + t.Fatal(txErr) + } + if err := ValidateOperationWaitsSnapshot(t.Context(), tx); err != nil { + t.Fatal("valid detached hold", err) + } + tx.Rollback() + if _, err := f.store.DB().Exec(`UPDATE review_execution_attempts SET external_id='unexpected-provider-effect' WHERE id=?`, preparing.ID); err != nil { + t.Fatal(err) + } + tx, txErr = f.store.DB().BeginTx(t.Context(), nil) + if txErr != nil { + t.Fatal(txErr) + } + if err := ValidateOperationWaitsSnapshot(t.Context(), tx); err == nil { + t.Fatal("restore skipped corrupt detached scheduling hold") + } + tx.Rollback() + if _, err := f.store.DB().Exec(`UPDATE review_execution_attempts SET external_id='' WHERE id=?`, preparing.ID); err != nil { + t.Fatal(err) + } + f.configure(t, otherAttemptProject, "test-capability", 0, false) + f.enqueue(t, otherAttemptProject, "other-after-corrupt-source", channel, 2, 1) + other := &controlledDriver{dispatch: func(_ context.Context, _ Operation, _ Attempt, _ func(context.Context, string) error) (Result, error) { + return Result{State: "failed", Reason: "synthetic_no_post"}, nil + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": other}); err != nil || other.calls.Load() != 1 { + t.Fatal("corrupt source starved healthy project", err, other.calls.Load()) + } return } if err != nil { diff --git a/internal/reviewexec/hosted_wait_validation.go b/internal/reviewexec/hosted_wait_validation.go index 7bb23837c..d689855fd 100644 --- a/internal/reviewexec/hosted_wait_validation.go +++ b/internal/reviewexec/hosted_wait_validation.go @@ -18,7 +18,7 @@ func ValidateOperationWaitsSnapshot(ctx context.Context, tx *sql.Tx) error { LEFT JOIN review_operations o ON o.id=a.operation_id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE (o.id IS NULL OR o.attempt_id<>a.id) AND t.reason IN ('allowance_exhausted','hosted_allowance_cooldown') - UNION SELECT o.project_id,o.id FROM review_operations o JOIN review_execution_attempts a ON a.operation_id=o.id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE a.id<>o.attempt_id AND t.reason IN ('pull_scheduling_paused','automation_authorization_changed') + UNION SELECT o.project_id,o.id FROM review_operations o JOIN review_execution_attempts a ON a.operation_id=o.id JOIN review_execution_transitions t ON t.attempt_id=a.id WHERE a.id<>o.attempt_id AND t.reason IN ('pull_scheduling_paused','automation_authorization_changed','automatic_scheduling_unavailable') ORDER BY 2`, cliDraftWait, cliDraftWait) if err != nil { return err diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index c948a61a3..3b49cbe21 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -656,7 +656,10 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { // Only proven retained project corruption is local. No intent // was admitted; retain the queued identity for a repaired read. - return e.finishPreparation(a, "held", "automatic_scheduling_unavailable") + if err := e.finishPreparation(a, "held", "automatic_scheduling_unavailable"); err != nil { + return err + } + continue } var refusal *core.Error if errors.As(err, &refusal) && (refusal.Code == "pull_scheduling_paused" || refusal.Code == "automation_authorization_changed") { From 08d2675c00e2e34f5e81aa8e9fba38468a3d84e7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 15 Nov 2026 07:12:44 +1300 Subject: [PATCH 06/41] Prove healthy work progresses in the same corruption-hold pass --- .../adoption_holds_integration_test.go | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/internal/reviewexec/adoption_holds_integration_test.go b/internal/reviewexec/adoption_holds_integration_test.go index 98e288766..e6c787f3d 100644 --- a/internal/reviewexec/adoption_holds_integration_test.go +++ b/internal/reviewexec/adoption_holds_integration_test.go @@ -700,3 +700,38 @@ func TestAdoptionHoldsIntegrationSupervisorSettlesRepositoryChangeDuringPrepare( } } } + +func TestSchedulingCorruptionContinuesHealthyCandidateInSamePass(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + t.Run(channel, func(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + f.enqueue(t, attemptProject, "first-corrupt", channel, 2, 1) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + f.enqueue(t, otherAttemptProject, "later-healthy", channel, 2, 1) + corruptPrepared := false + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + if o.ProjectID == attemptProject { + corruptPrepared = true + integrationImportHold(t, f, o.PullNumber) + if _, err := f.store.DB().Exec(`UPDATE review_adoption_obligations SET revision=2 WHERE project_id=?`, o.ProjectID); err != nil { + t.Fatal(err) + } + } + intent := "" + if channel == "hosted" { + intent = "synthetic-unposted-intent" + } + return Preparation{Anchor: attemptAnchor(o.ProjectID, o.PullNumber), Intent: intent}, nil + }, dispatch: func(_ context.Context, o Operation, _ Attempt, _ func(context.Context, string) error) (Result, error) { + if !corruptPrepared || o.ProjectID != otherAttemptProject { + t.Fatal("unexpected dispatch order or corrupt dispatch", o.ProjectID) + } + return Result{State: "failed", Reason: "synthetic_no_post"}, nil + }} + if err := f.e.processNext(t.Context(), map[string]Driver{"test-capability": driver}); err != nil || driver.calls.Load() != 1 { + t.Fatal("same pass starved later healthy candidate", err, driver.calls.Load()) + } + }) + } +} From 0c3b04f6911d69ca33689e8e38fbc813394cbd70 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 15 Nov 2026 19:19:16 +1300 Subject: [PATCH 07/41] Preserve retained scheduling authority and isolate malformed selections --- internal/reviewexec/allowance_observation.go | 2 +- internal/reviewexec/run_selection.go | 28 ++++++++++-- internal/reviewexec/run_selection_worker.go | 43 ++++++++++++++++-- .../scheduling_allowance_history_test.go | 32 +++++++++++++ .../scheduling_pause_history_test.go | 45 +++++++++++++++++++ internal/reviewexec/scheduling_snapshot.go | 38 ++++++++++++++++ .../reviewexec/selection_native_key_test.go | 29 ++++++++++++ .../selection_queued_prefix_test.go | 37 +++++++++++++++ 8 files changed, 246 insertions(+), 8 deletions(-) create mode 100644 internal/reviewexec/scheduling_allowance_history_test.go create mode 100644 internal/reviewexec/scheduling_pause_history_test.go create mode 100644 internal/reviewexec/selection_native_key_test.go create mode 100644 internal/reviewexec/selection_queued_prefix_test.go diff --git a/internal/reviewexec/allowance_observation.go b/internal/reviewexec/allowance_observation.go index ba197f0aa..67e00d8b2 100644 --- a/internal/reviewexec/allowance_observation.go +++ b/internal/reviewexec/allowance_observation.go @@ -78,7 +78,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 diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 02081f181..f04a68ade 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -294,7 +294,7 @@ func (e *Engine) RecoverReviewRuns(ctx context.Context) error { return err } type key struct { - p, id string + p, id any revision int64 } var keys []key @@ -315,14 +315,22 @@ 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 { + 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: k.p, ID: k.id, State: "selecting", Revision: k.revision}) + didChange, err := quarantineSelection(ctx, tx, Run{ProjectID: project, ID: id, State: "selecting", Revision: k.revision}) if err != nil { return err } if didChange { - changed = append(changed, k.id) + changed = append(changed, id) } continue } @@ -489,3 +497,15 @@ func quarantineSelection(ctx context.Context, tx *sql.Tx, expected Run) (bool, e n, err := result.RowsAffected() return n == 1, err } + +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 + } + result, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held',reason='local_read_unavailable',revision=CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision+1 ELSE revision END WHERE project_id=? AND id=? AND state=? AND `+selectionClaimRevision+`=?`, project, id, state, revision) + if err != nil { + return false, err + } + n, err := result.RowsAffected() + return n == 1, err +} diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 1fe869eda..60a58ba36 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -217,13 +217,36 @@ func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configurati } func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (runChoice, error) { + // Bound source work before metadata lookahead. Local suppression still + // rechecks the live prefix at admission if queued work changes afterward. + err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + var automatic bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=? AND project_id=?)`, r.ID, r.ProjectID).Scan(&automatic); err != nil { + return err + } + if !automatic { + return nil + } + limit, err := automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + if err != nil { + return err + } + if limit < 0 || limit > len(c.Queue) { + return schedulingUnavailable() + } + c.Queue = c.Queue[:limit] + return nil + }) + if err != nil { + return runChoice{}, err + } 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 @@ -450,9 +473,12 @@ func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) ( var repo int64 var changed string var project, id string + var nativeProject, nativeID any + var quarantined bool var expected int64 err := retryRunSelectionLocal(ctx, func() error { project, id, expected = "", "", 0 + nativeProject, nativeID = nil, nil return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { // Request capacity is a scheduling constraint, not a terminal hold. // Skip saturated projects before source work so they cannot occupy @@ -461,16 +487,27 @@ func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) ( WHERE s.state='queued' AND (SELECT count(*) FROM review_operations WHERE state IN ('queued','preparing','posting','active','uncertain'))=? ORDER BY revision DESC,sequence DESC LIMIT 2`, s.ProjectID, strconv.FormatInt(s.PullNumber, 10), s.Revision) + if err != nil { + return err + } + defer rows.Close() + count := 0 + for rows.Next() { + count++ + var revision int64 + var actor string + var payload sql.NullString + if err := rows.Scan(&revision, &actor, &payload); err != nil { + return err + } + var event struct { + PullNumber int64 `json:"pull_number"` + Paused *bool `json:"paused"` + } + if count != 1 || revision != s.Revision || actor != s.ActorID || !payload.Valid || strictjson.Decode([]byte(payload.String), &event) != nil || event.PullNumber != s.PullNumber || event.Paused == nil || *event.Paused != s.Paused { + return schedulingUnavailable() + } + } + if err := rows.Err(); err != nil { + return err + } + if count != 1 { + return schedulingUnavailable() + } + return rows.Close() +} diff --git a/internal/reviewexec/selection_native_key_test.go b/internal/reviewexec/selection_native_key_test.go new file mode 100644 index 000000000..8301b2b94 --- /dev/null +++ b/internal/reviewexec/selection_native_key_test.go @@ -0,0 +1,29 @@ +package reviewexec + +import "testing" + +func TestSelectionNativeBlobKeyDoesNotStopRecovery(t *testing.T) { + for _, state := range []string{"queued", "selecting"} { + t.Run(state, func(t *testing.T) { + f := selectionFixture(t) + r, _ := selectionEnqueue(t, f, "blob-selection", "hosted", nil) + admissionSQL(t, f, `UPDATE review_selections SET id=CAST(id AS BLOB),state=? WHERE id=?`, state, r.ID) + if state == "selecting" { + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + } else { + if _, err := f.e.runNext(t.Context(), nil); err != nil { + t.Fatal(err) + } + } + var got, reason string + if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=CAST(? AS BLOB)`, r.ID).Scan(&got, &reason); err != nil { + t.Fatal(err) + } + if got != "held" || reason != "local_read_unavailable" { + t.Fatal(got, reason) + } + }) + } +} diff --git a/internal/reviewexec/selection_queued_prefix_test.go b/internal/reviewexec/selection_queued_prefix_test.go new file mode 100644 index 000000000..112f44e80 --- /dev/null +++ b/internal/reviewexec/selection_queued_prefix_test.go @@ -0,0 +1,37 @@ +package reviewexec + +import ( + "context" + "github.com/benhook1013/FireController/internal/reviewprovider" + "sync/atomic" + "testing" + "time" +) + +func TestAutomaticSelectionDoesNotReadQueuedSuffix(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 3, 4, 5}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + f.enqueue(t, attemptProject, "accepted-later", "hosted", 3, 1) + c, err := f.e.configurationRevision(t.Context(), r.ProjectID, r.ConfigurationRevision) + if err != nil { + t.Fatal(err) + } + var suffix atomic.Int32 + reader := &refreshTestReader{pull: func(ctx context.Context, _ string, n int64) (reviewprovider.Pull, error) { + if n >= 3 { + suffix.Add(1) + } + p := schedulingPull(n) + isDraft := true + p.IsDraft = &isDraft + return p, nil + }} + if _, err = f.e.chooseRunWithSourceBudget(t.Context(), r, 801, c, reader, time.Second); err != nil { + t.Fatal(err) + } + if suffix.Load() != 0 { + t.Fatal("read ineligible queued suffix", suffix.Load()) + } +} From 976eae34bd381ca3895f332edbdb1e0063b11170 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 19 Nov 2026 01:35:06 +1300 Subject: [PATCH 08/41] Keep automatic scheduling backend separate from bound clients --- docs/mcp.md | 6 +- docs/review-scheduling.md | 4 +- internal/cli/cli.go | 24 +- internal/cli/operation_help.go | 3 - internal/cli/review_operation_control_test.go | 77 ---- internal/cli/review_scheduling.go | 107 ----- internal/cli/review_scheduling_help.go | 43 -- internal/cli/review_scheduling_test.go | 144 ------ internal/cli/reviews.go | 8 - internal/client/client.go | 5 +- internal/client/review_agent_output.go | 26 -- internal/client/review_agent_output_test.go | 3 - internal/client/review_scheduling.go | 184 -------- .../client/review_scheduling_diagnostic.go | 13 - .../review_scheduling_diagnostic_test.go | 105 ----- internal/client/review_scheduling_test.go | 434 ------------------ internal/mcpadapter/adapter_test.go | 5 +- internal/mcpadapter/arguments.go | 3 - internal/mcpadapter/review_scheduling.go | 108 ----- .../review_scheduling_arguments_test.go | 53 --- internal/mcpadapter/review_scheduling_test.go | 120 ----- internal/mcpadapter/tools.go | 21 +- .../packagedsmoke/project_management_test.go | 39 +- 23 files changed, 12 insertions(+), 1523 deletions(-) delete mode 100644 internal/cli/review_scheduling.go delete mode 100644 internal/cli/review_scheduling_help.go delete mode 100644 internal/cli/review_scheduling_test.go delete mode 100644 internal/client/review_scheduling.go delete mode 100644 internal/client/review_scheduling_diagnostic.go delete mode 100644 internal/client/review_scheduling_diagnostic_test.go delete mode 100644 internal/client/review_scheduling_test.go delete mode 100644 internal/mcpadapter/review_scheduling.go delete mode 100644 internal/mcpadapter/review_scheduling_arguments_test.go delete mode 100644 internal/mcpadapter/review_scheduling_test.go diff --git a/docs/mcp.md b/docs/mcp.md index 597267588..af10ec30f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -93,10 +93,6 @@ Startup validates configuration without opening the credential or contacting the | `inbox_events` | Required event cursor; optional limit and wait_ms 0–4000; one bounded incoming-event page. | | `wait_for_messages` | Required event cursor; optional limit 1–100 and wait_seconds 1–50, default 20/25. One new-message event page or quiet timeout over a call-owned persistent stream. | | `review_execution_read` | No fields; stored execution configuration and revision, without provider work. | -| `review_scheduling_read` | No fields; stored project scheduling settings, revision and paused queued PRs, without provider work. | -| `review_scheduling_configure` | Required idempotency_key/expected_revision/automatic_hosted; optional automatic_cli preserves its existing value when omitted. Project management capability configures [default-off automatic scheduling](review-scheduling.md), including authorization for later provider work within existing review limits. | -| `review_pull_scheduling_read` | Required pull_number; reads the per-PR pause for new and undispatched explicit and automatic reviews, and its revision. | -| `review_pull_scheduling_update` | Required idempotency_key/pull_number/expected_revision/paused; optional reason is accepted only when pausing. Changes the scheduling pause while preserving review limits and retained request controls. | | `review_operations_list` | Optional pull_number/channel/status/limit/cursor; one bounded page of retained operations, default five pending. No provider work or automatic continuation. | | `review_operation_read` | Required operation_id; optional wait_seconds (0–50/default 0) and diagnostics (default false). Compact retained status and original Hosted observer freshness, or explicit full detail, without provider polling. | | `review_operation_control` | Required operation_id/expected_revision/action/idempotency_key; action pause, resume or cancel applies guarded [retained request controls](retained-review-quota-controls.md#reading-state), preserving original authorization and attempt history. | @@ -148,7 +144,7 @@ Review queue/run/attempt lists default to five entries; other limits use the API [Job progress](job-progress.md) owns update/checklist content limits, independent revisions, explicit archives and integration proof. Checklist replacement can remove or replace effective items and is annotated destructive; its immutable history remains available. Job updates and checklist operations perform no provider work. -Mutations require the caller to retain an explicit key and request; the adapter never generates a replacement key or automatically retries. Job edits require the current expected revision; empty brief or worker clears that field. A dispatched write with a lost, canceled or invalid response returns `outcome_unknown` when a tool result can be delivered. Host cancellation may suppress that result, so absence of a reply is never proof of rollback. Recover using the original request, key and binding. The [MCP annotations](https://modelcontextprotocol.io/specification/2025-11-25/schema#toolannotations) distinguish reads from writes. Repeating identical arguments retains the same explicit key and has no additional effect; job edits and review decision/fix corrections can replace effective fields while retained history remains; creation/checkpoint/send/receipt transitions add records or handling state. Job, message and evidence controls operate within the configured service. `review_scheduling_configure`, `review_start`, `review_request`, `review_source_refresh`, `review_checkpoint_publish` and `review_checkpoint_recover` are annotated open-world because they authorize external provider work; a queued receipt does not establish started or completed execution. The [CLI recovery rules](development.md#explicit-agent-mutations) also apply. +Mutations require the caller to retain an explicit key and request; the adapter never generates a replacement key or automatically retries. Job edits require the current expected revision; empty brief or worker clears that field. A dispatched write with a lost, canceled or invalid response returns `outcome_unknown` when a tool result can be delivered. Host cancellation may suppress that result, so absence of a reply is never proof of rollback. Recover using the original request, key and binding. The [MCP annotations](https://modelcontextprotocol.io/specification/2025-11-25/schema#toolannotations) distinguish reads from writes. Repeating identical arguments retains the same explicit key and has no additional effect; job edits and review decision/fix corrections can replace effective fields while retained history remains; creation/checkpoint/send/receipt transitions add records or handling state. Job, message and evidence controls operate within the configured service. `review_start`, `review_request`, `review_source_refresh`, `review_checkpoint_publish` and `review_checkpoint_recover` are annotated open-world because they authorize external provider work; a queued receipt does not establish started or completed execution. The [CLI recovery rules](development.md#explicit-agent-mutations) also apply. Explicit message, review-result, source-refresh and checkpoint waits are capped at 50 seconds in both discovery and argument validation. With the five-second service budget, these calls leave at least five seconds below a 60-second host tool deadline. Hosts with shorter configured limits need shorter requested waits. This MCP cap does not narrow CLI or typed-client limits. `wait_for_ci` accepts 0–900 seconds and is exempt from this 50-second cap. For waits over two seconds, its call budget is the selected wait plus fifteen seconds; shorter waits use fifteen seconds. Both are subject to an earlier host deadline. Configure the host tool deadline to cover that budget; the adapter shortens the forwarded wait to leave response time within any earlier deadline. See [CI waits](ci-wait.md) for reconnect and pinned-comparison behavior. diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index 0773b778a..f81d2b17b 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -2,13 +2,13 @@ ## Source-slice boundary -This slice includes the scheduling engine, retained-state guards, HTTP API and CLI/MCP controls. The current-review-progress browser consumer, its scoped live-event additions, generated assets and browser smoke workload are delivered in the dependent browser slice. Browser behavior and historical validation described below apply to that combined stack, not this intermediate scheduling tree. +This slice includes the scheduling engine, retained-state guards and HTTP API. Bound Go client, CLI and MCP controls and their packaged administration smoke are delivered in the dependent client slice. The current-review-progress browser consumer, its scoped live-event additions, generated assets and browser smoke workload are delivered in the dependent browser slice. Browser behavior and historical validation described below apply to that combined stack, not this intermediate scheduling tree. Projects can independently opt in to automatic new Hosted or CLI requests. Both default to off. Explicit CLI requests continue to work without enabling automatic selection; a proven quota refusal retains any accepted request through [durable CLI waiting](retained-review-quota-controls.md), without replacing that operation. Automatic GitHub observation and automatic retry of an already authorized timer-backed request are independent of this setting; see [observation](github-observation.md) and [timer-backed waiting](retained-review-quota-controls.md). ## Automatic Hosted requests -A project manager enables scheduling through CLI or MCP. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. The HTTP contract also permits an authorized browser manager to explicitly select the authorizing worker while retaining the human session identity. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected queued intent may continue after an A-to-B-to-A authorizer sequence when the current authorizer again matches its original authorizer and complete history proves its channel stayed enabled throughout. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. +A project manager enables scheduling through the HTTP API; bound CLI and MCP delivery follows in the dependent client slice. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. The HTTP contract also permits an authorized browser manager to explicitly select the authorizing worker while retaining the human session identity. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected queued intent may continue after an A-to-B-to-A authorizer sequence when the current authorizer again matches its original authorizer and complete history proves its channel stayed enabled throughout. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. The scheduler uses the existing configured queue and ordinary durable selection/operation path. It checks eligible work at most once per five-second coordinator interval; this is not a promised start time or another GitHub polling loop. Source, dependency, publication, findings, routes, imported obligations, round limits, taper and provider guards still apply. Independent PRs can proceed while another awaits fixes; real dependencies retain predecessor guards. Retained scheduling validation failures prevent planning for the affected project; malformed shared scheduling state or unavailable shared authorization can affect both channels. Channel-front and source-retry selection validation failures, a retained parent cycle, or a planning basis above its row limit remain local to the affected project and channel. Independent projects continue, and channel-specific failures do not block the other channel. The execution supervisor skips these typed project-local refusals, and a damaged competing priority candidate cannot block a healthy project’s account claim. A deterministic basis refusal during selection settlement rolls back source and child writes and holds the original selection as `automatic_scheduling_unavailable`; it is not transient contention and does not enter the writer retry loop. The accepted basis remains available for duplicate suppression across ticks and restart. Startup validates the shared front-cache table definition without scanning optional cache rows. Damaged rows remain isolated by project/channel readers; backup and restore still validate the complete retained snapshot. Shared storage and transaction failures remain errors rather than being suppressed; arbitrary SQL failures are not classified as project-local corruption. Automatic requests never inherit out-of-order or file-limit overrides. Each project first plans in a bounded read-only snapshot. Only a candidate for a new intent or a due retained source retry enters the writer, which repeats authorization, configuration, policy, pause, busy and basis checks before ordinary atomic acceptance or retry. A changed plan waits for a later pass. diff --git a/internal/cli/cli.go b/internal/cli/cli.go index a11eb0e0e..ecdbb3cf5 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -46,7 +46,6 @@ type options struct { } type invocation struct { - reviewScheduling *reviewSchedulingInvocation ownerManagement *ownerManagementInvocation includeRetired bool ciWatch *ciWatchInvocation @@ -360,7 +359,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou if err != nil { return reportClientError(stderr, err, ctx) } - if call.reviewOperationControl != nil || call.reviewScheduling != nil && call.reviewScheduling.action != "read" { + if call.reviewOperationControl != nil { encoded, err := json.Marshal(value) if err == nil { encoded = append(encoded, '\n') @@ -414,27 +413,6 @@ func parseInvocation(args []string) (invocation, bool) { return call, false } call.command = remaining[0] - // Scheduling help is entirely local and has exact leaf grammar. - if len(remaining) >= 3 { - words := remaining - if words[0] == "help" { - words = words[1:] - } else if words[len(words)-1] == "--help" { - words = words[:len(words)-1] - } else { - words = nil - } - if len(words) == 2 || len(words) == 3 { - if words[0] == "reviews" && words[1] == "scheduling" { - name := strings.Join(words, " ") - if _, ok := operationHelp(name); ok { - call.operationHelp = name - return call, true - } - } - } - } - if len(remaining) == 2 && (remaining[1] == "help" || remaining[1] == "--help") && (call.command == "credentials" || call.command == "workers" || call.command == "reviews") { call.operationHelp = call.command + " help" return call, true diff --git a/internal/cli/operation_help.go b/internal/cli/operation_help.go index b9bffbfbd..533541c84 100644 --- a/internal/cli/operation_help.go +++ b/internal/cli/operation_help.go @@ -15,9 +15,6 @@ type operationHelpResponse struct { } func emitOperationHelp(operation string, stdout, stderr io.Writer) int { - if help, ok := operationHelp(operation); ok { - return emit(stdout, stderr, help) - } if help, ok := ownerManagementHelp(operation); ok { return emit(stdout, stderr, help) } diff --git a/internal/cli/review_operation_control_test.go b/internal/cli/review_operation_control_test.go index 02af3fd18..10e646dc5 100644 --- a/internal/cli/review_operation_control_test.go +++ b/internal/cli/review_operation_control_test.go @@ -6,12 +6,9 @@ import ( "github.com/benhook1013/FireController/internal/cli" "github.com/benhook1013/FireController/internal/client" "github.com/benhook1013/FireController/internal/strictjson" - "io" "net/http" "net/http/httptest" - "reflect" "strings" - "sync/atomic" "testing" ) @@ -111,77 +108,3 @@ func TestReviewControlOutputFailureRetainsSameKeyRecovery(t *testing.T) { t.Fatal("same-key recovery changed effect", code, out, stderr) } } - -func TestReviewSchedulingCLIOutputFailureRetainsSameKeyRecovery(t *testing.T) { - for _, action := range []string{"configure", "pause", "resume"} { - for _, output := range []struct { - name string - writer io.Writer - }{{"failed", roundFailWriter{}}, {"short", shortMapOutput{}}} { - t.Run(action+"/"+output.name, func(t *testing.T) { - f, project, worker := reviewExecutionFixture(t) - var posts atomic.Int64 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/scheduling") { - posts.Add(1) - if r.Header.Get("X-FC-Worker") != worker || r.Header.Get("X-FC-Instance") != f.store.InstanceID() || !strings.HasPrefix(r.URL.Path, "/api/v1/projects/"+project+"/") { - t.Error("scheduling mutation lost binding") - } - } - f.handler.ServeHTTP(w, r) - })) - defer server.Close() - profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"builder": {project, worker}}) - expected, revision := "0", int64(1) - if action == "resume" { - mutationSuccess(t, profiles, "builder", "reviews", "scheduling", "pause", "--pr", "2", "--expect-revision", "0", "--key", "prepare-paused-pull") - expected, revision = "1", 2 - posts.Store(0) - } - args := []string{"reviews", "scheduling", action, "--expect-revision", expected, "--key", "original-scheduling-key"} - state, id := "pull_scheduling_updated", "2" - switch action { - case "configure": - args = append(args, "--automatic-hosted", "true") - state, id = "scheduling_configured", project - case "pause", "resume": - args = append(args, "--pr", "2") - } - full := append([]string{"--profiles-file", profiles, "--profile", "builder"}, args...) - var diag strings.Builder - code := cli.RunContext(t.Context(), full, nil, output.writer, &diag) - var failure struct { - Error client.Error `json:"error"` - } - if code != cli.ExitConfig || json.Unmarshal([]byte(diag.String()), &failure) != nil || failure.Error.Code != "output_failed" || !failure.Error.OutcomeUnknown || !strings.Contains(failure.Error.Action, "exact same key, request and bound instance") || posts.Load() != 1 { - t.Fatal("committed scheduling output failure lost exact recovery or retried", code, diag.String(), posts.Load()) - } - code, out, stderr := mutationInvoke(t, profiles, "builder", args...) - var receipt client.ReviewRequestReceipt - if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &receipt) != nil || receipt.ID != id || receipt.State != state || receipt.Revision != revision || posts.Load() != 2 { - t.Fatal("exact recovery changed the scheduling effect", code, out, stderr, posts.Load()) - } - code, out, stderr = mutationInvoke(t, profiles, "builder", args...) - var replay client.ReviewRequestReceipt - if code != 0 || stderr != "" || json.Unmarshal([]byte(out), &replay) != nil || !reflect.DeepEqual(receipt, replay) || posts.Load() != 3 { - t.Fatal("scheduling replay changed receipt", code, out, stderr) - } - }) - } - } -} - -func TestReviewSchedulingCLIReadOutputFailureDoesNotClaimMutation(t *testing.T) { - f, project, worker := reviewExecutionFixture(t) - server := httptest.NewServer(f.handler) - defer server.Close() - profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"builder": {project, worker}}) - for _, suffix := range [][]string{nil, {"read"}, {"read", "--pr", "2"}} { - args := append([]string{"--profiles-file", profiles, "--profile", "builder", "reviews", "scheduling"}, suffix...) - var diag strings.Builder - code := cli.RunContext(t.Context(), args, nil, roundFailWriter{}, &diag) - if code != cli.ExitConfig || !strings.Contains(diag.String(), "output_failed") || strings.Contains(diag.String(), "outcome_unknown") || strings.Contains(diag.String(), "same key") { - t.Fatal("read output failure gained mutation recovery semantics", code, diag.String()) - } - } -} diff --git a/internal/cli/review_scheduling.go b/internal/cli/review_scheduling.go deleted file mode 100644 index 2f9fa0ac5..000000000 --- a/internal/cli/review_scheduling.go +++ /dev/null @@ -1,107 +0,0 @@ -package cli - -import ( - "context" - "strconv" - "strings" - - "github.com/benhook1013/FireController/internal/client" -) - -type reviewSchedulingInvocation struct { - action string - pull int64 - key string - config client.ConfigureReviewSchedulingRequest - pause client.ConfigureReviewPullSchedulingRequest -} - -func parseReviewScheduling(args []string) (*reviewSchedulingInvocation, bool) { - in := &reviewSchedulingInvocation{action: "read"} - if len(args) > 0 && !strings.HasPrefix(args[0], "--") { - in.action, args = args[0], args[1:] - } - allowed := map[string]bool{"--pr": true} - switch in.action { - case "read": - case "configure": - allowed = map[string]bool{"--automatic-hosted": true, "--automatic-cli": true, "--expect-revision": true, "--key": true} - case "pause", "resume": - allowed["--expect-revision"], allowed["--key"] = true, true - if in.action == "pause" { - allowed["--reason"] = true - } - default: - return nil, false - } - values := map[string]string{} - for i := 0; i < len(args); i++ { - flag, value, assigned := strings.Cut(args[i], "=") - if !allowed[flag] { - return nil, false - } - if _, exists := values[flag]; exists { - return nil, false - } - if !assigned { - i++ - if i >= len(args) { - return nil, false - } - value = args[i] - } - if value == "" && flag != "--reason" { - return nil, false - } - values[flag] = value - } - if value, exists := values["--pr"]; exists { - n, err := strconv.ParseInt(value, 10, 32) - if err != nil || n < 1 || strconv.FormatInt(n, 10) != value { - return nil, false - } - in.pull = n - } - if in.action == "read" { - return in, true - } - if !validMutationKey(values["--key"]) { - return nil, false - } - in.key = values["--key"] - revision, err := strconv.ParseInt(values["--expect-revision"], 10, 64) - if err != nil || strconv.FormatInt(revision, 10) != values["--expect-revision"] { - return nil, false - } - if in.action == "configure" { - value := values["--automatic-hosted"] - if value != "true" && value != "false" { - return nil, false - } - in.config = client.ConfigureReviewSchedulingRequest{ExpectedRevision: revision, AutomaticHosted: value == "true"} - if value, exists := values["--automatic-cli"]; exists { - if value != "true" && value != "false" { - return nil, false - } - enabled := value == "true" - in.config.AutomaticCLI = &enabled - } - return in, client.ValidateConfigureReviewScheduling(in.config) == nil - } - in.pause = client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: revision, Paused: in.action == "pause", Reason: values["--reason"]} - return in, client.ValidateConfigureReviewPullScheduling(in.pull, in.pause) == nil -} - -func executeReviewScheduling(ctx context.Context, service *client.Client, in *reviewSchedulingInvocation) (any, error) { - switch in.action { - case "configure": - return service.ConfigureReviewScheduling(ctx, in.key, in.config) - case "pause", "resume": - return service.ConfigureReviewPullScheduling(ctx, in.key, in.pull, in.pause) - default: - if in.pull != 0 { - return service.ReviewPullScheduling(ctx, in.pull) - } - return service.ReviewScheduling(ctx) - } -} diff --git a/internal/cli/review_scheduling_help.go b/internal/cli/review_scheduling_help.go deleted file mode 100644 index 4bc9c00a8..000000000 --- a/internal/cli/review_scheduling_help.go +++ /dev/null @@ -1,43 +0,0 @@ -package cli - -func operationHelp(operation string) (operationHelpResponse, bool) { - recovery := "Use an explicit --key (1-128 printable ASCII bytes without surrounding whitespace). After uncertain output retry the same key, exact request and binding; never invent a replacement key." - out := operationHelpResponse{Required: []string{}, Optional: []string{}} - switch operation { - case "reviews scheduling": - out.Usage = " reviews scheduling [--pr N] | configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY | pause --pr N --expect-revision N --key KEY [--reason TEXT] | resume --pr N --expect-revision N --key KEY" - out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)", "configure --automatic-hosted true|false (project manager; authorizes future automatic Hosted requests)", "pause|resume --pr N (writer; holds new/undispatched reviews without changing rounds)", "--reason TEXT (optional with pause, at most 256 UTF-8 bytes)"} - out.Optional = append(out.Optional, "reviews scheduling read --help", "reviews scheduling configure --help", "reviews scheduling pause --help", "reviews scheduling resume --help") - out.Semantics = []string{"Automation defaults off. Enabling requires this connection's active bound worker and current project-management authority; CLI automation is separately opt-in via --automatic-cli; omission preserves its current value. Existing grants and taper remain unchanged.", "Pause can precede any intent. Existing provider review collection continues, and separate operation pauses remain in effect. Read the current revision; mutations require an explicit key and preserve original-key recovery.", "No live provider request is needed to read or change a PR pause. Enabling project automation authorizes later Hosted or CLI selection under all existing comparison, obligation, round and provider guards."} - out.Documentation = "docs/review-scheduling.md" - case "reviews scheduling read": - out.Usage = " reviews scheduling read [--pr N]" - out.Optional = []string{"--pr N (read one PR pause; omission reads project settings and queued paused PRs)"} - out.Semantics = []string{"Returns stored scheduling state and its independent revision. Use the project revision for configure, or the selected PR revision for pause/resume. No provider request or writes."} - out.Example = " reviews scheduling read --pr 42" - out.Documentation = "docs/review-scheduling.md" - case "reviews scheduling configure": - out.Usage = " reviews scheduling configure --automatic-hosted true|false [--automatic-cli true|false] --expect-revision N --key KEY" - out.Required = []string{"--automatic-hosted true|false", "--expect-revision N (current project scheduling revision, including 0)", "--key KEY"} - out.Semantics = []string{"Requires project-management authority. Read reviews scheduling for the current project scheduling revision. Enabling authorizes future automatic Hosted or CLI requests through this connection's active bound worker under the existing review guards. Both default off; CLI omission preserves the current value. Automation does not adjudicate findings or increase grants.", recovery} - out.Optional = []string{"--automatic-cli true|false (separate opt-in; omission preserves the current CLI setting)"} - out.Example = " reviews scheduling configure --automatic-hosted true --expect-revision 0 --key automatic-hosted-1" - out.Documentation = "docs/review-scheduling.md" - case "reviews scheduling pause", "reviews scheduling resume": - out.Usage = " " + operation + " --pr N --expect-revision N --key KEY" - out.Required = []string{"--pr N", "--expect-revision N (current PR scheduling revision, including 0)", "--key KEY"} - out.Semantics = []string{"Requires project write access. Read reviews scheduling read --pr N for this PR's scheduling revision. Changes new/undispatched review scheduling in both channels; existing provider collection continues. Does not change rounds, channel closure or separate operation pauses.", recovery} - if operation == "reviews scheduling pause" { - out.Usage += " [--reason TEXT]" - out.Optional = []string{"--reason TEXT (optional, at most 256 UTF-8 bytes)"} - out.Semantics = append(out.Semantics, "May pause before the first review intent. No live provider request is needed to pause a PR.") - } else { - out.Semantics = append(out.Semantics, "Clears the PR pause and its reason. Accepts no --reason flag; does not resume separately paused operations or reopen closed channels.") - } - out.Example = " " + operation + " --pr 42 --expect-revision 0 --key scheduling-42-1" - out.Documentation = "docs/review-scheduling.md" - default: - return out, false - } - return out, true -} diff --git a/internal/cli/review_scheduling_test.go b/internal/cli/review_scheduling_test.go deleted file mode 100644 index 980d782d5..000000000 --- a/internal/cli/review_scheduling_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package cli - -import ( - "bytes" - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "sync/atomic" - "testing" -) - -func TestReviewSchedulingCLIExplicitControlsBeforeProfile(t *testing.T) { - for _, args := range [][]string{ - nil, {"--pr", "7"}, {"read", "--pr=7"}, - {"configure", "--automatic-hosted", "false", "--expect-revision", "0", "--key", "disable"}, - {"configure", "--automatic-hosted=true", "--expect-revision=3", "--key=enable"}, - {"pause", "--pr", "7", "--expect-revision", "0", "--reason", "Preparing changes", "--key", "pause"}, - {"resume", "--pr", "7", "--expect-revision", "1", "--key", "resume"}, - } { - call, ok := parseInvocation(append([]string{"reviews", "scheduling"}, args...)) - if !ok || call.reviewScheduling == nil || call.command != "reviews" { - t.Fatal("supported scheduling syntax refused", args, call, ok) - } - } - for _, args := range [][]string{ - {"configure", "--automatic-hosted", "true", "--key", "missing-revision"}, - {"configure", "--expect-revision", "0", "--key", "missing-explicit-bool"}, - {"configure", "--automatic-hosted", "yes", "--expect-revision", "0", "--key", "bad-bool"}, - {"configure", "--automatic-hosted", "true", "--expect-revision", "-1", "--key", "bad-revision"}, - {"--pr", "0"}, {"--pr", "07"}, {"--pr", "7", "--pr", "8"}, {"--key", "read-mutation"}, - {"pause", "--pr", "7", "--expect-revision", "0"}, - {"pause", "--pr", "7", "--expect-revision", "0", "--key", "bad-reason", "--reason", "line\nbreak"}, - {"pause", "--pr", "7", "--expect-revision", "0", "--key", "bad-reason", "--reason", strings.Repeat("x", 257)}, - {"resume", "--pr", "7", "--expect-revision", "1", "--key", "unexpected-reason", "--reason", "hidden"}, - {"configure", "--automatic-hosted", "true", "--expect-revision", "0", "--key", "foreign", "--worker", "other"}, - } { - var out, diag bytes.Buffer - code := RunContext(t.Context(), append([]string{"--profiles-file", "/missing", "reviews", "scheduling"}, args...), nil, &out, &diag) - if code != ExitUsage || out.Len() != 0 || !strings.Contains(diag.String(), "invalid_arguments") { - t.Fatal("invalid scheduling input reached profile/transport", args, code, out.String(), diag.String()) - } - } - var out, diag bytes.Buffer - if code := RunContext(t.Context(), []string{"--profiles-file", "/missing", "reviews", "scheduling", "--help"}, nil, &out, &diag); code != 0 || diag.Len() != 0 || !strings.Contains(out.String(), "docs/review-scheduling.md") || !strings.Contains(out.String(), "authorizes future") { - t.Fatal("scheduling help not usable offline", code, out.String(), diag.String()) - } -} - -func TestReviewSchedulingCLIOptionalAutomaticCLI(t *testing.T) { - base := []string{"configure", "--automatic-hosted=false", "--expect-revision=0", "--key=cli-setting"} - for _, value := range []string{"", "true", "false"} { - args := append([]string{}, base...) - if value != "" { - args = append(args, "--automatic-cli="+value) - } - in, ok := parseReviewScheduling(args) - if !ok || in.config.AutomaticHosted || (in.config.AutomaticCLI == nil) != (value == "") { - t.Fatalf("lost optional CLI state: %q %+v", value, in) - } - if value != "" && *in.config.AutomaticCLI != (value == "true") { - t.Fatal("wrong explicit CLI state") - } - } - for _, extra := range [][]string{{"--automatic-cli=yes"}, {"--automatic-cli="}, {"--automatic-cli"}, {"--automatic-cli=true", "--automatic-cli=false"}} { - if _, ok := parseReviewScheduling(append(append([]string{}, base...), extra...)); ok { - t.Fatal("accepted invalid CLI flag", extra) - } - } - if _, ok := parseReviewScheduling([]string{"configure", "--automatic-cli=true", "--expect-revision=0", "--key=missing-hosted"}); ok { - t.Fatal("Hosted flag must remain explicit") - } -} - -func TestReviewSchedulingLeafHelpIsOffline(t *testing.T) { - var requests atomic.Int64 - service := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { requests.Add(1) })) - defer service.Close() - path := filepath.Join(t.TempDir(), "profiles.json") - private := []byte("PRIVATE_INVALID_PROFILE") - if err := os.WriteFile(path, private, 0600); err != nil { - t.Fatal(err) - } - for _, leaf := range []string{"read", "configure", "pause", "resume"} { - for _, spelling := range [][]string{{"reviews", "scheduling", leaf, "--help"}, {"help", "reviews", "scheduling", leaf}} { - for _, profilePath := range []string{path, filepath.Join(t.TempDir(), "absent.json")} { - args := append([]string{"--profiles-file", profilePath, "--profile", "bound"}, spelling...) - ctx, cancel := context.WithCancel(t.Context()) - cancel() - var stdout, stderr bytes.Buffer - code := RunContext(ctx, args, map[string]string{"FC_SERVER": service.URL}, &stdout, &stderr) - var help operationHelpResponse - if code != ExitSuccess || stderr.Len() != 0 || stdout.Len() > 2500 || json.Unmarshal(stdout.Bytes(), &help) != nil || !strings.HasPrefix(help.Usage, " reviews scheduling "+leaf) || help.Documentation != "docs/review-scheduling.md" { - t.Fatalf("%v: code=%d stdout=%s stderr=%s", args, code, &stdout, &stderr) - } - if leaf != "read" && (!strings.Contains(help.Usage, "--expect-revision N --key KEY") || !strings.Contains(strings.Join(help.Semantics, " "), "same key, exact request")) { - t.Fatal("mutation help omitted revision/key recovery", leaf, help) - } - if leaf == "pause" && !strings.Contains(help.Usage, "[--reason TEXT]") || leaf == "resume" && strings.Contains(help.Usage, "--reason") { - t.Fatal("pause/resume reason syntax drifted", help) - } - if call, ok := parseInvocation(strings.Fields(strings.TrimPrefix(help.Example, " "))); !ok || call.command == "help" || call.reviewScheduling == nil || call.reviewScheduling.action != leaf { - t.Fatal("help example does not select its real scheduling operation", leaf, call, ok) - } - } - } - } - if requests.Load() != 0 { - t.Fatal("help contacted a server") - } - if after, err := os.ReadFile(path); err != nil || !bytes.Equal(after, private) { - t.Fatal("help changed selected configuration", err) - } - parent, _ := operationHelp("reviews scheduling") - for _, leaf := range []string{"read", "configure", "pause", "resume"} { - if !strings.Contains(strings.Join(parent.Optional, " "), "reviews scheduling "+leaf+" --help") { - t.Fatal("parent help does not discover leaf", leaf) - } - } -} - -func TestReviewSchedulingLeafHelpKeepsExactGrammar(t *testing.T) { - for _, args := range [][]string{ - {"reviews", "scheduling", "resume", "--help", "extra"}, - {"reviews", "scheduling", "pause", "--help", "--pr", "42"}, - {"reviews", "scheduling", "configure", "--help=true"}, - {"reviews", "scheduling", "read", "--pr", "42", "--help"}, - {"help", "reviews", "scheduling", "unknown"}, - {"help", "reviews", "scheduling", "resume", "--key", "help-is-not-a-write"}, - {"reviews", "scheduling", "resume", "--help", "--profile=a", "--profile=b"}, - } { - var stdout, stderr bytes.Buffer - if code := RunContext(t.Context(), args, nil, &stdout, &stderr); code != ExitUsage || stdout.Len() != 0 || !strings.Contains(stderr.String(), "invalid_arguments") { - t.Fatalf("%v: code=%d stdout=%s stderr=%s", args, code, &stdout, &stderr) - } - } - call, ok := parseInvocation([]string{"reviews", "scheduling", "pause", "--pr", "42", "--expect-revision", "0", "--key", "pause-1", "--reason", "--help"}) - if !ok || call.command == "help" || call.reviewScheduling == nil || call.reviewScheduling.pause.Reason != "--help" { - t.Fatal("help-looking reason was treated as local help", call, ok) - } -} diff --git a/internal/cli/reviews.go b/internal/cli/reviews.go index e219cae48..7b375d63f 100644 --- a/internal/cli/reviews.go +++ b/internal/cli/reviews.go @@ -16,11 +16,6 @@ func parseReview(call invocation, args []string) (invocation, bool) { call.reviewOperationControl, ok = parseReviewOperationControl(args) return call, ok } - if call.subcommand == "scheduling" { - var ok bool - call.reviewScheduling, ok = parseReviewScheduling(args) - return call, ok - } if call.subcommand == "ci-wait" { var ok bool call.ciWatch, ok = parseCIWatch(args) @@ -163,9 +158,6 @@ func reviewID(value, prefix string) bool { } func executeReview(ctx context.Context, service *client.Client, call invocation) (any, error) { - if call.reviewScheduling != nil { - return executeReviewScheduling(ctx, service, call.reviewScheduling) - } if call.ciWatch != nil { value, err := service.WatchCI(ctx, call.ciWatch.targets, call.ciWatch.seconds) return client.AgentCIWatch(value), err diff --git a/internal/client/client.go b/internal/client/client.go index 5be309021..73466d8fe 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -474,9 +474,8 @@ func (c *Client) requestWithCapabilities(ctx context.Context, method string, seg defer response.Body.Close() if wait != nil && wait.queuedCause != nil { *wait.queuedCause = "" - switch cause := response.Header.Get("X-FC-Review-Queued"); cause { - case "cli_quota_wait", "pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained": - *wait.queuedCause = cause + if response.Header.Get("X-FC-Review-Queued") == "cli_quota_wait" { + *wait.queuedCause = "cli_quota_wait" } } if response.StatusCode >= 300 && response.StatusCode < 400 { diff --git a/internal/client/review_agent_output.go b/internal/client/review_agent_output.go index 1513415c5..56cf67258 100644 --- a/internal/client/review_agent_output.go +++ b/internal/client/review_agent_output.go @@ -21,12 +21,6 @@ func draftReadinessDiagnostic() *ReviewOperationDiagnostic { } func selectionSourceDiagnostic(reason string) *ReviewOperationDiagnostic { - if reason == "automation_authorization_changed" { - return &ReviewOperationDiagnostic{"This selection stopped before it created a review operation because its scheduling authorization no longer applies.", "Read review_scheduling_read / reviews scheduling. A project manager can authorize future automatic selections through an active bound worker. The retained selection records the refusal."} - } - if hint := schedulingDiagnostic(reason); hint != nil { - return hint - } if reason == "pull_draft" { return draftReadinessDiagnostic() } @@ -51,9 +45,6 @@ func selectionSourceDiagnostic(reason string) *ReviewOperationDiagnostic { default: return nil } - if reason == "source_budget_exhausted" || reason == "source_fetch_timeout" || reason == "source_provider_unavailable" { - return &ReviewOperationDiagnostic{explanation, "An explicit held selection is terminal and has no child operation; after addressing the source issue, if the review remains authorized, use one fresh reviews start / review_start with a new key and current configuration. Its old key replays the hold. An eligible automatic selection may recover on its original identity after at least thirty seconds, subject to its retained retry budget, unchanged authorization and normal admission checks. Preserve the original selection while automatic recovery remains eligible; this diagnostic does not establish eligibility or promise an exact retry time. Keep pending selections and selected child operations on their original identities. No round reset or extra grant is needed."} - } return &ReviewOperationDiagnostic{explanation, "This held selection is terminal and has no child operation. After addressing the source issue, if the review remains authorized, use one fresh reviews start / review_start with a new key and current configuration. The old key replays this hold. Keep pending selections and selected child operations on their original identities. No round reset or extra grant is needed; normal front, source and provider checks still apply."} } @@ -75,14 +66,6 @@ type ReviewOperationStatusOutput struct { } func retainedWaitDiagnostic(wait *ReviewOperationWait, channel, state, reason, queuedCause string) *ReviewOperationDiagnostic { - if state == "queued" { - if hint := schedulingDiagnostic(queuedCause); hint != nil { - return hint - } - } - if hint := agentReviewOperationDiagnostic(channel, state, reason); hint != nil { - return hint - } if wait != nil { if diagnostic := operationWaitDiagnostic(wait, channel); diagnostic != nil { return diagnostic @@ -130,12 +113,3 @@ func operationWaitDiagnostic(w *ReviewOperationWait, channel string) *ReviewOper } return nil } - -func agentReviewOperationDiagnostic(channel, state, reason string) *ReviewOperationDiagnostic { - // Queued reasons can outlive a resumed pause; only the current queued cause - // can establish a scheduling hold. Held operations retain their own reason. - if state == "held" { - return schedulingDiagnostic(reason) - } - return nil -} diff --git a/internal/client/review_agent_output_test.go b/internal/client/review_agent_output_test.go index 59a5c1a80..c3ed74e66 100644 --- a/internal/client/review_agent_output_test.go +++ b/internal/client/review_agent_output_test.go @@ -26,9 +26,6 @@ func TestAgentSelectionSourceHoldIsBoundedAndNeverReplacesChild(t *testing.T) { continue } phrases := []string{"terminal and has no child", "After addressing", "if the review remains authorized", "new key and current configuration", "old key replays", "pending selections and selected child", "No round reset or extra grant"} - if reason == "source_budget_exhausted" || reason == "source_fetch_timeout" || reason == "source_provider_unavailable" { - phrases = []string{"An explicit held selection is terminal", "if the review remains authorized", "new key and current configuration", "old key replays", "eligible automatic selection may recover on its original identity", "after at least thirty seconds", "retained retry budget", "unchanged authorization", "Preserve the original selection", "does not establish eligibility or promise an exact retry time", "No round reset or extra grant"} - } if reason == "pull_draft" { phrases = []string{"After marking the PR ready for review", "if this review remains authorized", "new key and current configuration/head", "old key replays this terminal hold", "Do not reset rounds, grant extra reviews or retry automatically", "normal admission and provider checks"} for _, phrase := range []string{"GitHub Draft", "initial review readiness", "does not erase earned review progress"} { diff --git a/internal/client/review_scheduling.go b/internal/client/review_scheduling.go deleted file mode 100644 index efecb7d58..000000000 --- a/internal/client/review_scheduling.go +++ /dev/null @@ -1,184 +0,0 @@ -package client - -import ( - "context" - "encoding/json" - "github.com/benhook1013/FireController/internal/strictjson" - "math" - "net/http" - "strconv" - "time" - "unicode" - "unicode/utf8" -) - -type ReviewScheduling struct { - ProjectID string `json:"project_id"` - Revision int64 `json:"revision"` - AutomaticCLI bool `json:"automatic_cli"` - AutomaticHosted bool `json:"automatic_hosted"` - PausedPulls []ReviewPullScheduling `json:"paused_pulls"` - AuthorizingWorkerID string `json:"authorizing_worker_id,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - Reason string `json:"reason,omitempty"` -} - -type ReviewPullScheduling 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 ConfigureReviewSchedulingRequest struct { - ExpectedRevision int64 `json:"expected_revision"` - AutomaticHosted bool `json:"automatic_hosted"` - AutomaticCLI *bool `json:"automatic_cli,omitempty"` -} - -type ConfigureReviewPullSchedulingRequest struct { - ExpectedRevision int64 `json:"expected_revision"` - Paused bool `json:"paused"` - Reason string `json:"reason,omitempty"` -} - -func validSchedulingRevision(revision int64) bool { return revision >= 0 && revision < math.MaxInt64 } -func validSchedulingTime(value string) bool { - if len(value) > 64 { - return false - } - at, err := time.Parse(time.RFC3339Nano, value) - return err == nil && !at.IsZero() -} -func validSchedulingReason(reason string) bool { - if len(reason) > 256 || !utf8.ValidString(reason) { - return false - } - for _, r := range reason { - if unicode.IsControl(r) { - return false - } - } - return true -} - -func ValidateConfigureReviewScheduling(input ConfigureReviewSchedulingRequest) error { - if !validSchedulingRevision(input.ExpectedRevision) { - return mutationValidation() - } - return nil -} - -func ValidateConfigureReviewPullScheduling(pull int64, input ConfigureReviewPullSchedulingRequest) error { - if !validPullNumber(pull) || !validSchedulingRevision(input.ExpectedRevision) || !validSchedulingReason(input.Reason) { - return mutationValidation() - } - return nil -} - -func validPullScheduling(value ReviewPullScheduling, project string, pull int64) bool { - if value.ProjectID != project || value.PullNumber != pull || !validPullNumber(pull) || value.Revision < 0 || !validSchedulingReason(value.Reason) || !value.Paused && value.Reason != "" { - return false - } - if value.Revision == 0 { - return !value.Paused && value.Reason == "" && value.ActorID == "" && value.UpdatedAt == "" - } - return validID(value.ActorID) && validSchedulingTime(value.UpdatedAt) -} - -// Older services omit automatic_cli. Accept that as off while always emitting -// an explicit boolean in CLI/MCP output, including after an enabled read. -func decodeReviewSchedulingResponse(data []byte, dst any) error { - if err := strictjson.Decode(data, dst); err != nil { - return err - } - var fields map[string]json.RawMessage - if err := json.Unmarshal(data, &fields); err != nil || fields == nil { - return strictjson.ErrSyntax - } - if _, present := fields["automatic_cli"]; !present { - fields["automatic_cli"] = json.RawMessage("false") - var err error - data, err = json.Marshal(fields) - if err != nil { - return err - } - } - if !completeShape(data, dst) { - return strictjson.ErrSyntax - } - return nil -} - -func (c *Client) ReviewScheduling(ctx context.Context) (ReviewScheduling, error) { - // Allow 100 paused pulls, including six-byte JSON escaping of each - // 256-byte reason and bounded identities, plus the response envelope. - var value ReviewScheduling - if err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "scheduling"), nil, true, "", nil, http.StatusOK, false, &value, 512<<10, decodeReviewSchedulingResponse); err != nil { - return ReviewScheduling{}, err - } - if value.ProjectID != c.identity.ProjectID || value.Revision < 0 || value.PausedPulls == nil || len(value.PausedPulls) > 100 || value.Reason != "" && !safeCode(value.Reason) || value.AuthorizingWorkerID != "" && !validID(value.AuthorizingWorkerID) { - return ReviewScheduling{}, invalidResponse() - } - if value.Revision == 0 { - if value.AutomaticHosted || value.AutomaticCLI || value.AuthorizingWorkerID != "" || value.UpdatedAt != "" || value.Reason != "" { - return ReviewScheduling{}, invalidResponse() - } - } else if !validSchedulingTime(value.UpdatedAt) || (value.AutomaticHosted || value.AutomaticCLI) && value.AuthorizingWorkerID == "" { - return ReviewScheduling{}, invalidResponse() - } - seen := make(map[int64]bool, len(value.PausedPulls)) - for _, item := range value.PausedPulls { - if !item.Paused || seen[item.PullNumber] || !validPullScheduling(item, c.identity.ProjectID, item.PullNumber) { - return ReviewScheduling{}, invalidResponse() - } - seen[item.PullNumber] = true - } - return value, nil -} - -func (c *Client) ConfigureReviewScheduling(ctx context.Context, key string, input ConfigureReviewSchedulingRequest) (ReviewRequestReceipt, error) { - if !validMutationKey(key) || ValidateConfigureReviewScheduling(input) != nil { - return ReviewRequestReceipt{}, mutationValidation() - } - var receipt ReviewRequestReceipt - if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "scheduling"), key, input, http.StatusOK, &receipt); err != nil { - return receipt, err - } - if receipt.ID != c.identity.ProjectID || receipt.State != "scheduling_configured" || receipt.Revision != input.ExpectedRevision+1 { - return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The scheduling receipt was invalid; retain the original key and request.", http.StatusOK) - } - return receipt, nil -} - -func (c *Client) ReviewPullScheduling(ctx context.Context, pull int64) (ReviewPullScheduling, error) { - if !validPullNumber(pull) { - return ReviewPullScheduling{}, validation() - } - var value ReviewPullScheduling - if err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "pulls", strconv.FormatInt(pull, 10), "scheduling"), nil, true, "", nil, http.StatusOK, false, &value, 4<<10, decodeResponse); err != nil { - return ReviewPullScheduling{}, err - } - if !validPullScheduling(value, c.identity.ProjectID, pull) { - return ReviewPullScheduling{}, invalidResponse() - } - return value, nil -} - -func (c *Client) ConfigureReviewPullScheduling(ctx context.Context, key string, pull int64, input ConfigureReviewPullSchedulingRequest) (ReviewRequestReceipt, error) { - if !validMutationKey(key) || ValidateConfigureReviewPullScheduling(pull, input) != nil { - return ReviewRequestReceipt{}, mutationValidation() - } - var receipt ReviewRequestReceipt - id := strconv.FormatInt(pull, 10) - if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "pulls", id, "scheduling"), key, input, http.StatusOK, &receipt); err != nil { - return receipt, err - } - if receipt.ID != id || receipt.State != "pull_scheduling_updated" || receipt.Revision != input.ExpectedRevision+1 { - return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The PR scheduling receipt was invalid; retain the original key and request.", http.StatusOK) - } - return receipt, nil -} diff --git a/internal/client/review_scheduling_diagnostic.go b/internal/client/review_scheduling_diagnostic.go deleted file mode 100644 index cfe1b600a..000000000 --- a/internal/client/review_scheduling_diagnostic.go +++ /dev/null @@ -1,13 +0,0 @@ -package client - -func schedulingDiagnostic(reason string) *ReviewOperationDiagnostic { - switch reason { - case "pull_scheduling_paused": - return &ReviewOperationDiagnostic{"New reviews are paused for this PR; this is separate from an individual operation pause. Already issued reviews can still be collected.", "Read review_pull_scheduling_read / reviews scheduling read --pr N. Resume the PR only when authorized. Existing queued work retains its identity and any separate operation pause; a terminal held operation does not resume. Do not reset rounds or grant more reviews to clear this pause."} - case "automation_authorization_changed": - return &ReviewOperationDiagnostic{"Automatic scheduling for this channel is off, its authorization was interrupted, or its retained authorizer no longer has the required access. This retained selection/request cannot authorize provider work.", "Read review_scheduling_read / reviews scheduling. Re-enabling scheduling does not resume an operation whose channel authorization was interrupted. Inspect this retained operation before making a new authorized request. An authorized project manager can deliberately enable scheduling for new work with its current credential and active bound worker. Keep existing issued work on its original identity; do not switch another worker's credentials or reset rounds."} - case "automatic_intent_retained": - return &ReviewOperationDiagnostic{"An automatic review intent already exists for these same review facts; this selection did not create another provider request.", "Inspect existing scoped operations if needed. Ticks and observation refreshes do not restart cancelled, failed or held intent. Use a PR pause to prevent new scheduling across later meaningful changes. A separate explicit request still needs normal authorization and admission."} - } - return nil -} diff --git a/internal/client/review_scheduling_diagnostic_test.go b/internal/client/review_scheduling_diagnostic_test.go deleted file mode 100644 index 745f3fd33..000000000 --- a/internal/client/review_scheduling_diagnostic_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package client - -import ( - "reflect" - "strings" - "testing" -) - -func TestSchedulingDiagnosticsPreserveRetainedFacts(t *testing.T) { - for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { - v := ReviewOperationStatus{ID: "original", State: "held", Stage: "held", Reason: reason, Channel: "hosted", Revision: 3, NextAction: "read_diagnostics"} - out := AgentReviewOperationStatus(v) - if out.Diagnostic == nil || !reflect.DeepEqual(out.ReviewOperationStatus, v) || selectionSourceDiagnostic(reason) == nil { - t.Fatal("missing scheduling diagnostic or changed original facts", reason) - } - if agentReviewOperationDiagnostic("hosted", "active", reason) != nil { - t.Fatal("issued work gained scheduling refusal", reason) - } - } - if schedulingDiagnostic("unknown") != nil { - t.Fatal("invented scheduling refusal") - } -} - -func TestSchedulingDiagnosticsDoNotMislabelCLIAsHosted(t *testing.T) { - for _, reason := range []string{"automation_authorization_changed", "automatic_intent_retained"} { - value := AgentReviewOperationStatus(ReviewOperationStatus{State: "held", Stage: "held", Reason: reason, Channel: "cli", Revision: 1}) - if value.Diagnostic == nil || strings.Contains(value.Diagnostic.Explanation, "Hosted") { - t.Fatal("CLI refusal was attributed to the other channel", value) - } - } -} - -func TestQueuedSchedulingDiagnosticsUseCurrentCause(t *testing.T) { - const due = "2026-11-11T12:00:00Z" - for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { - for _, channel := range []string{"cli", "hosted"} { - for _, tc := range []struct { - name, cause, explanation, action string - wait *ReviewOperationWait - }{ - {name: "awaiting_scheduler", cause: "awaiting_scheduler"}, - {name: "queue_order", cause: "queue_order"}, - {name: "absent_cause"}, - {name: "unknown_cause", cause: "unknown"}, - {name: "cooldown", cause: "cooldown", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, - {name: "queue_order_with_timer", cause: "queue_order", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, - {name: "quota_with_timer", cause: "cli_quota_wait", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "retry_not_before", action: "Keep this"}, - {name: "operation_pause", cause: "operation_paused", wait: &ReviewOperationWait{Paused: true}, explanation: "no retry deadline is recorded", action: "Resume/cancel only this undispatched operation"}, - {name: "operation_pause_with_timer", cause: "operation_paused", wait: &ReviewOperationWait{Paused: true, RetryNotBefore: due}, explanation: "paused before", action: "Resume"}, - {name: "current_pr_pause", cause: "pull_scheduling_paused", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "New reviews are paused for this PR", action: "Resume the PR only when authorized"}, - {name: "current_authorization_hold", cause: "automation_authorization_changed", wait: &ReviewOperationWait{RetryNotBefore: due}, explanation: "Automatic scheduling for this channel is off", action: "An authorized project manager"}, - {name: "current_retained_intent", cause: "automatic_intent_retained", explanation: "An automatic review intent already exists", action: "Inspect existing scoped operations"}, - {name: "quota_without_timer", cause: "cli_quota_wait"}, - } { - t.Run(channel+"/"+reason+"/"+tc.name, func(t *testing.T) { - explanation, action := tc.explanation, tc.action - if tc.name == "quota_without_timer" && channel == "cli" { - explanation, action = "queued for shared CLI quota rechecks", "Keep this original request queued" - } - operation := ReviewOperation{ID: "original", State: "queued", Reason: reason, Channel: channel, Revision: 3, Wait: tc.wait, queuedCause: tc.cause} - status := ReviewOperationStatus{ID: operation.ID, State: operation.State, Stage: "queued", Reason: reason, Channel: channel, Revision: operation.Revision, Wait: tc.wait, queuedCause: tc.cause, NextAction: "wait"} - full, compact := AgentReviewOperation(operation), AgentReviewOperationStatus(status) - if !reflect.DeepEqual(full.ReviewOperation, operation) || !reflect.DeepEqual(compact.ReviewOperationStatus, status) || !reflect.DeepEqual(full.Diagnostic, compact.Diagnostic) { - t.Fatal("wrappers changed retained facts or disagree", full, compact) - } - if explanation == "" { - if full.Diagnostic != nil { - t.Fatal("historical reason invented a current scheduling hold", full.Diagnostic) - } - return - } - if full.Diagnostic == nil || !strings.Contains(full.Diagnostic.Explanation, explanation) || !strings.Contains(full.Diagnostic.NextAction, action) { - t.Fatal("current cause or retained operation wait guidance was masked", explanation, action, full.Diagnostic) - } - }) - } - } - } -} - -func TestHeldSchedulingDiagnosticsIgnoreQueuedCause(t *testing.T) { - for _, channel := range []string{"cli", "hosted"} { - for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_intent_retained"} { - operation := ReviewOperation{State: "held", Channel: channel, Reason: reason, queuedCause: "cooldown"} - status := ReviewOperationStatus{State: "held", Stage: "held", Channel: channel, Reason: reason, queuedCause: "cooldown", NextAction: "read_diagnostics"} - full, compact := AgentReviewOperation(operation), AgentReviewOperationStatus(status) - if !reflect.DeepEqual(full.Diagnostic, schedulingDiagnostic(reason)) || !reflect.DeepEqual(compact.Diagnostic, full.Diagnostic) || !reflect.DeepEqual(full.ReviewOperation, operation) || !reflect.DeepEqual(compact.ReviewOperationStatus, status) { - t.Fatal("held scheduling guidance or retained facts changed", full, compact) - } - } - } -} - -func TestSchedulingDiagnosticExplainsInterruptedAuthorization(t *testing.T) { - diagnostic := schedulingDiagnostic("automation_authorization_changed") - for _, want := range []string{"Re-enabling scheduling does not resume", "Inspect this retained operation", "new authorized request", "original identity"} { - if diagnostic == nil || !strings.Contains(diagnostic.NextAction, want) { - t.Fatalf("missing continuity guidance %q: %+v", want, diagnostic) - } - } - if strings.Contains(diagnostic.Explanation, "Automatic Hosted") { - t.Fatal("shared authorization diagnostic excluded CLI") - } -} diff --git a/internal/client/review_scheduling_test.go b/internal/client/review_scheduling_test.go deleted file mode 100644 index 8c3b008d1..000000000 --- a/internal/client/review_scheduling_test.go +++ /dev/null @@ -1,434 +0,0 @@ -package client_test - -import ( - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "io" - "math" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "sync/atomic" - "testing" - - "github.com/benhook1013/FireController/internal/client" - "github.com/benhook1013/FireController/internal/reviewexec" - "github.com/benhook1013/FireController/internal/reviews" -) - -func TestReviewSchedulingClientActualHTTPControlsDoNotStartWork(t *testing.T) { - f := newMutationFixture(t) - for _, ensure := range []func() error{ - func() error { return reviewexec.EnsureSchema(t.Context(), f.store) }, - func() error { return reviews.EnsureSchema(t.Context(), f.store) }, - } { - if err := ensure(); err != nil { - t.Fatal(err) - } - } - e, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "scheduling-client", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}) - if err != nil { - t.Fatal(err) - } - mux := http.NewServeMux() - mux.Handle("/", f.handler) - e.Register(mux) - f.handler = mux - var requests atomic.Int64 - service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests.Add(1); f.handler.ServeHTTP(w, r) })) - defer service.Close() - grant := func(token string, permissions []string) string { - sum := sha256.Sum256([]byte(token)) - return f.call(t, "POST", "/api/v1/projects/"+f.project+"/credentials", f.admin, f.sender, map[string]any{"token_sha256": hex.EncodeToString(sum[:]), "permissions": permissions})["id"].(string) - } - const ownerToken = "synthetic-scheduling-owner" - ownerID := grant(ownerToken, []string{"manage"}) - grant("synthetic-scheduling-writer", []string{"read", "write"}) - grant("synthetic-scheduling-reader", []string{"read"}) - owner := f.newClient(t, ownerToken, f.sender, service.URL) - writer := f.newClient(t, "synthetic-scheduling-writer", f.sender, service.URL) - reader := f.newClient(t, "synthetic-scheduling-reader", f.sender, service.URL) - providerCalls := f.providerCalls.Load() - initial, err := reader.ReviewScheduling(t.Context()) - if err != nil || initial.Revision != 0 || initial.AutomaticHosted || initial.PausedPulls == nil || len(initial.PausedPulls) != 0 || initial.Reason != "" { - t.Fatal(initial, err) - } - pull, err := reader.ReviewPullScheduling(t.Context(), 2) - if err != nil || pull.Revision != 0 || pull.Paused || pull.ProjectID != f.project || pull.PullNumber != 2 { - t.Fatal(pull, err) - } - paused := client.ConfigureReviewPullSchedulingRequest{Paused: true, Reason: "Fix in progress"} - first, err := writer.ConfigureReviewPullScheduling(t.Context(), "pause-before-intent", 2, paused) - if err != nil || first.ID != "2" || first.Revision != 1 { - t.Fatal(first, err) - } - replay, err := writer.ConfigureReviewPullScheduling(t.Context(), "pause-before-intent", 2, paused) - if err != nil || !reflect.DeepEqual(first, replay) { - t.Fatal("pause replay changed", first, replay, err) - } - _, err = writer.ConfigureReviewPullScheduling(t.Context(), "stale-pause", 2, paused) - checkError(t, err, "review_conflict") - _, err = reader.ConfigureReviewPullScheduling(t.Context(), "reader-pause", 2, paused) - checkError(t, err, "forbidden") - _, err = writer.ConfigureReviewPullScheduling(t.Context(), "pause-outside-queue", 99, paused) - if err != nil { - t.Fatal(err) - } - configuration := client.ConfigureReviewExecutionRequest{CapabilityID: "scheduling-client", Mode: "independent", Queue: []int64{2, 4}, Channels: []string{"cli", "hosted"}} - f.call(t, "POST", "/api/v1/projects/"+f.project+"/reviews/execution/configuration", f.admin, f.sender, configuration) - before := requests.Load() - filtered, err := reader.ReviewScheduling(t.Context()) - if err != nil || requests.Load() != before+1 || len(filtered.PausedPulls) != 1 || filtered.PausedPulls[0].PullNumber != 2 || !filtered.PausedPulls[0].Paused || filtered.PausedPulls[0].Reason != paused.Reason { - t.Fatal("project GET lost queue-filtered pauses or added per-PR requests", filtered, err) - } - enable := client.ConfigureReviewSchedulingRequest{AutomaticHosted: true} - _, err = writer.ConfigureReviewScheduling(t.Context(), "writer-enable", enable) - checkError(t, err, "forbidden") - enabled, err := owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) - if err != nil || enabled.ID != f.project || enabled.Revision != 1 { - t.Fatal(enabled, err) - } - again, err := owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) - if err != nil || !reflect.DeepEqual(enabled, again) { - t.Fatal("enable replay changed", again, err) - } - _, err = owner.ConfigureReviewScheduling(t.Context(), "stale-enable", enable) - checkError(t, err, "review_conflict") - current, err := reader.ReviewScheduling(t.Context()) - if err != nil || !current.AutomaticHosted || current.Revision != 1 || current.AuthorizingWorkerID != f.sender || current.Reason != "" { - t.Fatal(current, err) - } - _, err = writer.ConfigureReviewPullScheduling(t.Context(), "writer-resume", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: 1, Paused: false, Reason: "discard on resume"}) - if err != nil { - t.Fatal(err) - } - resumed, err := reader.ReviewPullScheduling(t.Context(), 2) - if err != nil || resumed.Paused || resumed.Revision != 2 || resumed.Reason != "" { - t.Fatal(resumed, err) - } - if _, err := f.store.DB().Exec(`UPDATE credentials SET revoked=1 WHERE id=?`, ownerID); err != nil { - t.Fatal(err) - } - withdrawn, err := reader.ReviewScheduling(t.Context()) - if err != nil || !withdrawn.AutomaticHosted || withdrawn.Reason != "authorizer_unavailable" || withdrawn.AuthorizingWorkerID != f.sender || len(withdrawn.PausedPulls) != 0 { - t.Fatal("withdrawn original authorization was not reported truthfully", withdrawn, err) - } - _, err = owner.ConfigureReviewScheduling(t.Context(), "owner-enable", enable) - checkError(t, err, "unauthorized") - for _, table := range []string{"review_operations", "review_execution_attempts", "review_execution_reservations", "review_execution_evidence", "review_round_completions", "review_selections", "review_automatic_selections"} { - var count int - if err := f.store.DB().QueryRow(`SELECT count(*) FROM ` + table).Scan(&count); err != nil || count != 0 { - t.Fatal("settings handler started or credited review work", table, count, err) - } - } - if f.providerCalls.Load() != providerCalls { - t.Fatal("settings/read/pause contacted a provider") - } -} - -func TestReviewSchedulingClientRejectsMalformedWireAndKeepsUnknownMutationsSingleShot(t *testing.T) { - var response atomic.Value - response.Store(`{"project_id":"project-one","revision":0,"automatic_hosted":false,"paused_pulls":[]}`) - var calls atomic.Int64 - service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/api/v1/instance" { - handshake(w) - return - } - calls.Add(1) - w.Header().Set("Content-Type", "application/json") - if r.Method == "POST" { - body, _ := io.ReadAll(r.Body) - want := `{"expected_revision":0,"automatic_hosted":true}` - if strings.Contains(r.URL.Path, "/pulls/2/") { - want = `{"expected_revision":0,"paused":true}` - } - if r.Header.Get("Idempotency-Key") != "original-scheduling-key" || r.Header.Get("X-FC-Worker") != "worker-one" || r.Header.Get("X-FC-Instance") != "instance-one" || string(body) != want { - t.Error("mutation lost original key/body/binding") - } - } - _, _ = io.WriteString(w, response.Load().(string)) - })) - defer service.Close() - c := newClient(t, service) - defaultProject := map[string]any{"project_id": "project-one", "revision": 0, "automatic_hosted": false, "paused_pulls": []any{}} - validPaused := map[string]any{"project_id": "project-one", "pull_number": 2, "revision": 1, "paused": true, "reason": "Fixing", "actor_id": "actor-one", "updated_at": "2026-11-01T00:00:00Z"} - // Exhausted stored revisions remain readable; only another increment is - // invalid. Keep the largest legitimate native int64 exact on the wire. - maxProject := map[string]any{} - for key, value := range defaultProject { - maxProject[key] = value - } - maxProject["revision"], maxProject["updated_at"] = int64(math.MaxInt64), "2026-11-01T00:00:00Z" - encoded, _ := json.Marshal(maxProject) - response.Store(string(encoded)) - projectAtLimit, err := c.ReviewScheduling(t.Context()) - if err != nil || projectAtLimit.Revision != math.MaxInt64 { - t.Fatal("exhausted project revision became unreadable", projectAtLimit, err) - } - maxPull := map[string]any{} - for key, value := range validPaused { - maxPull[key] = value - } - maxPull["revision"] = int64(math.MaxInt64) - encoded, _ = json.Marshal(maxPull) - response.Store(string(encoded)) - pullAtLimit, err := c.ReviewPullScheduling(t.Context(), 2) - if err != nil || pullAtLimit.Revision != math.MaxInt64 { - t.Fatal("exhausted PR revision became unreadable", pullAtLimit, err) - } - for _, tc := range []struct { - name string - change func(map[string]any) - }{ - {"project-binding", func(v map[string]any) { v["project_id"] = "another-project" }}, - {"missing-paused-array", func(v map[string]any) { delete(v, "paused_pulls") }}, - {"null-paused-array", func(v map[string]any) { v["paused_pulls"] = nil }}, - {"duplicate-paused", func(v map[string]any) { v["paused_pulls"] = []any{validPaused, validPaused} }}, - {"default-enabled", func(v map[string]any) { v["automatic_hosted"] = true }}, - {"default-dated", func(v map[string]any) { v["updated_at"] = "2026-11-01T00:00:00Z" }}, - {"negative-revision", func(v map[string]any) { v["revision"] = -1 }}, - {"fractional-revision", func(v map[string]any) { v["revision"] = 1.5 }}, - {"bad-date", func(v map[string]any) { v["revision"] = 1; v["updated_at"] = "PRIVATE_INVALID_DATE" }}, - {"zero-date", func(v map[string]any) { v["revision"] = 1; v["updated_at"] = "0001-01-01T00:00:00Z" }}, - {"oversized-date", func(v map[string]any) { - v["revision"] = 1 - v["updated_at"] = "2026-11-01T00:00:00." + strings.Repeat("1", 50) + "Z" - }}, - } { - t.Run(tc.name, func(t *testing.T) { - v := map[string]any{} - for k, x := range defaultProject { - v[k] = x - } - tc.change(v) - b, _ := json.Marshal(v) - response.Store(string(b)) - _, err := c.ReviewScheduling(t.Context()) - checkError(t, err, "invalid_response", "PRIVATE_INVALID_DATE") - }) - } - for _, tc := range []struct{ name, timestamp string }{ - {"offset", "2026-11-01T05:30:00+05:30"}, - {"redundant-precision", "2026-11-01T00:00:00.000000000Z"}, - } { - t.Run("project-valid-date-"+tc.name, func(t *testing.T) { - v := map[string]any{} - for k, x := range defaultProject { - v[k] = x - } - v["revision"], v["updated_at"] = 1, tc.timestamp - b, _ := json.Marshal(v) - response.Store(string(b)) - if _, err := c.ReviewScheduling(t.Context()); err != nil { - t.Fatalf("valid RFC3339Nano timestamp %q was rejected: %v", tc.timestamp, err) - } - }) - } - for _, tc := range []struct { - name string - change func(map[string]any) - }{ - {"project-binding", func(v map[string]any) { v["project_id"] = "another-project" }}, - {"pull-binding", func(v map[string]any) { v["pull_number"] = 4 }}, - {"default-paused", func(v map[string]any) { v["revision"] = 0 }}, - {"missing-actor", func(v map[string]any) { delete(v, "actor_id") }}, - {"unpaused-reason", func(v map[string]any) { v["paused"] = false }}, - {"bad-date", func(v map[string]any) { v["updated_at"] = "PRIVATE_INVALID_DATE" }}, - {"zero-date", func(v map[string]any) { v["updated_at"] = "0001-01-01T00:00:00Z" }}, - } { - t.Run("pull-"+tc.name, func(t *testing.T) { - v := map[string]any{} - for k, x := range validPaused { - v[k] = x - } - tc.change(v) - b, _ := json.Marshal(v) - response.Store(string(b)) - _, err := c.ReviewPullScheduling(t.Context(), 2) - checkError(t, err, "invalid_response") - }) - } - for _, tc := range []struct{ name, timestamp string }{ - {"offset", "2026-11-01T05:30:00+05:30"}, - {"redundant-precision", "2026-11-01T00:00:00.000000000Z"}, - } { - t.Run("pull-valid-date-"+tc.name, func(t *testing.T) { - v := map[string]any{} - for k, x := range validPaused { - v[k] = x - } - v["updated_at"] = tc.timestamp - b, _ := json.Marshal(v) - response.Store(string(b)) - if _, err := c.ReviewPullScheduling(t.Context(), 2); err != nil { - t.Fatalf("valid RFC3339Nano timestamp %q was rejected: %v", tc.timestamp, err) - } - }) - } - for _, pull := range []bool{false, true} { - body := `{"id":"wrong-target","state":"scheduling_configured","revision":1}` - if pull { - body = `{"id":"4","state":"pull_scheduling_updated","revision":1}` - } - response.Store(body) - before := calls.Load() - var err error - if pull { - _, err = c.ConfigureReviewPullScheduling(t.Context(), "original-scheduling-key", 2, client.ConfigureReviewPullSchedulingRequest{Paused: true}) - } else { - _, err = c.ConfigureReviewScheduling(t.Context(), "original-scheduling-key", client.ConfigureReviewSchedulingRequest{AutomaticHosted: true}) - } - checkError(t, err, "invalid_response") - var unknown *client.Error - if !errors.As(err, &unknown) || !unknown.OutcomeUnknown || calls.Load() != before+1 { - t.Fatal("invalid mutation receipt lost uncertainty or retried", err) - } - } -} - -func TestReviewSchedulingClientLocalValidationNeedsNoConnection(t *testing.T) { - c := &client.Client{} - for _, invoke := range []func() error{ - func() error { _, err := c.ReviewPullScheduling(t.Context(), 0); return err }, - func() error { - _, err := c.ConfigureReviewScheduling(t.Context(), "", client.ConfigureReviewSchedulingRequest{}) - return err - }, - func() error { - _, err := c.ConfigureReviewScheduling(t.Context(), "key", client.ConfigureReviewSchedulingRequest{ExpectedRevision: -1}) - return err - }, - func() error { - _, err := c.ConfigureReviewScheduling(t.Context(), "key", client.ConfigureReviewSchedulingRequest{ExpectedRevision: math.MaxInt64}) - return err - }, - func() error { - _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2147483648, client.ConfigureReviewPullSchedulingRequest{}) - return err - }, - func() error { - _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: -1}) - return err - }, - func() error { - _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: math.MaxInt64}) - return err - }, - func() error { - _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: "line\nbreak"}) - return err - }, - func() error { - _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: strings.Repeat("a", 257)}) - return err - }, - func() error { - _, err := c.ConfigureReviewPullScheduling(t.Context(), "key", 2, client.ConfigureReviewPullSchedulingRequest{Reason: string([]byte{255})}) - return err - }, - } { - if err := invoke(); err == nil { - t.Fatal("invalid local input reached the unconfigured connection") - } - } -} - -func TestSchedulingOptionalCLIWireContract(t *testing.T) { - for _, state := range []string{"omitted", "true", "false"} { - request := client.ConfigureReviewSchedulingRequest{AutomaticHosted: true} - want := `{"expected_revision":0,"automatic_hosted":true` - if state != "omitted" { - enabled := state == "true" - request.AutomaticCLI = &enabled - want += `,"automatic_cli":` + state - } - encoded, err := json.Marshal(request) - if err != nil || string(encoded) != want+"}" { - t.Fatalf("wrong optional CLI body: %s %v", encoded, err) - } - } - var response string - service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/api/v1/instance" { - handshake(w) - return - } - w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, response) - })) - defer service.Close() - c := newClient(t, service) - for _, tc := range []struct { - body string - valid, enabled bool - }{ - {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"paused_pulls":[]}`, true, false}, - {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[]}`, false, false}, - {`{"project_id":"project-one","revision":0,"automatic_hosted":false,"automatic_cli":null,"paused_pulls":[]}`, false, false}, - {`{"project_id":"project-one","revision":1,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[],"updated_at":"2026-11-01T00:00:00Z"}`, false, false}, - {`{"project_id":"project-one","revision":1,"automatic_hosted":false,"automatic_cli":true,"paused_pulls":[],"updated_at":"2026-11-01T00:00:00Z","authorizing_worker_id":"worker-one"}`, true, true}, - } { - response = tc.body - value, err := c.ReviewScheduling(t.Context()) - if (err == nil) != tc.valid || tc.valid && value.AutomaticCLI != tc.enabled { - t.Fatalf("wrong scheduling validation: %+v %v", value, err) - } - } -} - -func TestReviewSchedulingClientReadsMaximumEscapedPausedQueue(t *testing.T) { - project := strings.Repeat("<", 128) - value := client.ReviewScheduling{ - ProjectID: project, Revision: math.MaxInt64, AutomaticHosted: true, AutomaticCLI: true, - AuthorizingWorkerID: strings.Repeat("&", 128), UpdatedAt: "2026-11-01T00:00:00.999999999+05:30", - PausedPulls: make([]client.ReviewPullScheduling, 100), - } - for i := range value.PausedPulls { - value.PausedPulls[i] = client.ReviewPullScheduling{ - ProjectID: project, PullNumber: 2147483647 - int64(i), Revision: math.MaxInt64, Paused: true, - Reason: strings.Repeat("<", 256), ActorID: strings.Repeat(">", 128), UpdatedAt: value.UpdatedAt, - } - } - encoded, err := json.Marshal(value) - if err != nil || len(encoded) <= 256<<10 { - t.Fatalf("fixture must exercise escaped reasons and maximum identities: bytes=%d err=%v", len(encoded), err) - } - var response atomic.Value - response.Store(encoded) - var calls atomic.Int64 - service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/api/v1/instance" { - handshake(w) - return - } - calls.Add(1) - if r.Method != http.MethodGet || r.URL.Path != "/api/v1/projects/"+project+"/reviews/scheduling" { - t.Error("scheduling read changed scope or method") - } - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write(response.Load().([]byte)) - })) - defer service.Close() - selected := binding(t, service.URL) - selected.Context.ProjectID = project - c, err := client.New(t.Context(), selected) - if err != nil { - t.Fatal(err) - } - defer c.Close() - got, err := c.ReviewScheduling(t.Context()) - if err != nil || !reflect.DeepEqual(got, value) || calls.Load() != 1 { - t.Fatalf("valid maximum escaped scheduling response failed: calls=%d err=%v", calls.Load(), err) - } - // Retain a finite wire bound even for an otherwise valid response. - response.Store(append(append([]byte(nil), encoded...), []byte(strings.Repeat(" ", 512<<10))...)) - _, err = c.ReviewScheduling(t.Context()) - checkError(t, err, "invalid_response") - if calls.Load() != 2 { - t.Fatal("oversized scheduling read retried", calls.Load()) - } -} diff --git a/internal/mcpadapter/adapter_test.go b/internal/mcpadapter/adapter_test.go index a29929db2..1033e368f 100644 --- a/internal/mcpadapter/adapter_test.go +++ b/internal/mcpadapter/adapter_test.go @@ -242,8 +242,6 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { expected["review_obligation_resolve"] = true expected["review_queue_edit"] = true expected["review_operation_control"] = true - expected["review_scheduling_read"], expected["review_scheduling_configure"] = true, true - expected["review_pull_scheduling_read"], expected["review_pull_scheduling_update"] = true, true expected["wait_for_ci"] = true expected["review_rounds_read"], expected["review_rounds_configure"] = true, true expected["review_start"], expected["review_selection_read"] = true, true @@ -269,7 +267,6 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { writes["review_obligation_resolve"] = true writes["review_rounds_configure"] = true writes["review_operation_control"] = true - writes["review_scheduling_configure"], writes["review_pull_scheduling_update"] = true, true writes["job_primary_replace"] = true writes["map_entry_create"], writes["map_entry_replace"], writes["job_workstream_replace"] = true, true, true writes["worker_pause_replace"] = true @@ -289,7 +286,7 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { } delete(expected, tool.Name) a := tool.Annotations - if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update" || tool.Name == "review_operation_control" || tool.Name == "review_policy_configure" || tool.Name == "review_execution_configure" || tool.Name == "worker_retire" || tool.Name == "project_credential_update" || tool.Name == "project_credential_revoke" || tool.Name == "presentation_replace" || tool.Name == "publication_apply" || tool.Name == "publication_unpublish" || tool.Name == "review_import_apply" || tool.Name == "review_transfer_apply" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "review_pull_scheduling_update" || tool.Name == "review_scheduling_configure" || tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { + if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_operation_control" || tool.Name == "review_policy_configure" || tool.Name == "review_execution_configure" || tool.Name == "worker_retire" || tool.Name == "project_credential_update" || tool.Name == "project_credential_revoke" || tool.Name == "presentation_replace" || tool.Name == "publication_apply" || tool.Name == "publication_unpublish" || tool.Name == "review_import_apply" || tool.Name == "review_transfer_apply" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { t.Fatal("untruthful operation annotation") } data, _ := json.Marshal(tool.InputSchema) diff --git a/internal/mcpadapter/arguments.go b/internal/mcpadapter/arguments.go index f116fd643..5554bf7b8 100644 --- a/internal/mcpadapter/arguments.go +++ b/internal/mcpadapter/arguments.go @@ -63,9 +63,6 @@ func invalidArguments() *Diagnostic { } func parseArguments(name string, data json.RawMessage) (arguments, error) { - if reviewSchedulingTool(name) { - return reviewSchedulingArguments(name, data) - } if name == "wait_for_ci" { return ciWatchArguments(data) } diff --git a/internal/mcpadapter/review_scheduling.go b/internal/mcpadapter/review_scheduling.go deleted file mode 100644 index 91d984b57..000000000 --- a/internal/mcpadapter/review_scheduling.go +++ /dev/null @@ -1,108 +0,0 @@ -package mcpadapter - -import ( - "bytes" - "encoding/json" - "math" - - "github.com/benhook1013/FireController/internal/client" - "github.com/benhook1013/FireController/internal/strictjson" -) - -func reviewSchedulingWrite(name string) bool { - return name == "review_scheduling_configure" || name == "review_pull_scheduling_update" -} - -func reviewSchedulingTool(name string) bool { - return reviewSchedulingWrite(name) || name == "review_scheduling_read" || name == "review_pull_scheduling_read" -} - -func reviewSchedulingArguments(name string, raw json.RawMessage) (arguments, error) { - var args arguments - if len(raw) == 0 { - raw = []byte("{}") - } - trimmed := bytes.TrimSpace(raw) - if len(raw) > 4096 || len(trimmed) < 2 || trimmed[0] != '{' || trimmed[len(trimmed)-1] != '}' { - return args, invalidArguments() - } - if name == "review_scheduling_read" { - var empty struct{} - if strictjson.Decode(raw, &empty) != nil { - return args, invalidArguments() - } - return args, nil - } - if name == "review_pull_scheduling_read" { - var wire struct { - PullNumber int64 `json:"pull_number"` - } - if strictjson.Decode(raw, &wire) != nil || wire.PullNumber < 1 || wire.PullNumber > 2147483647 { - return args, invalidArguments() - } - args.pullNumber = wire.PullNumber - return args, nil - } - if name == "review_scheduling_configure" { - var wire struct { - Revision *int64 `json:"expected_revision"` - Enabled *bool `json:"automatic_hosted"` - CLI *bool `json:"automatic_cli,omitempty"` - Key string `json:"idempotency_key"` - } - if strictjson.Decode(raw, &wire) != nil || wire.Revision == nil || wire.Enabled == nil || !client.ValidMutationKey(wire.Key) { - return args, invalidArguments() - } - var present map[string]json.RawMessage - if json.Unmarshal(raw, &present) != nil || present["automatic_cli"] != nil && wire.CLI == nil { - return args, invalidArguments() - } - args.key = wire.Key - args.reviewScheduling = client.ConfigureReviewSchedulingRequest{ExpectedRevision: *wire.Revision, AutomaticHosted: *wire.Enabled, AutomaticCLI: wire.CLI} - if client.ValidateConfigureReviewScheduling(args.reviewScheduling) != nil { - return arguments{}, invalidArguments() - } - return args, nil - } - var wire struct { - PullNumber int64 `json:"pull_number"` - Revision *int64 `json:"expected_revision"` - Paused *bool `json:"paused"` - Reason *string `json:"reason,omitempty"` - Key string `json:"idempotency_key"` - } - if name != "review_pull_scheduling_update" || strictjson.Decode(raw, &wire) != nil || wire.Revision == nil || wire.Paused == nil || !client.ValidMutationKey(wire.Key) { - return args, invalidArguments() - } - var present map[string]json.RawMessage - if json.Unmarshal(raw, &present) != nil || present["reason"] != nil && (wire.Reason == nil || !*wire.Paused) { - return args, invalidArguments() - } - args.key, args.pullNumber = wire.Key, wire.PullNumber - args.reviewPullScheduling = client.ConfigureReviewPullSchedulingRequest{ExpectedRevision: *wire.Revision, Paused: *wire.Paused} - if wire.Reason != nil { - args.reviewPullScheduling.Reason = *wire.Reason - } - if client.ValidateConfigureReviewPullScheduling(args.pullNumber, args.reviewPullScheduling) != nil { - return arguments{}, invalidArguments() - } - return args, nil -} - -func reviewSchedulingDefinitions() []definition { - object := func(properties map[string]any, required ...string) map[string]any { - if required == nil { - required = []string{} - } - return map[string]any{"type": "object", "additionalProperties": false, "properties": properties, "required": required} - } - revision := map[string]any{"type": "integer", "minimum": 0, "maximum": int64(math.MaxInt64 - 1)} - pull := map[string]any{"type": "integer", "minimum": 1, "maximum": 2147483647} - key := map[string]any{"type": "string", "minLength": 1, "maxLength": 128, "description": "Explicit original idempotency key; retain with the exact request after unknown outcome."} - return []definition{ - {"review_scheduling_read", "Read this project's automatic Hosted and CLI settings and current queued PR pauses in one provider-free call. No settings, review or allowance changes. See docs/review-scheduling.md.", object(map[string]any{})}, - {"review_scheduling_configure", "Project manager: explicitly enable or disable automatic future Hosted or CLI requests under existing source, obligation, round and provider guards. Both default off. Optional automatic_cli preserves the current CLI setting when omitted. Existing grants and taper apply; no automatic adjudication or grant increase. Enabling retains this connection's current credential and active bound worker; withdrawn authority stops new automatic actions. This setting can authorize asynchronous provider work. Current revision and explicit key required; no automatic mutation retry. See docs/review-scheduling.md.", object(map[string]any{"expected_revision": revision, "automatic_hosted": map[string]any{"type": "boolean"}, "automatic_cli": map[string]any{"type": "boolean", "description": "Optional CLI opt-in; omission preserves the current setting."}, "idempotency_key": key}, "expected_revision", "automatic_hosted", "idempotency_key")}, - {"review_pull_scheduling_read", "Read one PR's temporary scheduling pause before or after an intent exists. Does not change Draft, grant, taper, closure or active provider work.", object(map[string]any{"pull_number": pull}, "pull_number")}, - {"review_pull_scheduling_update", "Writer: explicitly pause or resume new and undispatched reviews for one PR, including automatic Hosted and CLI selection. Does not cancel already-issued reviews or stop collecting results, change round credit or clear a separate operation pause. Retain current revision/key; reason is optional plain text only while paused and must be omitted on resume. See docs/review-scheduling.md.", object(map[string]any{"pull_number": pull, "expected_revision": revision, "paused": map[string]any{"type": "boolean"}, "reason": map[string]any{"type": "string", "maxLength": 256, "description": "Optional reason; omit on resume."}, "idempotency_key": key}, "pull_number", "expected_revision", "paused", "idempotency_key")}, - } -} diff --git a/internal/mcpadapter/review_scheduling_arguments_test.go b/internal/mcpadapter/review_scheduling_arguments_test.go deleted file mode 100644 index a3d54d153..000000000 --- a/internal/mcpadapter/review_scheduling_arguments_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package mcpadapter - -import ( - "encoding/json" - "testing" -) - -func TestSchedulingOptionalCLIArguments(t *testing.T) { - for _, value := range []string{"", "true", "false"} { - raw := `{"expected_revision":0,"automatic_hosted":false,"idempotency_key":"cli-setting"` - if value != "" { - raw += `,"automatic_cli":` + value - } - args, err := reviewSchedulingArguments("review_scheduling_configure", json.RawMessage(raw+"}")) - if err != nil || (args.reviewScheduling.AutomaticCLI == nil) != (value == "") { - t.Fatalf("lost optional CLI state %q: %+v %v", value, args, err) - } - if value != "" && *args.reviewScheduling.AutomaticCLI != (value == "true") { - t.Fatal("wrong CLI state") - } - } - for _, raw := range []string{ - `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":null,"idempotency_key":"key"}`, - `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":"true","idempotency_key":"key"}`, - `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":true,"automatic_cli":false,"idempotency_key":"key"}`, - `{"expected_revision":0,"automatic_cli":true,"idempotency_key":"key"}`, - } { - if _, err := reviewSchedulingArguments("review_scheduling_configure", json.RawMessage(raw)); err == nil { - t.Fatal("accepted malformed CLI configuration", raw) - } - } -} - -func TestSchedulingPauseReasonIsOmittedOnResume(t *testing.T) { - for _, raw := range []string{ - `{"pull_number":7,"expected_revision":2,"paused":false,"idempotency_key":"resume"}`, - `{"pull_number":7,"expected_revision":2,"paused":true,"reason":"","idempotency_key":"pause-empty-reason"}`, - `{"pull_number":7,"expected_revision":2,"paused":true,"reason":"Fixing","idempotency_key":"pause-reason"}`, - } { - if _, err := reviewSchedulingArguments("review_pull_scheduling_update", json.RawMessage(raw)); err != nil { - t.Fatalf("rejected valid scheduling update %s: %v", raw, err) - } - } - for _, raw := range []string{ - `{"pull_number":7,"expected_revision":2,"paused":false,"reason":"no longer allowed","idempotency_key":"resume-reason"}`, - `{"pull_number":7,"expected_revision":2,"paused":false,"reason":"","idempotency_key":"resume-empty-reason"}`, - `{"pull_number":7,"expected_revision":2,"paused":false,"reason":null,"idempotency_key":"resume-null-reason"}`, - } { - if _, err := reviewSchedulingArguments("review_pull_scheduling_update", json.RawMessage(raw)); err == nil { - t.Fatalf("accepted reason on resume: %s", raw) - } - } -} diff --git a/internal/mcpadapter/review_scheduling_test.go b/internal/mcpadapter/review_scheduling_test.go deleted file mode 100644 index bd155a266..000000000 --- a/internal/mcpadapter/review_scheduling_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package mcpadapter_test - -import ( - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strconv" - "testing" - - "github.com/benhook1013/FireController/internal/client" - "github.com/benhook1013/FireController/internal/profile" - "github.com/benhook1013/FireController/internal/reviewexec" -) - -func TestSchedulingSDKBoundControlsAndDiscovery(t *testing.T) { - f := mutationFixture(t) - if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { - t.Fatal(err) - } - engine, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "scheduling-fixture", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}) - if err != nil { - t.Fatal(err) - } - mux := http.NewServeMux() - mux.Handle("/", f.handler) - engine.Register(mux) - server := httptest.NewServer(mux) - defer server.Close() - managerCredential := filepath.Join(t.TempDir(), "manager.token") - if err := os.WriteFile(managerCredential, []byte(f.admin), 0600); err != nil { - t.Fatal(err) - } - managerProfile := profiles(t, map[string]profile.Context{"chosen": {Profile: "chosen", ServerURL: server.URL, InstanceID: f.store.InstanceID(), ProjectID: f.project, WorkerID: f.sender}}, managerCredential) - manager := reviewControlsStdio(t, managerProfile, "chosen") - writer := connect(t, f.adapter(t, server.URL, f.sender), "") - beforeProviders := f.providers.Load() - var initial client.ReviewScheduling - decodeResult(t, call(t, writer, "review_scheduling_read", nil), &initial) - if initial.Revision != 0 || initial.AutomaticHosted || initial.PausedPulls == nil { - t.Fatal(initial) - } - diagnosticResult(t, call(t, writer, "review_scheduling_configure", map[string]any{"expected_revision": 0, "automatic_hosted": true, "idempotency_key": "writer-cannot-enable"}), "forbidden", false) - input := map[string]any{"expected_revision": 0, "automatic_hosted": true, "idempotency_key": "manager-enable"} - var first, replay client.ReviewRequestReceipt - decodeResult(t, call(t, manager, "review_scheduling_configure", input), &first) - decodeResult(t, call(t, manager, "review_scheduling_configure", input), &replay) - if first != replay || first.ID != f.project || first.Revision != 1 { - t.Fatal(first, replay) - } - // CLI opt-in is independent; a legacy Hosted-only write preserves it. - decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 1, "automatic_hosted": false, "automatic_cli": true, "idempotency_key": "manager-cli-enable"}), &first) - var automatic client.ReviewScheduling - decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) - if automatic.AutomaticHosted || !automatic.AutomaticCLI || automatic.AuthorizingWorkerID != f.sender { - t.Fatal("CLI opt-in lost shared authorization", automatic) - } - decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 2, "automatic_hosted": true, "idempotency_key": "manager-legacy-preserve"}), &first) - decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) - if !automatic.AutomaticHosted || !automatic.AutomaticCLI { - t.Fatal("legacy configuration changed CLI opt-in", automatic) - } - decodeResult(t, call(t, manager, "review_scheduling_configure", map[string]any{"expected_revision": 3, "automatic_hosted": true, "automatic_cli": false, "idempotency_key": "manager-cli-disable"}), &first) - decodeResult(t, call(t, writer, "review_scheduling_read", nil), &automatic) - if !automatic.AutomaticHosted || automatic.AutomaticCLI { - t.Fatal("explicit CLI disable was lost", automatic) - } - var paused client.ReviewRequestReceipt - decodeResult(t, call(t, writer, "review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 0, "paused": true, "reason": "Preparing changes", "idempotency_key": "pause-before-intent"}), &paused) - if paused.ID != strconv.Itoa(7) || paused.Revision != 1 { - t.Fatal(paused) - } - var state client.ReviewPullScheduling - decodeResult(t, call(t, writer, "review_pull_scheduling_read", map[string]any{"pull_number": 7}), &state) - if !state.Paused || state.Reason != "Preparing changes" || state.ProjectID != f.project { - t.Fatal(state) - } - decodeResult(t, call(t, writer, "review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 1, "paused": false, "idempotency_key": "resume-before-intent"}), &paused) - decodeResult(t, call(t, writer, "review_pull_scheduling_read", map[string]any{"pull_number": 7}), &state) - if state.Paused || state.Reason != "" || state.Revision != 2 { - t.Fatal(state) - } - for _, tc := range []struct { - name string - args map[string]any - }{ - {"review_scheduling_read", map[string]any{"project_id": "foreign"}}, - {"review_scheduling_configure", map[string]any{"expected_revision": 1, "automatic_hosted": nil, "idempotency_key": "null"}}, - {"review_scheduling_configure", map[string]any{"expected_revision": 1, "idempotency_key": "missing-bool"}}, - {"review_pull_scheduling_read", map[string]any{"pull_number": 0}}, - {"review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 2, "paused": nil, "idempotency_key": "null-pause"}}, - {"review_pull_scheduling_update", map[string]any{"pull_number": 7, "expected_revision": 2, "paused": true, "reason": nil, "idempotency_key": "null-reason"}}, - } { - diagnosticResult(t, call(t, manager, tc.name, tc.args), "invalid_arguments", false) - } - listed, err := allDiscoveredTools(t, manager) - if err != nil { - t.Fatal(err) - } - seen := 0 - for _, tool := range listed.Tools { - if tool.Name != "review_scheduling_read" && tool.Name != "review_scheduling_configure" && tool.Name != "review_pull_scheduling_read" && tool.Name != "review_pull_scheduling_update" { - continue - } - seen++ - write := tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update" - if tool.Annotations == nil || tool.Annotations.ReadOnlyHint == write || tool.Annotations.OpenWorldHint == nil || *tool.Annotations.OpenWorldHint != (tool.Name == "review_scheduling_configure" || tool.Name == "review_pull_scheduling_update") { - t.Fatal("unsafe annotations", tool.Name) - } - } - if seen != 4 || f.providers.Load() != beforeProviders { - t.Fatal("missing tools or provider work", seen, f.providers.Load(), beforeProviders) - } - for _, table := range []string{"review_selections", "review_operations", "review_execution_attempts"} { - var n int - if err := f.store.DB().QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil || n != 0 { - t.Fatal("handler started review work", table, n, err) - } - } -} diff --git a/internal/mcpadapter/tools.go b/internal/mcpadapter/tools.go index de96427b1..fb60b931b 100644 --- a/internal/mcpadapter/tools.go +++ b/internal/mcpadapter/tools.go @@ -20,8 +20,6 @@ const maxToolWaitSeconds = 50 type arguments struct { operationControl client.ReviewOperationControl - reviewScheduling client.ConfigureReviewSchedulingRequest - reviewPullScheduling client.ConfigureReviewPullSchedulingRequest ciWatchTargets []client.CIWatchTarget ownerManagement *ownerManagementInvocation existingManagement *existingManagementArgs @@ -86,20 +84,17 @@ func boundServer(binding profile.Binding) *mcp.Server { definitions = append(definitions, projectMapDefinitions()...) definitions = append(definitions, jobContextDefinition(), messageWaitDefinition()) definitions = append(definitions, ciWatchDefinition()) - definitions = append(definitions, reviewSchedulingDefinitions()...) known := make(map[string]bool) transports := sessionTransports{pools: make(map[*mcp.ServerSession]*client.TransportPool)} for _, tool := range definitions { known[tool.name] = true - write := reviewSchedulingWrite(tool.name) || ownerManagementWrite(tool.name) || existingManagementWrite(tool.name) || tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" - openWorld := tool.name == "review_pull_scheduling_update" || tool.name == "review_scheduling_configure" || tool.name == "wait_for_ci" || tool.name == "review_start" || checkpointWrite(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" - destructive := reviewSchedulingWrite(tool.name) || ownerManagementDestructive(tool.name) || existingManagementDestructive(tool.name) || tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" + write := ownerManagementWrite(tool.name) || existingManagementWrite(tool.name) || tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" + openWorld := tool.name == "wait_for_ci" || tool.name == "review_start" || checkpointWrite(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" + destructive := ownerManagementDestructive(tool.name) || existingManagementDestructive(tool.name) || tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" s.AddTool(&mcp.Tool{Name: tool.name, Description: tool.description, InputSchema: tool.schema, Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !write, IdempotentHint: true, DestructiveHint: &destructive, OpenWorldHint: &openWorld}}, func(ctx context.Context, request *mcp.CallToolRequest) (*mcp.CallToolResult, error) { var args arguments var err error - if reviewSchedulingTool(tool.name) { - args, err = reviewSchedulingArguments(tool.name, request.Params.Arguments) - } else if tool.name == "wait_for_ci" { + if tool.name == "wait_for_ci" { args, err = ciWatchArguments(request.Params.Arguments) } else if ownerManagementTool(tool.name) { args, err = ownerManagementArguments(tool.name, request.Params.Arguments) @@ -207,14 +202,6 @@ func boundServer(binding profile.Binding) *mcp.Server { value, err = service.ReviewExecution(ctx) case "review_operations_list": value, err = service.ReviewOperations(ctx, args.reviewOperations) - case "review_scheduling_read": - value, err = service.ReviewScheduling(ctx) - case "review_scheduling_configure": - value, err = service.ConfigureReviewScheduling(ctx, args.key, args.reviewScheduling) - case "review_pull_scheduling_read": - value, err = service.ReviewPullScheduling(ctx, args.pullNumber) - case "review_pull_scheduling_update": - value, err = service.ConfigureReviewPullScheduling(ctx, args.key, args.pullNumber, args.reviewPullScheduling) case "wait_for_ci": var watch client.CIWatchResult watch, err = service.WatchCI(ctx, args.ciWatchTargets, args.reviewSourceWait) diff --git a/tools/packagedsmoke/project_management_test.go b/tools/packagedsmoke/project_management_test.go index 99770b3f3..ccbc38ea7 100644 --- a/tools/packagedsmoke/project_management_test.go +++ b/tools/packagedsmoke/project_management_test.go @@ -113,18 +113,6 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { var owner client.ProjectCredentialReceipt decode(t, cli(adminProfile, "admin", "credentials", "grant", "--credential-file", managerFile, "--permission", "manage", "--key", "grant-manager"), &owner) managerProfile := profile("manager", managerFile) - // Scheduling configuration is independent of execution configuration and keeps - // exact control identities across native CLI/MCP and restart. - var scheduling client.ReviewScheduling - decode(t, cli(managerProfile, "manager", "reviews", "scheduling"), &scheduling) - if scheduling.Revision != 0 || scheduling.AutomaticHosted || scheduling.AutomaticCLI { - t.Fatal("new scheduling is not off", scheduling) - } - configured := cli(managerProfile, "manager", "reviews", "scheduling", "configure", "--automatic-hosted", "false", "--automatic-cli", "false", "--expect-revision", "0", "--key", "scheduling-off") - if !bytes.Equal(configured, cli(managerProfile, "manager", "reviews", "scheduling", "configure", "--automatic-hosted", "false", "--automatic-cli", "false", "--expect-revision", "0", "--key", "scheduling-off")) { - t.Fatal("scheduling exact replay changed") - } - var grant client.ProjectCredentialReceipt decode(t, cli(managerProfile, "manager", "credentials", "grant", "--credential-file", readerFile, "--permission", "read", "--key", "grant-reader"), &grant) permissionFile := filepath.Join(private, "permissions.json") @@ -167,13 +155,6 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { t.Fatal("missing MCP text") return nil } - - call("review_pull_scheduling_update", map[string]any{"pull_number": 42, "paused": true, "reason": "Synthetic scheduling hold", "expected_revision": 0, "idempotency_key": "scheduling-pause"}) - var paused client.ReviewPullScheduling - decode(t, call("review_pull_scheduling_read", map[string]any{"pull_number": 42}), &paused) - if !paused.Paused || paused.Revision != 1 { - t.Fatal("MCP pause not retained", paused) - } call("inbox_ack", map[string]any{"message_id": message.ID, "worker_id": target.ID, "idempotency_key": "peer-ack"}) var retired client.WorkerRetirementReceipt decode(t, call("worker_retire", map[string]any{"worker_id": target.ID, "idempotency_key": "retire"}), &retired) @@ -197,26 +178,8 @@ func TestPackagedProjectManagementSmoke(t *testing.T) { daemon.stop(t) daemon = startDaemon(t, ctx, filepath.Join(bin, "fcd"), data, env) managerProfile = profile("manager-restarted", managerFile) - decode(t, cli(managerProfile, "manager-restarted", "reviews", "scheduling", "read", "--pr", "42"), &paused) - if !paused.Paused || paused.Revision != 1 || paused.Reason != "Synthetic scheduling hold" { - t.Fatal("restart changed paused scheduling control", paused) - } - cli(managerProfile, "manager-restarted", "reviews", "scheduling", "resume", "--pr", "42", "--expect-revision", "1", "--key", "scheduling-resume") - daemon.stop(t) - daemon = startDaemon(t, ctx, filepath.Join(bin, "fcd"), data, env) - managerProfile = profile("manager-resumed", managerFile) - var resumed client.ReviewPullScheduling - decode(t, cli(managerProfile, "manager-resumed", "reviews", "scheduling", "read", "--pr", "42"), &resumed) - if resumed.Paused || resumed.Revision != 2 || resumed.Reason != "" { - t.Fatal("restart changed scheduling control", resumed) - } - decode(t, cli(managerProfile, "manager-resumed", "reviews", "scheduling"), &scheduling) - if scheduling.Revision != 1 || scheduling.AutomaticHosted || scheduling.AutomaticCLI { - t.Fatal("restart changed default-off control", scheduling) - } - var replay client.WorkerRetirementReceipt - decode(t, cli(managerProfile, "manager-resumed", "workers", "retire", target.ID, "--key", "retire"), &replay) + decode(t, cli(managerProfile, "manager-restarted", "workers", "retire", target.ID, "--key", "retire"), &replay) if replay != retired { t.Fatal("restart changed retirement receipt") } From f245142af858d35f9a04e300cfcc00fe5a73a658 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 02:25:22 +1300 Subject: [PATCH 09/41] Preserve cooldown history across unused scheduling holds --- .../scheduling_cooldown_history_test.go | 63 +++++++++++++++++++ internal/reviewexec/wait_deadline.go | 21 ++++++- 2 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 internal/reviewexec/scheduling_cooldown_history_test.go diff --git a/internal/reviewexec/scheduling_cooldown_history_test.go b/internal/reviewexec/scheduling_cooldown_history_test.go new file mode 100644 index 000000000..b52aa58a2 --- /dev/null +++ b/internal/reviewexec/scheduling_cooldown_history_test.go @@ -0,0 +1,63 @@ +package reviewexec + +import ( + "reflect" + "testing" +) + +func TestSchedulingHoldKeepsCooldownHistoryStrict(t *testing.T) { + for _, channel := range []string{"cli", "hosted"} { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_scheduling_unavailable"} { + for _, damage := range []string{"none", "first-reason", "missing-first", "extra-transition", "intent", "reservation", "evidence"} { + t.Run(channel+"/"+reason+"/"+damage, func(t *testing.T) { + f, original, now := deadlineRuntimeFixture(t, channel) + before := cliWaitRead(t, f, original.OperationID) + *now = cliWaitDue(t, before) + retry := f.start(t, attemptProject, Receipt{ID: original.OperationID}) + if _, err := f.e.Advance(t.Context(), attemptProject, retry.ID, retry.Revision, "held", reason, ""); err != nil { + t.Fatal(err) + } + after := cliWaitRead(t, f, original.OperationID) + if after.State != "queued" || after.AttemptID != "" || !reflect.DeepEqual(before.Wait, after.Wait) { + t.Fatal("lost original timer", after) + } + switch damage { + case "first-reason": + admissionSQL(t, f, `UPDATE review_execution_transitions SET reason='not-preparing' WHERE attempt_id=? AND revision=1`, retry.ID) + case "missing-first": + admissionSQL(t, f, `DELETE FROM review_execution_transitions WHERE attempt_id=? AND revision=1`, retry.ID) + case "extra-transition": + admissionSQL(t, f, `INSERT INTO review_execution_transitions SELECT attempt_id,3,state,reason,external_id,created_at FROM review_execution_transitions WHERE attempt_id=? AND revision=2`, retry.ID) + case "intent": + admissionSQL(t, f, `UPDATE review_execution_attempts SET intent='issued' WHERE id=?`, retry.ID) + case "reservation": + admissionSQL(t, f, `INSERT INTO review_execution_reservations VALUES(?,901,2,?,?,?)`, retry.Provider, channel, retry.Account, retry.ID) + case "evidence": + admissionSQL(t, f, `INSERT INTO review_execution_evidence VALUES('bad-evidence',?,?,?,'{}','bad')`, attemptProject, retry.ID, after.ID) + } + state := deadlineRuntimeState(t, f) + wait, err := readOperationWait(t.Context(), f.store.DB(), after) + if damage == "none" { + if err != nil || !reflect.DeepEqual(wait, before.Wait) { + t.Fatal("valid history refused", wait, err) + } + } else if err == nil || wait != nil { + t.Fatal("runtime accepted corruption", wait, err) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + err = ValidateOperationWaitsSnapshot(t.Context(), tx) + tx.Rollback() + if (err == nil) != (damage == "none") { + t.Fatal("snapshot history classification", err) + } + if state != deadlineRuntimeState(t, f) { + t.Fatal("validation mutated retained history") + } + }) + } + } + } +} diff --git a/internal/reviewexec/wait_deadline.go b/internal/reviewexec/wait_deadline.go index 72d23e361..80ce7e667 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, scheduling []string var first string var earliest time.Time tied := false @@ -153,6 +153,10 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba if !state.Valid || !retainedReason.Valid || state.String != "held" || attemptState != "held" { return waitUnavailable() } + if retainedReason.String == "pull_scheduling_paused" || retainedReason.String == "automation_authorization_changed" || retainedReason.String == "automatic_scheduling_unavailable" { + scheduling = append(scheduling, id) + continue + } if o.Channel == "cli" && retainedReason.String == cliDraftWait { continue } @@ -173,6 +177,21 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba return err } rows.Close() + // Scheduling guards detach unused preparations without becoming quota + // baselines. Reuse the same strict journal proof as snapshot validation. + for _, id := range scheduling { + 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 From 5084daa32b112fbade79830647708bd20459cfae Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 11:15:53 +1300 Subject: [PATCH 10/41] fix: preserve admission preparation on damaged retained configuration --- .../scheduling_admission0030_test.go | 21 +++++++++++++++++-- internal/reviewexec/supervisor.go | 11 +++++----- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/internal/reviewexec/scheduling_admission0030_test.go b/internal/reviewexec/scheduling_admission0030_test.go index 9384038e7..83de77853 100644 --- a/internal/reviewexec/scheduling_admission0030_test.go +++ b/internal/reviewexec/scheduling_admission0030_test.go @@ -8,7 +8,7 @@ import ( func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { for _, channel := range []string{"hosted", "cli"} { - for _, change := range []string{"explicit-pause", "automatic-pause", "disable", "disable-reenable", "revoke", "lost-management", "malformed-state"} { + for _, change := range []string{"explicit-pause", "automatic-pause", "disable", "disable-reenable", "revoke", "lost-management", "malformed-state", "malformed-scheduling"} { t.Run(channel+"/"+change, func(t *testing.T) { f := schedulingFixtureWithQueue(t, []int64{2}) f.e.publishAttempt = publishAttemptTransition @@ -34,7 +34,7 @@ func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { if change == "explicit-pause" || change == "automatic-pause" { reason = "pull_scheduling_paused" } - if change == "malformed-state" { + if change == "malformed-state" || change == "malformed-scheduling" { reason = "automatic_scheduling_unavailable" } var preparedAttempt Attempt @@ -62,6 +62,8 @@ func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { admissionSQL(t, f, `UPDATE credentials SET revoked=1 WHERE id='exec-writer-cred'`) case "lost-management": admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) + case "malformed-scheduling": + admissionSQL(t, f, `UPDATE review_scheduling SET updated_at=? WHERE project_id=?`, "not-a-timestamp", attemptProject) case "malformed-state": admissionSQL(t, f, `UPDATE review_execution_config SET body_json='{' WHERE project_id=?`, attemptProject) } @@ -75,6 +77,21 @@ func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { t.Fatal("late control refusal became a worker failure", err) } after := roundOperation(t, f, id) + if change == "malformed-state" { + // Damaged retained configuration is not a proven scheduling-only + // refusal: preserve the unused preparation for explicit recovery. + if after.State != "preparing" || after.AttemptID != preparedAttempt.ID || after.ActorID != before.ActorID || after.WorkerID != before.WorkerID || after.HeadSHA != before.HeadSHA || after.ConfigurationRevision != before.ConfigurationRevision || after.Channel != before.Channel || driver.prepares.Load() != 1 || driver.calls.Load() != 0 { + t.Fatal("damaged configuration discarded preparation or dispatched", before, after) + } + if attribution != snapshotTable(t, f, "review_automatic_selections") || waits != snapshotTable(t, f, "review_operation_waits") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 1 || attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 1 { + t.Fatal("damaged configuration changed retained work or reservation") + } + var state, anchor, intent, external string + if err := f.store.DB().QueryRow(`SELECT state,anchor_json,intent,external_id FROM review_execution_attempts WHERE id=?`, preparedAttempt.ID).Scan(&state, &anchor, &intent, &external); err != nil || state != "preparing" || anchor != "null" || intent != "" || external != "" { + t.Fatal("damaged configuration recorded dispatch intent", state, anchor, intent, external, err) + } + return + } if after.State != "queued" || after.Reason != reason || after.AttemptID != "" || after.ActorID != before.ActorID || after.WorkerID != before.WorkerID || after.HeadSHA != before.HeadSHA || after.ConfigurationRevision != before.ConfigurationRevision || after.Channel != before.Channel || driver.prepares.Load() != 1 || driver.calls.Load() != 0 { t.Fatal("late refusal lost the request or dispatched", before, after) } diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index b0f56c21d..040b75a9c 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -673,6 +673,12 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr 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. Configuration damage + // also carries the broader project-local tag, so classify it first. + if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + continue + } if automaticProjectRefused(err) { // Only proven scheduling-local corruption releases this unused preparation. if err := e.finishPreparation(a, "held", "automatic_scheduling_unavailable"); err != nil { @@ -680,11 +686,6 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr } continue } - // 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) { - 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 From 9787a70596510f612a874a0b8d2ab44397ec2915 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 20:33:14 +1300 Subject: [PATCH 11/41] Test hosted queue cancellation after resuming the predecessor --- internal/reviewexec/hosted_priority_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/reviewexec/hosted_priority_test.go b/internal/reviewexec/hosted_priority_test.go index e02034c7f..6de8ddfbd 100644 --- a/internal/reviewexec/hosted_priority_test.go +++ b/internal/reviewexec/hosted_priority_test.go @@ -249,6 +249,10 @@ func TestHostedCooldownQueuePriorityProjection(t *testing.T) { if read("5").Items[0].Channels[0].Wait.QueueAheadPullNumber != 0 { t.Fatal("paused earlier request reserved display priority") } + timerControl(t, f, head.ID, "resume", "display-resume-head") + if read("5").Items[0].Channels[0].Wait.QueueAheadPullNumber != 2 { + t.Fatal("resuming the earlier request did not restore display priority") + } timerControl(t, f, head.ID, "cancel", "display-cancel-head") if read("5").Items[0].Channels[0].Wait.QueueAheadPullNumber != 0 { t.Fatal("mere earlier queue row reserved display priority") From 7ae8f915680eda3ff5bda8efe9d1705784edff4c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 21:06:23 +1300 Subject: [PATCH 12/41] Prove the automatic CLI comparison rejects a stale head --- internal/reviewexec/scheduling_cli_test.go | 28 +++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/internal/reviewexec/scheduling_cli_test.go b/internal/reviewexec/scheduling_cli_test.go index 0d93b64b7..09a7ecb70 100644 --- a/internal/reviewexec/scheduling_cli_test.go +++ b/internal/reviewexec/scheduling_cli_test.go @@ -203,15 +203,27 @@ func TestSchedulingCLIControlsAndCurrentHead(t *testing.T) { if r.State != "selected" { t.Fatal(r) } - if kind == "stale-head" { - admissionSQL(t, f, `UPDATE review_operations SET head_sha=? WHERE id=?`, strings.Repeat("f", 40), r.OperationID) + // The execution admission guard, not automatic selection, owns the head check. + attempt, err := f.e.StartAttempt(t.Context(), attemptProject, r.OperationID) + if err != nil || attempt.State != "preparing" { + t.Fatal("selected operation did not prepare", attempt, err) } - // Normal execution gates, rather than automatic scheduling, still own final admission. - if kind == "stale-head" { - _, err := f.e.ExecutionContext(t.Context(), attemptProject, r.OperationID) - if err == nil { - t.Fatal("stale head admitted") - } + current, err := f.e.ExecutionContext(t.Context(), attemptProject, r.OperationID) + if err != nil { + t.Fatal("selected operation did not pass execution context", err) + } + matching := attemptAnchor(attemptProject, current.Operation.PullNumber) + matching.CandidateSHA = current.Operation.HeadSHA + stale := matching + stale.CandidateSHA = strings.Repeat("f", 40) + if stale.CandidateSHA == matching.CandidateSHA { + t.Fatal("fixture did not change candidate head") + } + _, err = f.e.Admit(t.Context(), attemptProject, attempt.ID, attempt.Revision, stale, "") + attemptCode(t, err, "review_conflict") + admitted, err := f.e.Admit(t.Context(), attemptProject, attempt.ID, attempt.Revision, matching, "") + if err != nil || admitted.State != "active" || admitted.Anchor == nil || *admitted.Anchor != matching { + t.Fatal("same attempt with matching head did not admit", admitted, err) } schedulingCLIGenerate(t, f, false) }) From 010615f918713fcdb69344a61a656ed7e9e4a8f1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 21:23:22 +1300 Subject: [PATCH 13/41] Pin the account used for automatic CLI selection --- internal/reviewexec/scheduling_automatic.go | 17 +++++++++++--- internal/reviewexec/scheduling_cli.go | 6 ++--- internal/reviewexec/scheduling_cli_test.go | 26 +++++++++++++++++++++ 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 1609f824f..eb2a96ed6 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -554,6 +554,7 @@ func automaticChannelEnabled(s schedulingRecord, channel string) bool { // serialized writer and compare its identity before using ordinary acceptance // or retry CAS. Idle and permanently suppressed projects never take the writer. type automaticProjectPlan struct { + account string scheduling schedulingRecord scope core.Scope basis string @@ -628,7 +629,7 @@ func (e *Engine) planAutomaticProject(ctx context.Context, tx *sql.Tx, project, if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND (basis_sha256=? OR settled_basis_sha256=?))`, project, basis, basis).Scan(&seen); err != nil { return nil, err } - plan := &automaticProjectPlan{scheduling: s, scope: scope, basis: basis} + plan := &automaticProjectPlan{account: automaticAccountKey(e.capabilities[c.CapabilityID]), scheduling: s, scope: scope, basis: basis} if seen { plan.retry, err = e.automaticSourceRetryCandidate(ctx, tx, project, basis, s.Revision, time.Now(), channel) if err != nil || plan.retry == nil { @@ -638,7 +639,17 @@ func (e *Engine) planAutomaticProject(ctx context.Context, tx *sql.Tx, project, return plan, nil } +func automaticAccountKey(capability Capability) string { + return capability.Provider + "\x00" + capability.Account +} + func (e *Engine) generateAutomaticProject(ctx context.Context, project, channel string, readers map[string]TargetReader) (bool, error) { + return e.generateAutomaticProjectForAccount(ctx, project, channel, readers, "") +} + +// A CLI pass nominates only under the account counted by its pre-read; +// a changed account must be reconsidered by a fresh pass. +func (e *Engine) generateAutomaticProjectForAccount(ctx context.Context, project, channel string, readers map[string]TargetReader, expectedAccount string) (bool, error) { var candidate *automaticProjectPlan err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { var err error @@ -648,7 +659,7 @@ func (e *Engine) generateAutomaticProject(ctx context.Context, project, channel if ctx.Err() != nil { return false, ctx.Err() } - if err != nil || candidate == nil { + if err != nil || candidate == nil || expectedAccount != "" && candidate.account != expectedAccount { return false, err } return e.acceptAutomaticProject(ctx, project, channel, readers, candidate) @@ -661,7 +672,7 @@ func (e *Engine) acceptAutomaticProject(ctx context.Context, project, channel st if err != nil || current == nil { return err } - if current.basis != candidate.basis || current.scheduling.Revision != candidate.scheduling.Revision || (current.retry == nil) != (candidate.retry == nil) { + if channel == "cli" && current.account != candidate.account || current.basis != candidate.basis || current.scheduling.Revision != candidate.scheduling.Revision || (current.retry == nil) != (candidate.retry == nil) { return nil } if current.retry != nil { diff --git a/internal/reviewexec/scheduling_cli.go b/internal/reviewexec/scheduling_cli.go index a4c7aa249..eccb1b065 100644 --- a/internal/reviewexec/scheduling_cli.go +++ b/internal/reviewexec/scheduling_cli.go @@ -45,7 +45,7 @@ func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]Ta } capability, ok := e.capabilities[c.CapabilityID] if ok { - account = capability.Provider + "\x00" + capability.Account + account = automaticAccountKey(capability) } return nil }) @@ -55,10 +55,10 @@ func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]Ta if err != nil { return generated, err } - if selectedAccounts[account] { + if account == "" || selectedAccounts[account] { continue } - worked, err := e.generateAutomaticProject(ctx, project, "cli", readers) + worked, err := e.generateAutomaticProjectForAccount(ctx, project, "cli", readers, account) if automaticProjectRefused(err) { continue } diff --git a/internal/reviewexec/scheduling_cli_test.go b/internal/reviewexec/scheduling_cli_test.go index 09a7ecb70..722a25395 100644 --- a/internal/reviewexec/scheduling_cli_test.go +++ b/internal/reviewexec/scheduling_cli_test.go @@ -585,3 +585,29 @@ func TestSchedulingChannelBasisRejectsInvalidCurrentHistory(t *testing.T) { }) } } + +func TestAutomaticCLIAccountChangeWaitsForNextPass(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingCLIEnable(t, f, 0, true) + oldAccount := automaticAccountKey(f.e.capabilities["test-capability"]) + newAccount := automaticAccountKey(f.e.capabilities["other-account"]) + if oldAccount == newAccount { + t.Fatal("fixture needs distinct accounts") + } + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}, "other-account": &refreshTestReader{}} + // Commit a capability change after the pass observes its account but before + // the generator acquires the planning snapshot. + f.configure(t, attemptProject, "other-account", 1, false) + if worked, err := f.e.generateAutomaticProjectForAccount(t.Context(), attemptProject, "cli", readers, oldAccount); err != nil || worked { + t.Fatal("selection accepted under a different account from this pass", worked, err) + } + if got := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections`); got != 0 { + t.Fatal("changed account left an attribution", got) + } + if worked, err := f.e.generateAutomaticProjectForAccount(t.Context(), attemptProject, "cli", readers, newAccount); err != nil || !worked { + t.Fatal("fresh pass did not select the newly bound account", worked, err) + } + if got := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections`); got != 1 { + t.Fatal("fresh account produced an unexpected attribution count", got) + } +} From 50a28a49f70e04f03b03532056e48d4fea7a6dfb Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 22:41:16 +1300 Subject: [PATCH 14/41] Reject stale scheduling projections in backup snapshots --- internal/reviewexec/scheduling_snapshot.go | 12 ++++++++++ internal/reviewexec/scheduling_test.go | 27 ++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 52d301ea2..b5ae6bc87 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -61,6 +61,18 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { if closeErr != nil { return closeErr } + // A retained projection cannot predate a matching scheduling event. + var ahead bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_scheduling s WHERE EXISTS( + SELECT 1 FROM events e WHERE e.project_id=s.project_id AND e.resource_id=s.project_id + AND e.event_type='review.scheduling_updated' AND e.revision>s.revision))`).Scan(&ahead) + if err != nil { + return err + } + if ahead { + return schedulingUnavailable() + } + rows, err = tx.QueryContext(ctx, `SELECT project_id,pull_number,revision,paused,reason,actor_id,updated_at FROM review_pull_scheduling`) if err != nil { return err diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index dbdc14e4b..c10f7eb53 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -1406,6 +1406,33 @@ func TestValidateSchedulingSnapshotAcceptsSupportedVersions(t *testing.T) { } } +func TestValidateSchedulingSnapshotRejectsStaleProjectProjection(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + var actor, worker, credential, at string + err := f.store.DB().QueryRowContext(t.Context(), `SELECT actor_id,worker_id,credential_id,updated_at FROM review_scheduling WHERE project_id=?`, attemptProject).Scan(&actor, &worker, &credential, &at) + if err != nil { + t.Fatal(err) + } + schedulingEnable(t, f, 1, false) + // Retained events for another project or resource must not advance this + // projection's revision. + for _, identity := range [][2]string{{otherAttemptProject, attemptProject}, {attemptProject, otherAttemptProject}} { + admissionSQL(t, f, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) + SELECT ?,event_type,?,revision+1,actor_id,payload_json,created_at FROM events + WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision=2`, + identity[0], identity[1], attemptProject, attemptProject) + } + if err := validateSchedulingSnapshotForTest(t, f); err != nil { + t.Fatalf("healthy rev-2 projection rejected: %v", err) + } + // Reinstall only the older projection, while retaining both genuine + // scheduling events as they would exist after a stale snapshot restore. + admissionSQL(t, f, `UPDATE review_scheduling SET revision=1,automatic_hosted=1,actor_id=?,worker_id=?,credential_id=?,updated_at=? WHERE project_id=?`, + actor, worker, credential, at, attemptProject) + attemptCode(t, validateSchedulingSnapshotForTest(t, f), "storage_unavailable") +} + func TestValidateSchedulingSnapshotRejectsMalformedAndFutureVersions(t *testing.T) { for _, tc := range []struct { name string From c2928f751ddf83749547aec12835bf4ed554557e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 22:50:40 +1300 Subject: [PATCH 15/41] Refuse a backup missing a retained paused pull control --- internal/backup/scheduling_test.go | 1 + internal/reviewexec/scheduling_snapshot.go | 55 ++++++++++++++++++++-- internal/reviewexec/scheduling_test.go | 22 +++++++++ 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index 8e0a9a932..008e62f70 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -229,6 +229,7 @@ func TestSchedulingBackupRefusesResealedShapeReferencesAndProvenance(t *testing. {"missing-credential", `UPDATE review_automatic_selections SET credential_id='credential_missing'`}, {"wrong-target", `UPDATE review_automatic_selections SET pull_number=99`}, {"future-control-revision", `UPDATE review_automatic_selections SET scheduling_revision=99`}, + {"missing-paused-projection", `DELETE FROM review_pull_scheduling WHERE paused=1`}, {"blob-pause-reason", `UPDATE review_pull_scheduling SET reason=CAST(reason AS BLOB)`}, {"blob-pause-actor", `UPDATE review_pull_scheduling SET actor_id=CAST(actor_id AS BLOB)`}, {"blob-pause-time", `UPDATE review_pull_scheduling SET updated_at=CAST(updated_at AS BLOB)`}, diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index b5ae6bc87..c7e4d7a77 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -100,6 +100,9 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { if closeErr != nil { return closeErr } + 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 { @@ -175,6 +178,52 @@ func scanSchedulingSnapshot(row interface{ Scan(...any) error }, destinations .. 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. +func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, `WITH orphan AS ( + SELECT e.project_id,e.resource_id,e.revision, + CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END AS payload, + ROW_NUMBER() OVER (PARTITION BY e.project_id,e.resource_id ORDER BY e.revision DESC,e.sequence DESC) AS newest, + COUNT(*) OVER (PARTITION BY e.project_id,e.resource_id,e.revision) AS matches + FROM events e LEFT JOIN review_pull_scheduling s + ON s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) + AND CAST(s.pull_number AS TEXT)=e.resource_id + WHERE e.event_type='review.pull_scheduling_updated' AND s.pull_number IS NULL + ) + SELECT resource_id,revision,payload,matches FROM orphan WHERE newest=1`) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var resource string + var revision, matches int64 + var payload sql.NullString + if err := rows.Scan(&resource, &revision, &payload, &matches); err != nil { + return err + } + pull, err := strconv.ParseInt(resource, 10, 32) + if err != nil || pull < 1 || strconv.FormatInt(pull, 10) != resource || revision < 1 || matches != 1 || + !validPullSchedulingPayload(payload, pull, false) { + return schedulingUnavailable() + } + } + if err := rows.Err(); err != nil { + return err + } + return rows.Close() +} + +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 +} + // A restored control must agree with its latest retained user decision. func validatePullSchedulingEvent(ctx context.Context, tx *sql.Tx, s PullScheduling) error { rows, err := tx.QueryContext(ctx, `SELECT revision,actor_id,CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND event_type='review.pull_scheduling_updated' AND resource_id=? AND revision>=? ORDER BY revision DESC,sequence DESC LIMIT 2`, s.ProjectID, strconv.FormatInt(s.PullNumber, 10), s.Revision) @@ -191,11 +240,7 @@ func validatePullSchedulingEvent(ctx context.Context, tx *sql.Tx, s PullScheduli if err := rows.Scan(&revision, &actor, &payload); err != nil { return err } - var event struct { - PullNumber int64 `json:"pull_number"` - Paused *bool `json:"paused"` - } - if count != 1 || revision != s.Revision || actor != s.ActorID || !payload.Valid || strictjson.Decode([]byte(payload.String), &event) != nil || event.PullNumber != s.PullNumber || event.Paused == nil || *event.Paused != s.Paused { + if count != 1 || revision != s.Revision || actor != s.ActorID || !validPullSchedulingPayload(payload, s.PullNumber, s.Paused) { return schedulingUnavailable() } } diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index c10f7eb53..0a40d6d95 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -1433,6 +1433,28 @@ func TestValidateSchedulingSnapshotRejectsStaleProjectProjection(t *testing.T) { attemptCode(t, validateSchedulingSnapshotForTest(t, f), "storage_unavailable") } +func TestValidateSchedulingSnapshotRejectsMissingPausedPullProjection(t *testing.T) { + f := schedulingFixture(t) + schedulingPause(t, f, 2, 0, true) + schedulingPause(t, f, 4, 0, true) + revision, resumed := int64(1), false + scope := selectionScope(t, f, attemptProject, f.writer, "write") + if _, err := f.e.ConfigurePullScheduling(t.Context(), scope, "resume-snapshot-control", 4, PullSchedulingRequest{ + ExpectedRevision: &revision, Paused: &resumed, + }); err != nil { + t.Fatal(err) + } + if err := validateSchedulingSnapshotForTest(t, f); err != nil { + t.Fatalf("healthy paused and resumed projections rejected: %v", err) + } + admissionSQL(t, f, `DELETE FROM review_pull_scheduling WHERE project_id=? AND pull_number=4`, attemptProject) + if err := validateSchedulingSnapshotForTest(t, f); err != nil { + t.Fatalf("absent projection for a latest genuine resume refused: %v", err) + } + admissionSQL(t, f, `DELETE FROM review_pull_scheduling WHERE project_id=? AND pull_number=2`, attemptProject) + attemptCode(t, validateSchedulingSnapshotForTest(t, f), "storage_unavailable") +} + func TestValidateSchedulingSnapshotRejectsMalformedAndFutureVersions(t *testing.T) { for _, tc := range []struct { name string From fedecd6af14fc5fb22ddd0b0b40a76fc34cdf774 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 23:03:53 +1300 Subject: [PATCH 16/41] Roll back automatic review enqueue on transient overload --- internal/reviewexec/scheduling_automatic.go | 8 ++- internal/reviewexec/scheduling_test.go | 57 +++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index eb2a96ed6..383cc333a 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -666,6 +666,10 @@ func (e *Engine) generateAutomaticProjectForAccount(ctx context.Context, project } func (e *Engine) acceptAutomaticProject(ctx context.Context, project, channel string, readers map[string]TargetReader, candidate *automaticProjectPlan) (bool, error) { + return e.acceptAutomaticProjectWithEnqueue(ctx, project, channel, readers, candidate, e.enqueueRunTx) +} + +func (e *Engine) acceptAutomaticProjectWithEnqueue(ctx context.Context, project, channel string, readers map[string]TargetReader, candidate *automaticProjectPlan, enqueue func(context.Context, *sql.Tx, core.Scope, RunRequest) (Receipt, error)) (bool, error) { worked := false err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { current, err := e.planAutomaticProject(ctx, tx, project, channel, readers) @@ -682,10 +686,10 @@ func (e *Engine) acceptAutomaticProject(ctx context.Context, project, channel st err = updateRunAt(ctx, tx, *current.retry, "queued", "", "", time.Now()) } else { // Same ordinary acceptance path, fully reauthorized in this snapshot. - receipt, enqueueErr := e.enqueueRunTx(ctx, tx, current.scope, RunRequest{Channel: channel}) + receipt, enqueueErr := enqueue(ctx, tx, current.scope, RunRequest{Channel: channel}) if enqueueErr != nil { var failure *core.Error - if errors.As(enqueueErr, &failure) && (failure.Status == 409 || failure.Code == "overloaded") { + if errors.As(enqueueErr, &failure) && failure.Status == 409 { return nil } return enqueueErr diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index 0a40d6d95..5bcf7f9a3 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -1478,3 +1478,60 @@ func TestValidateSchedulingSnapshotRequiresPresentDomainMetadata(t *testing.T) { t.Fatalf("missing optional domain metadata should not be mistaken for a schema version: %v", err) } } + +func TestAutomaticAcceptanceOverloadRollsBackPartialSelection(t *testing.T) { + f := schedulingFixture(t) + schedulingEnable(t, f, 0, true) + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}} + var candidate *automaticProjectPlan + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + candidate, err = f.e.planAutomaticProject(ctx, tx, attemptProject, "hosted", readers) + return err + }); err != nil || candidate == nil { + t.Fatalf("could not prepare automatic selection: %v", err) + } + assertCounts := func(want int) { + t.Helper() + for _, query := range []string{ + `SELECT count(*) FROM review_selections`, + `SELECT count(*) FROM review_automatic_selections`, + `SELECT count(*) FROM events WHERE event_type='review.selection_requested'`, + } { + var count int + if err := f.store.DB().QueryRowContext(t.Context(), query).Scan(&count); err != nil || count != want { + t.Fatalf("%s: count=%d want=%d err=%v", query, count, want, err) + } + } + } + conflict := func(context.Context, *sql.Tx, core.Scope, RunRequest) (Receipt, error) { + return Receipt{}, core.Fail("review_busy", "Synthetic prewrite conflict.", 409) + } + if worked, err := f.e.acceptAutomaticProjectWithEnqueue(t.Context(), attemptProject, "hosted", readers, candidate, conflict); worked || err != nil { + t.Fatalf("prewrite conflict was not benign: worked=%t err=%v", worked, err) + } + assertCounts(0) + // Exercise real writes, then inject a timeout-class failure at the enqueue + // boundary without relying on timing, an expired context or SQLite locks. + overloaded := core.Fail("overloaded", "Synthetic transient admission failure.", 503) + fault := func(ctx context.Context, tx *sql.Tx, scope core.Scope, req RunRequest) (Receipt, error) { + receipt, err := f.e.enqueueRunTx(ctx, tx, scope, req) + if err != nil { + return Receipt{}, err + } + if receipt.ID == "" || ctx.Err() != nil { + t.Fatal("no live-transaction selection to roll back", receipt, ctx.Err()) + } + return Receipt{}, overloaded + } + worked, err := f.e.acceptAutomaticProjectWithEnqueue(t.Context(), attemptProject, "hosted", readers, candidate, fault) + assertCounts(0) + var refusal *core.Error + if worked || !errors.As(err, &refusal) || refusal.Code != "overloaded" { + t.Fatalf("transient overload was not propagated: worked=%t err=%v", worked, err) + } + if worked, err := f.e.acceptAutomaticProject(t.Context(), attemptProject, "hosted", readers, candidate); !worked || err != nil { + t.Fatalf("clean retry failed: worked=%t err=%v", worked, err) + } + assertCounts(1) +} From 2193fa51c767c39311b599db24289d99d76df8aa Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 23:09:44 +1300 Subject: [PATCH 17/41] Validate automatic recovery and detached draft evidence --- internal/reviewexec/hosted_wait_validation.go | 11 +++--- .../scheduling_recovery0030_test.go | 35 +++++++++++++++++++ .../reviewexec/scheduling_source_retry.go | 5 +-- internal/reviewexec/scheduling_test.go | 18 ++++++++++ 4 files changed, 62 insertions(+), 7 deletions(-) diff --git a/internal/reviewexec/hosted_wait_validation.go b/internal/reviewexec/hosted_wait_validation.go index f2f8d12aa..00c9225d0 100644 --- a/internal/reviewexec/hosted_wait_validation.go +++ b/internal/reviewexec/hosted_wait_validation.go @@ -77,7 +77,7 @@ func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) } var firstDeadline, lastDeadline, baselineDeadline time.Time foundCurrent := o.AttemptID == "" - foundDraft := false + foundDetached, foundDraft := false, false for _, id := range ids { a, err := readAttempt(ctx, tx, o.ProjectID, id) if err != nil { @@ -96,15 +96,16 @@ func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) } continue } - _, draft, err := historicalUnusedPreparationOperation(ctx, tx, o, a, true) + historicalUnused, unused, err := historicalUnusedPreparationOperation(ctx, tx, o, a, true) if err != nil { if errors.Is(err, sql.ErrNoRows) { return waitUnavailable() } return err } - if draft { - foundDraft = true + if unused { + foundDetached = true + foundDraft = foundDraft || historicalUnused.Reason == cliDraftWait continue } if !hasBaseline { @@ -174,7 +175,7 @@ func validateOperationWaitHistory(ctx context.Context, tx *sql.Tx, o Operation) return waitUnavailable() } } - if !foundCurrent || o.Wait == nil && !foundDraft { + if !foundCurrent || o.Wait == nil && !foundDetached || o.Reason == cliDraftWait && !foundDraft { return waitUnavailable() } if hasBaseline { diff --git a/internal/reviewexec/scheduling_recovery0030_test.go b/internal/reviewexec/scheduling_recovery0030_test.go index c6d2c04d4..348e7170c 100644 --- a/internal/reviewexec/scheduling_recovery0030_test.go +++ b/internal/reviewexec/scheduling_recovery0030_test.go @@ -155,3 +155,38 @@ func TestRecovery0030InitialReadRequiresCompleteTransitionEvidence(t *testing.T) }) } } + +func TestRecovery0030InitialReadRequiresAlternationAndMatchingFinalState(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + recovery0030Claim(t, f, r.ID) + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + recovery0030Claim(t, f, r.ID) + r = selectionRead(t, f, r.ID) + assertInitial := func(run Run, want bool) { + t.Helper() + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + got, err := automaticSourceInitialRead(ctx, tx, run) + if err != nil { + return err + } + if got != want { + t.Errorf("transition proof=%t want=%t", got, want) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + assertInitial(r, true) + wrongFinal := r + wrongFinal.State = "queued" + assertInitial(wrongFinal, false) + admissionSQL(t, f, `UPDATE events SET payload_json='{"state":"queued","reason":""}' WHERE resource_id=? AND event_type='review.selection_updated' AND revision=2`, r.ID) + assertInitial(r, false) +} diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index c5d290824..56e2d5850 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -127,9 +127,10 @@ func automaticSourceInitialRead(ctx context.Context, tx *sql.Tx, r Run) (bool, e var count, distinct, first, last, invalid int64 err := tx.QueryRowContext(ctx, `SELECT count(*),count(DISTINCT revision),COALESCE(min(revision),0),COALESCE(max(revision),0),COALESCE(sum( CASE WHEN typeof(revision)='integer' AND json_valid(payload_json) THEN - CASE WHEN json_extract(payload_json,'$.state') IN ('queued','selecting') AND json_extract(payload_json,'$.reason')='' THEN 0 ELSE 1 END + CASE WHEN json_extract(payload_json,'$.state')=CASE WHEN revision%2=0 THEN 'selecting' ELSE 'queued' END + AND json_extract(payload_json,'$.reason')='' AND (revision<>? OR json_extract(payload_json,'$.state')=?) THEN 0 ELSE 1 END ELSE 1 END),0) - FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' AND revision BETWEEN 2 AND ?`, r.ProjectID, r.ID, r.Revision).Scan(&count, &distinct, &first, &last, &invalid) + FROM events WHERE project_id=? AND resource_id=? AND event_type='review.selection_updated' AND revision BETWEEN 2 AND ?`, r.Revision, r.State, r.ProjectID, r.ID, r.Revision).Scan(&count, &distinct, &first, &last, &invalid) if err != nil { return false, err } diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index 5bcf7f9a3..e8b6e1604 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -1535,3 +1535,21 @@ func TestAutomaticAcceptanceOverloadRollsBackPartialSelection(t *testing.T) { } assertCounts(1) } + +func TestSchedulingWaitSnapshotRequiresActualDraftProof(t *testing.T) { + f := schedulingFixture(t) + r := f.enqueue(t, attemptProject, "scheduling-only-cli", "cli", 2, 1) + a := f.start(t, attemptProject, r) + if _, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", "pull_scheduling_paused", ""); err != nil { + t.Fatal(err) + } + assertCLIWaitSnapshot(t, f) + o := cliWaitRead(t, f, r.ID) + o.Reason = cliDraftWait + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return validateOperationWaitHistory(ctx, tx, o) + }) + if err == nil { + t.Fatal("scheduling-only history was accepted as draft proof") + } +} From 197e5c9a015750821f2ee440f4e6034da75c1893 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 19 Nov 2026 23:14:50 +1300 Subject: [PATCH 18/41] Reselect Hosted work after its queue boundary expands --- internal/reviewexec/run_selection_worker.go | 30 ++++++++--- internal/reviewexec/scheduling_test.go | 60 +++++++++++++++++++++ 2 files changed, 84 insertions(+), 6 deletions(-) diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 60a58ba36..6d744f49f 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -163,11 +163,12 @@ func (r *runReads) ParentPull(ctx context.Context, repository, branch string) (r } type runChoice struct { - state, reason string - sourceReason string - prefix []SourcePlan - number int64 - head string + state, reason string + sourceReason string + prefix []SourcePlan + number int64 + head string + automaticHostedQueueLimit *int } // retryRunSelectionLocal retains completed source reads while only retrying @@ -216,7 +217,9 @@ func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configurati return e.chooseRunWithSourceBudget(ctx, r, repo, c, reader, e.runSourceBudget) } -func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (runChoice, error) { +func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (result runChoice, resultErr error) { + var automaticHostedQueueLimit *int + defer func() { result.automaticHostedQueueLimit = automaticHostedQueueLimit }() // Bound source work before metadata lookahead. Local suppression still // rechecks the live prefix at admission if queued work changes afterward. err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { @@ -234,6 +237,9 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 if limit < 0 || limit > len(c.Queue) { return schedulingUnavailable() } + if r.Channel == "hosted" { + automaticHostedQueueLimit = &limit + } c.Queue = c.Queue[:limit] return nil }) @@ -680,6 +686,18 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return updateRun(ctx, tx, current, "held", reason, "") } bindingValidated = true + if choice.automaticHostedQueueLimit != nil { + // The existing binding pins the configured queue. If its + // waiting boundary moved while reading source, do not settle + // the newly exposed suffix without an ordinary fresh read. + limit, err := automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + if err != nil { + return err + } + if limit > *choice.automaticHostedQueueLimit { + return updateRun(ctx, tx, current, "held", "selection_changed", "") + } + } if err = publishSourcePlans(ctx, tx, core.Scope{ProjectID: current.ProjectID, PrincipalID: current.ActorID, WorkerID: current.WorkerID}, repo, metadataPins, choice.prefix); err != nil { return err } diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index e8b6e1604..4ab2396f2 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -15,6 +15,7 @@ import ( "reflect" "strconv" "strings" + "sync/atomic" "testing" "time" ) @@ -1553,3 +1554,62 @@ func TestSchedulingWaitSnapshotRequiresActualDraftProof(t *testing.T) { t.Fatal("scheduling-only history was accepted as draft proof") } } + +func TestAutomaticSelectionDoesNotSettleNewlyExposedQueueSuffix(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4, 6}) + f.enqueue(t, attemptProject, "ordinary-queued-boundary", "hosted", 4, 1) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + before := schedulingLatest(t, f) + + var readSix atomic.Bool + reader := &refreshTestReader{ + repository: func(_ context.Context, id int64) (reviewprovider.Repository, error) { + schedulingPause(t, f, 4, 0, true) + return reviewprovider.Repository{ID: id, FullName: "owner/repo", DefaultBranch: "main"}, nil + }, + pull: func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { + if n == 6 { + readSix.Store(true) + } + return reviewprovider.Pull{Number: n, RepositoryID: 801, State: "closed", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }, + } + selectionNext(t, f, reader) + after := selectionRead(t, f, before.ID) + var basis string + if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, before.ID).Scan(&basis); err != nil { + t.Fatal(err) + } + if readSix.Load() || after.State != "held" || after.Reason != "selection_changed" || basis != "" { + t.Fatalf("unacquired suffix retired: readSix=%t state=%s reason=%s basis=%s", readSix.Load(), after.State, after.Reason, basis) + } + schedulingGenerate(t, f, true) + reader.repository = nil + selectionNext(t, f, reader) + if !readSix.Load() { + t.Fatal("fresh selection did not acquire newly exposed pull") + } +} + +func TestAutomaticCLISelectionKeepsExistingSourceLimit(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4, 6}) + f.enqueue(t, attemptProject, "ordinary-cli-queued-boundary", "cli", 4, 1) + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + r := schedulingLatest(t, f) + recovery0030Claim(t, f, r.ID) + r = selectionRead(t, f, r.ID) + var c Configuration + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + c, _, err = readConfiguration(ctx, tx, attemptProject) + return err + }); err != nil { + t.Fatal(err) + } + choice, err := f.e.chooseRun(t.Context(), r, 801, c, &refreshTestReader{}) + if err != nil || choice.automaticHostedQueueLimit != nil || len(choice.prefix) != 1 || choice.prefix[0].Pull.Number != 2 { + t.Fatalf("CLI source remains limited to PR2, without a Hosted settlement pin: %+v err=%v", choice, err) + } +} From fcde591c21a5f1c8a6d9229fc9eb747249c6b05e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 21 Nov 2026 00:41:07 +1300 Subject: [PATCH 19/41] Strengthen scheduling recovery proof and canonical declaration --- .../scheduling_recovery_regression_test.go | 16 ++++++++++++++-- internal/reviewexec/scheduling_schema.go | 6 ++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/internal/reviewexec/scheduling_recovery_regression_test.go b/internal/reviewexec/scheduling_recovery_regression_test.go index 5bac03b1d..796cee25f 100644 --- a/internal/reviewexec/scheduling_recovery_regression_test.go +++ b/internal/reviewexec/scheduling_recovery_regression_test.go @@ -320,8 +320,20 @@ func TestAutomaticCoordinatorIsolatesProjectState(t *testing.T) { if channel == "cli" { otherChannel = "hosted" } - if got := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections a JOIN review_selections s ON s.id=a.selection_id WHERE s.channel=?`, otherChannel); got < 1 { - t.Fatal("other channel was suppressed", got) + // Front frames and retry selections are channel-local. On the + // unaffected channel either project can legitimately be selected. + if fault == "front" || fault == "oversized-front" || fault == "retry-selection" { + if got := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections a JOIN review_selections s ON s.id=a.selection_id WHERE s.channel=?`, otherChannel); got < 1 { + t.Fatal("other channel was suppressed", got) + } + return + } + const otherProjectIntents = `SELECT count(*) FROM review_automatic_selections a JOIN review_selections s ON s.id=a.selection_id WHERE a.project_id=? AND s.channel=?` + if got := attemptCount(t, f.store, otherProjectIntents, otherAttemptProject, otherChannel); got != 1 { + t.Fatal("healthy project not selected on the other channel", got) + } + if got := attemptCount(t, f.store, otherProjectIntents, attemptProject, otherChannel); got != 0 { + t.Fatal("project with shared invalid state selected on the other channel", got) } }) } diff --git a/internal/reviewexec/scheduling_schema.go b/internal/reviewexec/scheduling_schema.go index 63db42f98..7c33554c1 100644 --- a/internal/reviewexec/scheduling_schema.go +++ b/internal/reviewexec/scheduling_schema.go @@ -20,13 +20,15 @@ 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 automatic_cli INTEGER NOT NULL DEFAULT 0 CHECK(automatic_cli IN(0,1))`} + 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] + ", automatic_cli INTEGER NOT NULL DEFAULT 0 CHECK(automatic_cli IN(0,1)))" + statements[0] = statements[0][:len(statements[0])-1] + ", " + schedulingAutomaticCLIColumn + ")" return statements } From eeb2ef166ec6dead3d5929e727a3e2fa5849db32 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 02:05:33 +1300 Subject: [PATCH 20/41] Reject cycles in retained front-frame parent observations --- internal/reviewexec/front_frame.go | 28 +++++++++++++++++++ internal/reviewexec/front_frame_cycle_test.go | 25 +++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 internal/reviewexec/front_frame_cycle_test.go diff --git a/internal/reviewexec/front_frame.go b/internal/reviewexec/front_frame.go index 5f8733794..66390dd0c 100644 --- a/internal/reviewexec/front_frame.go +++ b/internal/reviewexec/front_frame.go @@ -52,6 +52,7 @@ func validFrontFrame(f frontFrame, c Configuration, channel string) bool { } observed := "" var latest time.Time + parents := make(map[int64]int64, len(f.prefix)) for i, p := range f.prefix { if p.Number != c.Queue[i] || (p.State != "open" && p.State != "closed") || p.Merged && p.State != "closed" || !sha.MatchString(p.HeadSHA) || !sha.MatchString(p.BaseSHA) || !sha.MatchString(p.ParentSHA) || p.ParentSHA != p.BaseSHA || p.BaseRef == "" || !safeText(p.BaseRef, 256) || !roundTime(p.ObservedAt) || p.SourceReason != "" && !perPullSourceHold(p.SourceReason) { return false @@ -67,15 +68,42 @@ func validFrontFrame(f frontFrame, c Configuration, channel string) bool { } } + parents[p.Number] = p.ParentPullNumber + at, _ := time.Parse(time.RFC3339Nano, p.ObservedAt) if observed == "" || at.After(latest) { latest = at observed = p.ObservedAt } } + if !acyclicFrontParents(parents) { + return false + } checked, _ := time.Parse(time.RFC3339Nano, f.checkedAt) return f.observedAt == observed && (len(f.prefix) == 0 || !checked.Before(latest)) } + +// acyclicFrontParents checks observed edges only; an unobserved parent is not +// evidence of a cycle in the retained prefix. +func acyclicFrontParents(parents map[int64]int64) bool { + seen := make(map[int64]int64, len(parents)) + for start := range parents { + for number := start; number != 0; number = parents[number] { + if seen[number] == start { + return false + } + if seen[number] != 0 { + break + } + if _, observed := parents[number]; !observed { + break + } + seen[number] = start + } + } + return true +} + func writeFrontFrame(ctx context.Context, tx *sql.Tx, r Run, repo int64, c Configuration, choice runChoice) error { f := frontFrame{repository: repo, configuration: r.ConfigurationRevision, checkedAt: stamp(), sourceReason: choice.sourceReason, prefix: []frontPull{}} var hasProjection bool diff --git a/internal/reviewexec/front_frame_cycle_test.go b/internal/reviewexec/front_frame_cycle_test.go new file mode 100644 index 000000000..6893c8dad --- /dev/null +++ b/internal/reviewexec/front_frame_cycle_test.go @@ -0,0 +1,25 @@ +package reviewexec + +import ( + "strings" + "testing" +) + +func TestFrontFrameRejectsObservedParentCycle(t *testing.T) { + const observed = "2026-11-20T19:00:00Z" + var revision int64 + config := Configuration{ExpectedRevision: &revision, CapabilityID: "test", Mode: "stacked", Queue: []int64{2, 4, 6}, Channels: []string{"cli"}} + head2, head4, head6 := strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("c", 40) + pull := func(n, parent int64, head, base string) frontPull { + return frontPull{Number: n, ParentPullNumber: parent, HeadSHA: head, BaseSHA: base, ParentSHA: base, State: "open", BaseRef: "main", ObservedAt: observed} + } + frame := frontFrame{repository: 1, configuration: 1, checkedAt: observed, observedAt: observed, sourceReason: "source_unavailable", + prefix: []frontPull{pull(2, 4, head2, head4), pull(4, 6, head4, head6)}} + if !validFrontFrame(frame, config, "cli") { + t.Fatal("unobserved parent in the unacquired suffix rejected") + } + frame.prefix[1] = pull(4, 2, head4, head2) + if validFrontFrame(frame, config, "cli") { + t.Fatal("reciprocal observed parents accepted") + } +} From 400a3d9a00069319b4b7f7521038e6c23888c56f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 04:05:15 +1300 Subject: [PATCH 21/41] Test legacy retained cycle isolation without weakening writer validation --- .../scheduling_recovery_regression_test.go | 59 ++++++++++++++++--- 1 file changed, 52 insertions(+), 7 deletions(-) diff --git a/internal/reviewexec/scheduling_recovery_regression_test.go b/internal/reviewexec/scheduling_recovery_regression_test.go index 796cee25f..ebe84f2fd 100644 --- a/internal/reviewexec/scheduling_recovery_regression_test.go +++ b/internal/reviewexec/scheduling_recovery_regression_test.go @@ -150,18 +150,60 @@ func TestAutomaticGeneratorsIsolateRetainedParentCycle(t *testing.T) { admissionSQL(t, f, `UPDATE review_execution_config SET body_json=json_set(body_json,'$.mode','stacked') WHERE project_id=?`, attemptProject) now, sha := stamp(), strings.Repeat("a", 40) prefix := []frontPull{{Number: 2, State: "open", HeadSHA: sha, BaseSHA: sha, BaseRef: "four", ParentPullNumber: 4, ParentSHA: sha, ObservedAt: now}, {Number: 4, State: "open", HeadSHA: sha, BaseSHA: sha, BaseRef: "two", ParentPullNumber: 2, ParentSHA: sha, ObservedAt: now}} + // Use the real writer for both shapes: changing only the back edge + // must retain the valid prefix, while the cyclic prefix is degraded + // to the explicit unavailable frame before it reaches storage. + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + c, revision, err := readConfiguration(ctx, tx, attemptProject) + if err != nil { + return err + } + run := Run{ProjectID: attemptProject, ConfigurationRevision: revision, Channel: channel} + acyclic := append([]frontPull(nil), prefix...) + acyclic[1].ParentPullNumber = 0 + for _, candidate := range []struct { + prefix []frontPull + complete bool + reason string + }{ + {prefix: acyclic, complete: true}, + {prefix: prefix, reason: "source_unavailable"}, + } { + plans := (frontFrame{repository: 801, prefix: candidate.prefix}).plans() + if err := writeFrontFrame(ctx, tx, run, 801, c, runChoice{prefix: plans}); err != nil { + return err + } + frame, found, err := readFrontFrame(ctx, tx, attemptProject, channel) + if err != nil { + return err + } + wantPrefix := 0 + if candidate.complete { + wantPrefix = len(candidate.prefix) + } + if !found || frame.complete != candidate.complete || frame.sourceReason != candidate.reason || len(frame.prefix) != wantPrefix { + t.Fatalf("unexpected persisted front frame: found=%v complete=%v reason=%q prefix=%d", found, frame.complete, frame.sourceReason, len(frame.prefix)) + } + } + return nil + }); err != nil { + t.Fatal(err) + } + + // Simulate a legacy retained row from before the writer enforced + // the graph invariant; do not bypass the guard in production. raw, err := json.Marshal(prefix) if err != nil { t.Fatal(err) } - admissionSQL(t, f, `INSERT INTO review_front_frames VALUES(?,?,801,1,?,?,1,'',?)`, attemptProject, channel, now, now, string(raw)) - // Prove the fixture reaches the narrow cycle error, not generic corruption. + admissionSQL(t, f, `UPDATE review_front_frames SET checked_at=?,source_observed_at=?,complete=1,source_reason='',prefix_json=? WHERE project_id=? AND channel=?`, now, now, string(raw), attemptProject, channel) err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { _, err := automaticDependenciesChannel(ctx, tx, attemptProject, 2, channel) return err }) - if !errors.Is(err, errAutomaticParentCycle) { - t.Fatal("invalid cycle fixture", err) + var refusal *core.Error + if !automaticProjectRefused(err) || !errors.As(err, &refusal) || refusal.Code != "storage_unavailable" { + t.Fatal("expected a project-local retained-frame refusal", err) } for _, project := range []string{attemptProject, otherAttemptProject} { zero := int64(0) @@ -180,9 +222,12 @@ func TestAutomaticGeneratorsIsolateRetainedParentCycle(t *testing.T) { if err != nil || !worked { t.Fatal("project cycle stopped healthy project", worked, err) } - var project string - if err := f.store.DB().QueryRow(`SELECT project_id FROM review_automatic_selections`).Scan(&project); err != nil || project != otherAttemptProject { - t.Fatal(project, err) + var selections, healthy int + if err := f.store.DB().QueryRow(`SELECT count(*),count(CASE WHEN project_id=? THEN 1 END) FROM review_automatic_selections`, otherAttemptProject).Scan(&selections, &healthy); err != nil { + t.Fatal(err) + } + if selections != 1 || healthy != 1 { + t.Fatalf("expected exactly one selection for the healthy project: total=%d healthy=%d", selections, healthy) } // Shared storage failure must still reach the coordinator rather than being hidden. admissionSQL(t, f, `ALTER TABLE review_front_frames RENAME TO missing_front_frames`) From 86547426e0c1e24a4226e45636638d67ae1726b4 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 05:37:31 +1300 Subject: [PATCH 22/41] Address retained scheduling, fairness and restore review findings Bound queue and snapshot reads, preserve detached Hosted preflight during snapshot validation, and classify temporary preparation outcomes without changing live authorization or the legacy restore contract. --- internal/reviewexec/allowance_observation.go | 29 ++++- ...hosted_detached_preflight_snapshot_test.go | 60 ++++++++++ internal/reviewexec/hosted_priority.go | 3 + internal/reviewexec/round_controls.go | 2 +- .../reviewexec/run_selection_capacity_test.go | 28 +++++ internal/reviewexec/run_selection_worker.go | 32 +++--- internal/reviewexec/scheduling.go | 31 +++++- ...g_adjudication_basis_compatibility_test.go | 80 ++++++++++++++ .../scheduling_authorization_continuity.go | 6 +- internal/reviewexec/scheduling_automatic.go | 39 ++++++- internal/reviewexec/scheduling_cli.go | 55 ++++++++-- .../scheduling_cli_fairness_test.go | 26 +++++ .../reviewexec/scheduling_cli_priority.go | 10 +- internal/reviewexec/scheduling_cli_test.go | 15 +++ internal/reviewexec/scheduling_snapshot.go | 55 +++++++--- ...cheduling_snapshot_event_integrity_test.go | 103 ++++++++++++++++++ .../reviewexec/scheduling_source_retry.go | 29 +++-- .../scheduling_source_retry_test.go | 44 ++++++++ internal/reviewexec/scheduling_test.go | 97 +++++++++++------ internal/reviewexec/supervisor.go | 33 ++++-- .../supervisor_classification_test.go | 40 +++++++ internal/reviewexec/types.go | 1 + 22 files changed, 705 insertions(+), 113 deletions(-) create mode 100644 internal/reviewexec/hosted_detached_preflight_snapshot_test.go create mode 100644 internal/reviewexec/scheduling_adjudication_basis_compatibility_test.go create mode 100644 internal/reviewexec/scheduling_cli_fairness_test.go create mode 100644 internal/reviewexec/scheduling_snapshot_event_integrity_test.go create mode 100644 internal/reviewexec/supervisor_classification_test.go diff --git a/internal/reviewexec/allowance_observation.go b/internal/reviewexec/allowance_observation.go index 67e00d8b2..f24d2e9ff 100644 --- a/internal/reviewexec/allowance_observation.go +++ b/internal/reviewexec/allowance_observation.go @@ -27,6 +27,7 @@ const ( storedReviewAdmission storedConfigurationHistory storedOperationIdentity + storedRoundHistory ) type storedUnavailableError struct { @@ -107,6 +108,12 @@ func readCLIAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation, a } func readHostedAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (hostedAllowanceRecord, error) { + return readHostedAllowanceRecordForHistory(ctx, q, o, a, false) +} + +// Scheduling detachment is attribution for snapshot inspection only. Live +// allowance and query readers do not use it to authorize or recover actions. +func readHostedAllowanceRecordForHistory(ctx context.Context, q EvidenceQuery, o Operation, a Attempt, snapshot bool) (hostedAllowanceRecord, error) { var project, attempt string var body sql.NullString err := q.QueryRowContext(ctx, `SELECT project_id,attempt_id,CASE WHEN typeof(body_json)='text' AND length(CAST(body_json AS BLOB))<=16384 THEN body_json END FROM review_hosted_preflight WHERE attempt_id=?`, a.ID).Scan(&project, &attempt, &body) @@ -120,10 +127,22 @@ func readHostedAllowanceRecord(ctx context.Context, q EvidenceQuery, o Operation return hostedAllowanceRecord{}, allowanceUnavailable() } if o.AttemptID != a.ID { - var err error - o, err = historicalCooldownOperation(ctx, q, o, a) - if err != nil { - return hostedAllowanceRecord{}, allowanceDependencyError(err) + var retained bool + if snapshot && o.Channel == "hosted" { + var historical Operation + historical, retained, err = historicalUnusedPreparationOperation(ctx, q, o, a, true) + if err != nil { + return hostedAllowanceRecord{}, allowanceDependencyError(err) + } + if retained { + o = historical + } + } + if !retained { + o, err = historicalCooldownOperation(ctx, q, o, a) + if err != nil { + return hostedAllowanceRecord{}, allowanceDependencyError(err) + } } } if !validAllowanceOwners(o, a) { @@ -289,7 +308,7 @@ func ValidateAllowanceSnapshot(ctx context.Context, q EvidenceQuery, executionVe if table == "review_cli_preflight" { _, err = readCLIAllowanceRecord(ctx, q, o, a) } else { - _, err = readHostedAllowanceRecord(ctx, q, o, a) + _, err = readHostedAllowanceRecordForHistory(ctx, q, o, a, true) } if err != nil { return err diff --git a/internal/reviewexec/hosted_detached_preflight_snapshot_test.go b/internal/reviewexec/hosted_detached_preflight_snapshot_test.go new file mode 100644 index 000000000..0f6f9b948 --- /dev/null +++ b/internal/reviewexec/hosted_detached_preflight_snapshot_test.go @@ -0,0 +1,60 @@ +package reviewexec + +import ( + "testing" +) + +func TestHostedSnapshotRetainsUnusedSchedulingPreflight(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_scheduling_unavailable"} { + t.Run(reason, func(t *testing.T) { + f, first, _, input := hostedAllowanceFixture(t) + if err := f.e.RecordHostedAllowance(t.Context(), attemptProject, first.ID, first.Revision, input); err != nil { + t.Fatal(err) + } + if _, err := f.e.Advance(t.Context(), attemptProject, first.ID, first.Revision, "held", reason, ""); err != nil { + t.Fatal(err) + } + check := func() { + t.Helper() + tables := []string{"review_hosted_preflight", "review_hosted_allowance_queries", "review_operations", "review_operation_waits"} + before := make([]string, len(tables)) + for i, table := range tables { + before[i] = snapshotTable(t, f, table) + } + tx, err := f.store.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if err := ValidateAllowanceSnapshot(t.Context(), tx, 10); err != nil { + t.Fatalf("valid detached Hosted preflight refused: %v", err) + } + for i, table := range tables { + if after := snapshotTableThrough(t, tx, table); before[i] != after { + t.Fatalf("snapshot wrote to %s inside inspection", table) + } + } + } + check() + next := f.start(t, attemptProject, Receipt{ID: first.OperationID}) + if next.ID == "" || next.ID == first.ID { + t.Fatal("new attempt not independently attached", next) + } + check() + o, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, first.OperationID) + if err != nil { + t.Fatal(err) + } + if o.AttemptID != next.ID { + t.Fatal("snapshot rebound the current operation", o.AttemptID) + } + detached, err := readAttempt(t.Context(), f.store.DB(), attemptProject, first.ID) + if err != nil { + t.Fatal(err) + } + if _, err := readHostedAllowanceRecord(t.Context(), f.store.DB(), o, detached); err == nil { + t.Fatal("live allowance lookup accepted detached scheduling history") + } + }) + } +} diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 97cb72b6e..16d8d967c 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -82,6 +82,9 @@ 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 { + if pullSchedulingRefused(err) { + continue + } return nil, err } if valid { diff --git a/internal/reviewexec/round_controls.go b/internal/reviewexec/round_controls.go index d1b474915..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 { diff --git a/internal/reviewexec/run_selection_capacity_test.go b/internal/reviewexec/run_selection_capacity_test.go index fbde2490c..475ebb49c 100644 --- a/internal/reviewexec/run_selection_capacity_test.go +++ b/internal/reviewexec/run_selection_capacity_test.go @@ -164,3 +164,31 @@ func TestRunSelectionCapacityPreservesActualChild409AndSavepoint(t *testing.T) { t.Fatal("actual 409 retried or retained partial child work", got) } } + +func TestAutomaticSelectionCapacityDoesNotSettlePendingBasis(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + r := schedulingLatest(t, f) + reader := &refreshTestReader{ + repository: func(_ context.Context, id int64) (reviewprovider.Repository, error) { + selectionCapacityFill(t, f, attemptProject) + return reviewprovider.Repository{ID: id, FullName: "owner/repo", DefaultBranch: "main"}, nil + }, + } + selectionNext(t, f, reader) + var settled string + if err := f.store.DB().QueryRow("SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?", r.ID).Scan(&settled); err != nil { + t.Fatal(err) + } + got := selectionRead(t, f, r.ID) + if got.State != "queued" || got.OperationID != "" || settled != "" { + t.Fatalf("capacity retry must retain its unsettled selection: %+v basis=%q", got, settled) + } + selectionCapacityRelease(t, f, attemptProject) + selectionNext(t, f, &refreshTestReader{}) + got = selectionRead(t, f, r.ID) + if got.State != "selected" || got.OperationID == "" { + t.Fatalf("same selection did not retry after capacity release: %+v", got) + } +} diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index e9f3c4292..163f7bc96 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -163,12 +163,12 @@ 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 - automaticHostedQueueLimit *int + state, reason string + sourceReason string + prefix []SourcePlan + number int64 + head string + automaticQueueLimit *int } // retryRunSelectionLocal retains completed source reads while only retrying @@ -218,8 +218,8 @@ func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configurati } func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (result runChoice, resultErr error) { - var automaticHostedQueueLimit *int - defer func() { result.automaticHostedQueueLimit = automaticHostedQueueLimit }() + var automaticQueueLimit *int + defer func() { result.automaticQueueLimit = automaticQueueLimit }() // 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 @@ -247,8 +247,8 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 if err != nil { return runChoice{}, err } - if automatic && r.Channel == "hosted" { - automaticHostedQueueLimit = &limit + if automatic { + automaticQueueLimit = &limit } c.Queue = c.Queue[:limit] if len(c.Queue) == 0 { @@ -650,12 +650,12 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat defer func() { if resultErr == nil && bindingValidated { var pull int64 - var reason string - if err := tx.QueryRowContext(ctx, `SELECT COALESCE(o.pull_number,0),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, &reason); err != nil { + 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 } - if reason != "selection_changed" { + if state != "queued" && reason != "selection_changed" { resultErr = e.settleAutomaticBasis(ctx, tx, r, pull) } } @@ -692,15 +692,15 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat return updateRun(ctx, tx, current, "held", reason, "") } bindingValidated = true - if choice.automaticHostedQueueLimit != nil { + if choice.automaticQueueLimit != nil { // The existing binding pins the configured queue. If its // waiting boundary moved while reading source, do not settle - // the newly exposed suffix without an ordinary fresh read. + // stale source bounds without an ordinary fresh read. limit, err := automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) if err != nil { return err } - if limit > *choice.automaticHostedQueueLimit { + if limit != *choice.automaticQueueLimit { return updateRun(ctx, tx, current, "held", "selection_changed", "") } } diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index 1fdad1996..23a1bccf3 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -71,9 +71,32 @@ type schedulingRecord struct { actor, credential string } +// Scheduling failures are a subset of project-local failures. A pull-local +// refusal is independent of other pulls; shared scheduling faults are not. +type schedulingStateError struct { + error + pullLocal bool +} + +func (e *schedulingStateError) Unwrap() error { return e.error } + func schedulingUnavailable() error { return automaticProjectStateFailure("storage_unavailable", "Stored review scheduling is unavailable.", 503) } + +func schedulingRecordUnavailable(pullLocal bool) error { + return &schedulingStateError{error: schedulingUnavailable(), pullLocal: pullLocal} +} + +func schedulingRefused(err error) bool { + var scheduling *schedulingStateError + return errors.As(err, &scheduling) +} + +func pullSchedulingRefused(err error) bool { + var scheduling *schedulingStateError + return errors.As(err, &scheduling) && scheduling.pullLocal +} 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 @@ -95,11 +118,11 @@ func readScheduling(ctx context.Context, tx *sql.Tx, project string) (s scheduli 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, schedulingUnavailable() + return s, schedulingRecordUnavailable(false) } 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, schedulingUnavailable() + return s, schedulingRecordUnavailable(false) } return s, nil } @@ -295,11 +318,11 @@ func readPullScheduling(ctx context.Context, tx *sql.Tx, project string, pull in s.ActorID, actorOK = actor.(string) s.UpdatedAt, updatedOK = updated.(string) if !revisionOK || !pausedOK || !reasonOK || !actorOK || !updatedOK || pausedValue < 0 || pausedValue > 1 { - return s, schedulingUnavailable() + return s, schedulingRecordUnavailable(true) } s.Paused = pausedValue == 1 if s.Revision < 1 || !identifier.MatchString(s.ActorID) || !roundTime(s.UpdatedAt) || !validSchedulingReason(s.Reason) || !s.Paused && s.Reason != "" { - return s, schedulingUnavailable() + return s, schedulingRecordUnavailable(true) } return s, nil } diff --git a/internal/reviewexec/scheduling_adjudication_basis_compatibility_test.go b/internal/reviewexec/scheduling_adjudication_basis_compatibility_test.go new file mode 100644 index 000000000..9adc515a2 --- /dev/null +++ b/internal/reviewexec/scheduling_adjudication_basis_compatibility_test.go @@ -0,0 +1,80 @@ +package reviewexec + +import ( + "bytes" + "database/sql" + "encoding/json" + "testing" +) + +func TestAutomaticAdjudicationBasisPreservesValidRetainedDigest(t *testing.T) { + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + tx, err := db.BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + for _, ddl := range []string{ + "CREATE TABLE review_adjudication_state(evidence_id TEXT,revision INTEGER,project_id TEXT)", + "CREATE TABLE review_execution_evidence(id TEXT,project_id TEXT,operation_id TEXT,body_json TEXT)", + "CREATE TABLE review_operations(id TEXT,project_id TEXT,pull_number INTEGER,channel TEXT)", + } { + if _, err = tx.ExecContext(t.Context(), ddl); err != nil { + t.Fatal(err) + } + } + for _, row := range []struct { + id, project, channel, body string + pull int + }{ + {"e1", "p", "cli", `{"capture":{"review":{"Findings":[]}}}`, 2}, + {"e2", "p", "hosted", `{"capture":{"review":{"Findings":[{"Title":"Valid finding"}]}}}`, 2}, + {"e3", "p", "hosted", `{"capture":{"review":{"Findings":null}}}`, 2}, + {"e4", "p", "cli", `{"capture":{"review":{"Findings":[{"Title":"Valid finding"}]}}}`, 2}, + {"e5", "p", "hosted", `{"capture":{"review":{"Findings":[]}}}`, 4}, + {"e6", "q", "cli", `{"capture":{"review":{"Findings":[{"Title":"Valid finding"}]}}}`, 2}, + } { + if _, err = tx.ExecContext(t.Context(), "INSERT INTO review_adjudication_state VALUES(?,1,?)", row.id, row.project); err != nil { + t.Fatal(err) + } + if _, err = tx.ExecContext(t.Context(), "INSERT INTO review_execution_evidence VALUES(?,?,?,?)", row.id, row.project, row.id, row.body); err != nil { + t.Fatal(err) + } + if _, err = tx.ExecContext(t.Context(), "INSERT INTO review_operations VALUES(?,?,?,?)", row.id, row.project, row.pull, row.channel); err != nil { + t.Fatal(err) + } + } + for _, channel := range []string{"cli", "hosted"} { + label := automaticAdjudicationBasisLabel(channel) + var before, after bytes.Buffer + before.WriteString(label) + before.WriteByte(0) + rows, err := tx.QueryContext(t.Context(), label, "p", 2) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var id string + var revision int64 + if err = rows.Scan(&id, &revision); err != nil { + t.Fatal(err) + } + if err = json.NewEncoder(&before).Encode([]any{id, revision}); err != nil { + t.Fatal(err) + } + } + if err = rows.Close(); err != nil { + t.Fatal(err) + } + if err = automaticBasisAppender(t.Context(), tx, &after, channel, 1)(label, false, "p", 2); err != nil { + t.Fatal(err) + } + if !bytes.Equal(before.Bytes(), after.Bytes()) { + t.Fatalf("%s changed valid digest input", channel) + } + } +} diff --git a/internal/reviewexec/scheduling_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go index 8e41cb112..4587945d5 100644 --- a/internal/reviewexec/scheduling_authorization_continuity.go +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -35,7 +35,7 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision if revision < 1 || revision >= current.Revision || current.Revision-revision > 10000 { return false, nil } - rows, err := tx.QueryContext(ctx, `SELECT revision,actor_id,payload_json FROM events WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision BETWEEN ? AND ? ORDER BY revision,sequence LIMIT 10002`, r.ProjectID, r.ProjectID, revision, current.Revision) + rows, err := tx.QueryContext(ctx, `SELECT revision,actor_id,CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND event_type='review.scheduling_updated' AND resource_id=? AND revision BETWEEN ? AND ? ORDER BY revision,sequence LIMIT 10002`, r.ProjectID, r.ProjectID, revision, current.Revision) if err != nil { return false, err } @@ -44,7 +44,7 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision for rows.Next() { var retainedRevision any var actor string - var payload []byte + var payload sql.NullString if err = rows.Scan(&retainedRevision, &actor, &payload); err != nil { return false, err } @@ -56,7 +56,7 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision Hosted *bool `json:"automatic_hosted"` CLI *bool `json:"automatic_cli"` } - if len(payload) > 4096 || strictjson.Validate(payload) != nil || json.Unmarshal(payload, &settings) != nil { + if !payload.Valid || strictjson.Validate([]byte(payload.String)) != nil || json.Unmarshal([]byte(payload.String), &settings) != nil { return false, nil } enabled := settings.Hosted diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 383cc333a..ec0055142 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -10,6 +10,7 @@ import ( "errors" "io" "slices" + "strconv" "strings" "time" @@ -175,6 +176,32 @@ func automaticPullBasisChannel(ctx context.Context, tx *sql.Tx, project string, return automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) } +// This historical label is part of the retained digest. Do not change it +// when tightening the SQL used to obtain the same valid rows. +func automaticAdjudicationBasisLabel(channel string) string { + return `SELECT a.evidence_id,a.revision FROM review_adjudication_state a JOIN review_execution_evidence e ON e.id=a.evidence_id AND e.project_id=a.project_id JOIN review_operations o ON o.id=e.operation_id AND o.project_id=e.project_id WHERE a.project_id=? AND o.pull_number=? AND (o.channel='` + channel + `' OR json_array_length(json_extract(e.body_json,'$.capture.review.Findings'))>0) ORDER BY a.evidence_id LIMIT 10001` +} + +func automaticAdjudicationBasisSQL(channel string) string { + // CASE keeps JSON functions away from unavailable input. A null/omitted + // slice was historically empty, not malformed. Keep same-channel rows + // and their contribution independent of the opposite-channel test. + return `WITH evidence AS ( + SELECT a.evidence_id,a.revision,CASE + WHEN o.channel='` + channel + `' THEN 1 + WHEN typeof(e.body_json)='text' AND length(CAST(e.body_json AS BLOB))<=` + strconv.Itoa(MaxEvidenceInputBytes+8192) + ` + THEN CASE WHEN json_valid(e.body_json) THEN CASE + WHEN json_type(e.body_json,'$.capture.review.Findings')='array' THEN json_array_length(e.body_json,'$.capture.review.Findings') + WHEN COALESCE(json_type(e.body_json,'$.capture.review.Findings'),'null')='null' THEN 0 + END END END AS count + FROM review_adjudication_state a JOIN review_execution_evidence e ON e.id=a.evidence_id AND e.project_id=a.project_id + JOIN review_operations o ON o.id=e.operation_id AND o.project_id=e.project_id + WHERE a.project_id=? AND o.pull_number=? + ) + SELECT CASE WHEN count IS NOT NULL THEN evidence_id END,revision FROM evidence + WHERE count IS NULL OR count>0 ORDER BY evidence_id LIMIT 10001` +} + func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channel string, basisRevision int64) func(string, bool, ...any) error { return func(query string, pinJoins bool, args ...any) error { if channel == "cli" { @@ -182,7 +209,12 @@ func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channe } h.Write([]byte(query)) h.Write([]byte{0}) - rows, err := tx.QueryContext(ctx, automaticBasisQuery(query, pinJoins), args...) + 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 } @@ -210,6 +242,9 @@ func automaticBasisAppender(ctx context.Context, tx *sql.Tx, h io.Writer, channe values[i] = string(b) } } + if adjudication && values[0] == nil { + return schedulingUnavailable() + } // Keep the original query label and JSON framing. Only the // channel's semantic revision differs after a relevant write. if query == `SELECT revision,automatic_`+channel+` FROM review_scheduling WHERE project_id=?` { @@ -240,7 +275,7 @@ func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string, }{ {`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}}, - {`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`, []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}}, } diff --git a/internal/reviewexec/scheduling_cli.go b/internal/reviewexec/scheduling_cli.go index eccb1b065..01fa3da95 100644 --- a/internal/reviewexec/scheduling_cli.go +++ b/internal/reviewexec/scheduling_cli.go @@ -7,22 +7,49 @@ import ( "github.com/benhook1013/FireController/internal/core" ) -func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]TargetReader) (bool, error) { +const automaticCLITraversalLimit = 100 + +// Each priority group has independent wraparound and a reserved part of the +// bounded traversal. An idle group lends its unused slots to the other one. +func automaticCLIProjects(ctx context.Context, tx *sql.Tx, preferred bool, cursor string, limit int) ([]string, error) { + rows, err := tx.QueryContext(ctx, `SELECT s.project_id FROM review_scheduling s LEFT JOIN projects p ON p.id=s.project_id + WHERE s.automatic_cli=1 AND COALESCE(lower(p.repository)=?,0)=? + ORDER BY (s.project_id<=?),s.project_id LIMIT ?`, preferredCLIRepository, preferred, cursor, limit) + if err != nil { + return nil, err + } + defer rows.Close() var projects []string + for rows.Next() { + var project string + if err = rows.Scan(&project); err != nil { + return nil, err + } + projects = append(projects, project) + } + if err = rows.Err(); err != nil { + return nil, err + } + return projects, rows.Close() +} + +func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]TargetReader) (bool, error) { + var preferred, other []string if err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { - rows, err := tx.QueryContext(ctx, `SELECT project_id FROM review_scheduling WHERE automatic_cli=1 ORDER BY (SELECT lower(repository) FROM projects WHERE id=project_id)<>?,(project_id<=?),project_id LIMIT 100`, preferredCLIRepository, e.automaticCLICursor) + const half = automaticCLITraversalLimit / 2 + var err error + preferred, err = automaticCLIProjects(ctx, tx, true, e.automaticCLICursor, half) if err != nil { return err } - defer rows.Close() - for rows.Next() { - var p string - if err = rows.Scan(&p); err != nil { - return err - } - projects = append(projects, p) + other, err = automaticCLIProjects(ctx, tx, false, e.automaticCLIOtherCursor, automaticCLITraversalLimit-len(preferred)) + if err != nil { + return err + } + if len(preferred) == half && len(other) < half { + preferred, err = automaticCLIProjects(ctx, tx, true, e.automaticCLICursor, automaticCLITraversalLimit-len(other)) } - return rows.Err() + return err }); err != nil { return false, err } @@ -31,8 +58,12 @@ func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]Ta // must not starve simply because preferred work is always available. generated := false selectedAccounts := map[string]bool{} - for _, project := range projects { - e.automaticCLICursor = project + for i, project := range append(preferred, other...) { + if i < len(preferred) { + e.automaticCLICursor = project + } else { + e.automaticCLIOtherCursor = project + } var account string err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { c, _, err := readConfiguration(ctx, tx, project) diff --git a/internal/reviewexec/scheduling_cli_fairness_test.go b/internal/reviewexec/scheduling_cli_fairness_test.go new file mode 100644 index 000000000..69e897c65 --- /dev/null +++ b/internal/reviewexec/scheduling_cli_fairness_test.go @@ -0,0 +1,26 @@ +package reviewexec + +import ( + "testing" +) + +func TestAutomaticCLITraversalReachesOrdinaryProjectBehindPreferredWindow(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + // Idle projects have an enabled schedule but haven't configured execution. + // Insert durable fixture rows from an ordinary enabled template. + schedulingCLIEnable(t, f, 0, true) + admissionSQL(t, f, `WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<110) + INSERT INTO projects(id,name,github_repository_id,repository) + SELECT printf('preferred-%03d',i),printf('Preferred %03d',i),10000+i,'benhook1013/FireMUD' FROM n`) + admissionSQL(t, f, `INSERT INTO review_scheduling(project_id,revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at) + SELECT p.id,s.revision,s.automatic_hosted,s.automatic_cli,s.actor_id,s.worker_id,s.credential_id,s.updated_at + FROM projects p CROSS JOIN review_scheduling s WHERE p.id LIKE 'preferred-%' AND s.project_id=?`, attemptProject) + worked, err := f.e.generateAutomaticCLI(t.Context(), map[string]TargetReader{"test-capability": &refreshTestReader{}}) + if err != nil || !worked { + t.Fatalf("preferred idle rows starved configured ordinary project: worked=%v err=%v", worked, err) + } + var selections int + if err := f.store.DB().QueryRow("SELECT count(*) FROM review_automatic_selections WHERE project_id=?", attemptProject).Scan(&selections); err != nil || selections != 1 { + t.Fatalf("wanted exactly one ordinary-project selection, got %d, err=%v", selections, err) + } +} diff --git a/internal/reviewexec/scheduling_cli_priority.go b/internal/reviewexec/scheduling_cli_priority.go index ed1fb0788..db76bb62a 100644 --- a/internal/reviewexec/scheduling_cli_priority.go +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -3,6 +3,7 @@ package reviewexec import ( "context" "database/sql" + "slices" "strings" "time" ) @@ -147,7 +148,14 @@ candidates: if prior.Provider != capability.Provider || prior.Account != capability.Account { continue } - for _, pull := range c.Queue { + queue := c.Queue + if r.ExpectedPullNumber != 0 { + if !slices.Contains(queue, r.ExpectedPullNumber) { + continue + } + queue = []int64{r.ExpectedPullNumber} + } + for _, pull := range queue { pause, err := readPullScheduling(ctx, tx, r.ProjectID, pull) if err != nil { if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { diff --git a/internal/reviewexec/scheduling_cli_test.go b/internal/reviewexec/scheduling_cli_test.go index b9f1a6f05..8fb8e334e 100644 --- a/internal/reviewexec/scheduling_cli_test.go +++ b/internal/reviewexec/scheduling_cli_test.go @@ -612,3 +612,18 @@ func TestAutomaticCLIAccountChangeWaitsForNextPass(t *testing.T) { t.Fatal("fresh account produced an unexpected attribution count", got) } } + +func TestSchedulingCLIPinnedPausedSelectionDoesNotClaimPriority(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4}) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + admissionSQL(t, f, "UPDATE projects SET repository='benhook1013/FireMUD' WHERE id=?", attemptProject) + schedulingPause(t, f, 2, 0, true) + pinned := int64(2) + if _, err := f.e.EnqueueRun(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "explicit-pinned-pr", RunRequest{Channel: "cli", ExpectedPullNumber: &pinned}); err != nil { + t.Fatal(err) + } + low := f.enqueue(t, otherAttemptProject, "nonpreferred-pull", "cli", 2, 1) + if a, err := f.e.StartAttempt(t.Context(), otherAttemptProject, low.ID); err != nil || a.ID == "" { + t.Fatalf("pinned paused selection stalled healthy project's attempt: %+v %v", a, err) + } +} diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index c7e4d7a77..ec294560e 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -61,11 +61,13 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { if closeErr != nil { return closeErr } - // A retained projection cannot predate a matching scheduling event. + // A genuine project scheduling event must have a projection at least + // as new. Only projects with no retained history default to revision zero. var ahead bool - err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_scheduling s WHERE EXISTS( - SELECT 1 FROM events e WHERE e.project_id=s.project_id AND e.resource_id=s.project_id - AND e.event_type='review.scheduling_updated' AND e.revision>s.revision))`).Scan(&ahead) + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM events e + LEFT JOIN review_scheduling s ON s.project_id=e.project_id + WHERE e.event_type='review.scheduling_updated' AND e.resource_id=e.project_id + AND (s.project_id IS NULL OR e.revision>s.revision))`).Scan(&ahead) if err != nil { return err } @@ -77,6 +79,7 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { 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 { @@ -86,9 +89,7 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { err = schedulingUnavailable() break } - if err = validatePullSchedulingEvent(ctx, tx, s); err != nil { - break - } + controls++ } if err == nil { err = rows.Err() @@ -100,6 +101,9 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { if closeErr != nil { return closeErr } + if err := validatePullSchedulingEvents(ctx, tx, controls); err != nil { + return err + } if err := validateOrphanPullSchedulingEvents(ctx, tx); err != nil { return err } @@ -224,30 +228,49 @@ func validPullSchedulingPayload(payload sql.NullString, pull int64, paused bool) event.PullNumber == pull && event.Paused != nil && *event.Paused == paused } -// A restored control must agree with its latest retained user decision. -func validatePullSchedulingEvent(ctx context.Context, tx *sql.Tx, s PullScheduling) error { - rows, err := tx.QueryContext(ctx, `SELECT revision,actor_id,CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END FROM events WHERE project_id=? AND event_type='review.pull_scheduling_updated' AND resource_id=? AND revision>=? ORDER BY revision DESC,sequence DESC LIMIT 2`, s.ProjectID, strconv.FormatInt(s.PullNumber, 10), s.Revision) +// Scan the event journal once for existing pull controls. With events on the +// outer side of this join, SQLite can seek the control's composite primary key +// rather than reading the same project's event history once for each control. +// Ordered qualifying matches keep duplicate detection constant-space. +const pullSchedulingSnapshotEventsSQL = `SELECT s.project_id,s.pull_number,s.revision,s.paused,s.actor_id, + e.revision,e.actor_id,CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END + FROM events e CROSS JOIN review_pull_scheduling s + WHERE e.event_type='review.pull_scheduling_updated' AND s.project_id=e.project_id + AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id + AND e.revision>=s.revision + ORDER BY s.project_id,s.pull_number` + +func validatePullSchedulingEvents(ctx context.Context, tx *sql.Tx, controls int) error { + if controls == 0 { + return nil + } + rows, err := tx.QueryContext(ctx, pullSchedulingSnapshotEventsSQL) if err != nil { return err } defer rows.Close() count := 0 + var lastProject string + var lastPull int64 for rows.Next() { - count++ - var revision int64 - var actor string + var project, actor, eventActor string + var pull, controlRevision, paused int64 + var nativeRevision any var payload sql.NullString - if err := rows.Scan(&revision, &actor, &payload); err != nil { + if err := rows.Scan(&project, &pull, &controlRevision, &paused, &actor, &nativeRevision, &eventActor, &payload); err != nil { return err } - if count != 1 || revision != s.Revision || actor != s.ActorID || !validPullSchedulingPayload(payload, s.PullNumber, s.Paused) { + revision, integer := nativeRevision.(int64) + if (project == lastProject && pull == lastPull) || !integer || revision != controlRevision || eventActor != actor || !validPullSchedulingPayload(payload, pull, paused == 1) { return schedulingUnavailable() } + count++ + lastProject, lastPull = project, pull } if err := rows.Err(); err != nil { return err } - if count != 1 { + 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..7e89bfb2a --- /dev/null +++ b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go @@ -0,0 +1,103 @@ +package reviewexec + +import ( + "database/sql" + "testing" +) + +func schedulingEventSnapshotFixture(t *testing.T) *sql.Tx { + t.Helper() + db, err := sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatal(err) + } + db.SetMaxOpenConns(1) + t.Cleanup(func() { db.Close() }) + tx, err := db.BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { tx.Rollback() }) + // These are in-memory snapshot inputs, not changes to a running project. + // Keep event revision untyped to model the native value delivered to Scan. + for _, statement := range []string{ + "CREATE TABLE metadata(key,value)", + "INSERT INTO metadata VALUES ('schema:review_scheduling','2')", + "CREATE TABLE events(sequence INTEGER PRIMARY KEY, project_id, resource_id, event_type, revision, actor_id, payload_json)", + "CREATE TABLE review_scheduling(project_id,revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at)", + "CREATE TABLE review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at)", + "CREATE TABLE review_automatic_selections(selection_id,project_id,scheduling_revision,basis_sha256,settled_basis_sha256,pull_number,pull_basis_sha256,actor_id,worker_id,credential_id)", + "CREATE TABLE review_selections(id,project_id,channel,state,actor_id,worker_id,operation_id)", + "CREATE TABLE review_operations(id,project_id,pull_number,channel,actor_id,worker_id)", + "CREATE TABLE workers(project_id,id)", + "CREATE TABLE credentials(id,principal_id)", + } { + if _, err := tx.ExecContext(t.Context(), statement); err != nil { + t.Fatal(err) + } + } + return tx +} + +func TestSchedulingSnapshotRequiresEnabledProjectProjection(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + if err := ValidateSchedulingSnapshot(t.Context(), tx); err != nil { + t.Fatalf("project with no scheduling history: %v", err) + } + // An ordinary configure event in a partial snapshot with no control row. + _, err := tx.ExecContext(t.Context(), `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json) + VALUES ('test-project','test-project','review.scheduling_updated',1,'test-actor','{"automatic_hosted":true}')`) + if err != nil { + t.Fatal(err) + } + attemptCode(t, ValidateSchedulingSnapshot(t.Context(), tx), "storage_unavailable") +} + +func TestSchedulingSnapshotRequiresNativeEventRevision(t *testing.T) { + for _, tc := range []struct { + name string + revision any + valid bool + }{{"integer", int64(1), true}, {"real", float64(1), false}} { + t.Run(tc.name, func(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + _, err := tx.ExecContext(t.Context(), `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json) + VALUES ('test-project','2','review.pull_scheduling_updated',?,'test-actor','{"pull_number":2,"paused":true}')`, tc.revision) + if err != nil { + t.Fatal(err) + } + if _, err := tx.ExecContext(t.Context(), `INSERT INTO review_pull_scheduling VALUES ('test-project',2,1,1,'','test-actor',?)`, stamp()); err != nil { + t.Fatal(err) + } + err = ValidateSchedulingSnapshot(t.Context(), tx) + if tc.valid { + if err != nil { + t.Fatalf("native revision refused: %v", err) + } + } else { + attemptCode(t, err, "storage_unavailable") + } + }) + } +} + +// Different projects can legitimately schedule the same pull number. Each +// one's newest event must remain attached to its own represented control. +func TestSchedulingSnapshotPullEventStreamKeepsProjectIdentity(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + if _, err := tx.ExecContext(t.Context(), `INSERT INTO review_pull_scheduling VALUES + ('test-project',2,2,0,'','test-actor',?), + ('other-project',2,1,1,'','other-actor',?)`, stamp(), stamp()); err != nil { + t.Fatal(err) + } + if _, err := tx.ExecContext(t.Context(), `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json) VALUES + ('test-project','2','review.pull_scheduling_updated',1,'test-actor','{"pull_number":2,"paused":true}'), + ('other-project','2','review.pull_scheduling_updated',1,'other-actor','{"pull_number":2,"paused":true}'), + ('test-project','2','review.pull_scheduling_updated',2,'test-actor','{"pull_number":2,"paused":false}'), + ('other-project','2','ordinary.event',9,'other-actor','{}')`); err != nil { + t.Fatal(err) + } + if err := ValidateSchedulingSnapshot(t.Context(), tx); err != nil { + t.Fatal(err) + } +} diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index 56e2d5850..e1f02ae17 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -99,14 +99,12 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin if err != nil { return "", err } + initial, err := automaticSourceInitialRead(ctx, tx, r) + if err != nil || initial { + return "", err + } if accepted != current { - initial, err := automaticSourceInitialRead(ctx, tx, r) - if err != nil { - return "", err - } - if !initial { - return "automation_authorization_changed", nil - } + return "automation_authorization_changed", nil } superseded, err := automaticSourceSuperseded(ctx, tx, r) if err != nil { @@ -142,7 +140,7 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er // that intent was cancelled, denied, held or completed. A directly submitted // operation is also a fence; never recover behind its cancellation/uncertainty. // Compare parsed times, not RFC3339 text with variable fractional precision. - // Millisecond ties conservatively fence rather than ordering by random IDs. + // For rows with no acceptance event, millisecond ties conservatively fence. // Event sequence is the durable acceptance order even if the wall clock // moves backwards. Missing acceptance evidence is not permission to retry. var accepted int64 @@ -154,6 +152,19 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er return false, err } var superseded bool - err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections WHERE project_id=? AND channel=? AND id<>? AND julianday(created_at)>=julianday(?)) OR EXISTS(SELECT 1 FROM review_operations WHERE project_id=? AND channel=? AND julianday(created_at)>=julianday(?)) OR EXISTS(SELECT 1 FROM events e JOIN review_selections s ON s.project_id=e.project_id AND s.id=e.resource_id WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.selection_requested' AND 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 o.channel=?)`, r.ProjectID, r.Channel, r.ID, r.CreatedAt, r.ProjectID, r.Channel, r.CreatedAt, r.ProjectID, accepted, r.Channel, r.ProjectID, accepted, r.Channel).Scan(&superseded) + err = tx.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM review_selections s WHERE s.project_id=? AND s.channel=? AND s.id<>? + AND julianday(s.created_at)>=julianday(?) + AND NOT EXISTS(SELECT 1 FROM events e WHERE e.project_id=s.project_id AND e.resource_id=s.id AND e.event_type='review.selection_requested' AND e.revision=1) +) OR EXISTS( + SELECT 1 FROM review_operations o WHERE o.project_id=? AND o.channel=? AND julianday(o.created_at)>=julianday(?) + AND NOT EXISTS(SELECT 1 FROM events e WHERE e.project_id=o.project_id AND e.resource_id=o.id AND e.event_type='review.requested' AND e.revision=1) +) OR EXISTS( + SELECT 1 FROM events e JOIN review_selections s ON s.project_id=e.project_id AND s.id=e.resource_id + WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.selection_requested' AND e.revision=1 AND s.channel=? +) OR EXISTS( + SELECT 1 FROM events e JOIN review_operations o ON o.project_id=e.project_id AND o.id=e.resource_id + WHERE e.project_id=? AND e.sequence>? AND e.event_type='review.requested' AND e.revision=1 AND o.channel=? +)`, r.ProjectID, r.Channel, r.ID, r.CreatedAt, r.ProjectID, r.Channel, r.CreatedAt, r.ProjectID, accepted, r.Channel, r.ProjectID, accepted, r.Channel).Scan(&superseded) return superseded, err } diff --git a/internal/reviewexec/scheduling_source_retry_test.go b/internal/reviewexec/scheduling_source_retry_test.go index c96e74f4e..6cffb7424 100644 --- a/internal/reviewexec/scheduling_source_retry_test.go +++ b/internal/reviewexec/scheduling_source_retry_test.go @@ -384,3 +384,47 @@ func TestAutomaticSourceRetryAcceptanceOrderSurvivesClockRollback(t *testing.T) t.Fatal("wall-clock rollback erased a later accepted intent") } } + +func TestAutomaticSourceRetryIgnoresEarlierAcceptanceWithFutureTimestamp(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + older := f.enqueue(t, attemptProject, "earlier-accepted-operation", "hosted", 2, 1) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + if _, err := f.e.ControlOperation(t.Context(), scope, "cancel-earlier-operation", older.ID, OperationControl{ExpectedRevision: 1, Action: "cancel"}); err != nil { + t.Fatal(err) + } + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + at := time.Now().UTC().Add(time.Hour).Format(time.RFC3339Nano) + admissionSQL(t, f, "UPDATE review_operations SET created_at=?,updated_at=? WHERE id=?", at, at, older.ID) + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + superseded, err := automaticSourceSuperseded(ctx, tx, r) + if err == nil && superseded { + t.Fatal("earlier durable acceptance cannot supersede its later intent") + } + return err + }); err != nil { + t.Fatal(err) + } +} + +func TestAutomaticInitialReadCanResumeAfterCancelledInterveningIntent(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + original := schedulingLatest(t, f) + recovery0030Claim(t, f, original.ID) + intervening := f.enqueue(t, attemptProject, "intervening-operation", "hosted", 2, 1) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + if _, err := f.e.ControlOperation(t.Context(), scope, "cancel-intervening-operation", intervening.ID, OperationControl{ExpectedRevision: 1, Action: "cancel"}); err != nil { + t.Fatal(err) + } + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + selectionNext(t, f, &refreshTestReader{}) + got := selectionRead(t, f, original.ID) + if got.State != "selected" || got.OperationID == "" || got.OperationID == intervening.ID { + t.Fatalf("proven unfinished initial read did not resume: %+v", got) + } +} diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index dbcc7dd14..6e08d470a 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -92,7 +92,7 @@ func TestSchedulingHTTPDefaultsStrictCASAndPermissions(t *testing.T) { t.Fatalf("HEAD %s must use the read path: status=%d body=%s", path, head.Code, head.Body.String()) } } - for _, body := range []string{`{}`, `{"expected_revision":0}`, `{"expected_revision":0,"automatic_hosted":null}`, `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":null}`, `{"expected_revision":0,"automatic_hosted":true,"token":"private"}`, `{"expected_revision":0,"automatic_hosted":true,"automatic_hosted":false}`} { + for _, body := range []string{`{}`, `{"expected_revision":0}`, `{"expected_revision":0,"automatic_hosted":null}`, `{"expected_revision":0,"automatic_hosted":false,"automatic_cli":null}`, `{"expected_revision":0,"automatic_hosted":false,"AUTOMATIC_CLI":null}`, `{"expected_revision":0,"automatic_hosted":true,"token":"private"}`, `{"expected_revision":0,"automatic_hosted":true,"automatic_hosted":false}`} { if w = call("POST", "scheduling", f.writer, core.NewID("key"), body); w.Code != 400 { t.Fatal(w.Code, w.Body.String()) } @@ -1563,39 +1563,47 @@ func TestSchedulingWaitSnapshotRequiresActualDraftProof(t *testing.T) { } func TestAutomaticSelectionDoesNotSettleNewlyExposedQueueSuffix(t *testing.T) { - f := schedulingFixtureWithQueue(t, []int64{2, 4, 6}) - f.enqueue(t, attemptProject, "ordinary-queued-boundary", "hosted", 4, 1) - schedulingEnable(t, f, 0, true) - schedulingGenerate(t, f, true) - before := schedulingLatest(t, f) + for _, channel := range []string{"hosted", "cli"} { + t.Run(channel, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4, 6}) + f.enqueue(t, attemptProject, "ordinary-queued-boundary", channel, 4, 1) + enable, generate := schedulingEnable, schedulingGenerate + if channel == "cli" { + enable, generate = schedulingCLIEnable, schedulingCLIGenerate + } + enable(t, f, 0, true) + generate(t, f, true) + before := schedulingLatest(t, f) - var readSix atomic.Bool - reader := &refreshTestReader{ - repository: func(_ context.Context, id int64) (reviewprovider.Repository, error) { - schedulingPause(t, f, 4, 0, true) - return reviewprovider.Repository{ID: id, FullName: "owner/repo", DefaultBranch: "main"}, nil - }, - pull: func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { - if n == 6 { - readSix.Store(true) + var readSix atomic.Bool + reader := &refreshTestReader{ + repository: func(_ context.Context, id int64) (reviewprovider.Repository, error) { + schedulingPause(t, f, 4, 0, true) + return reviewprovider.Repository{ID: id, FullName: "owner/repo", DefaultBranch: "main"}, nil + }, + pull: func(_ context.Context, _ string, n int64) (reviewprovider.Pull, error) { + if n == 6 { + readSix.Store(true) + } + return reviewprovider.Pull{Number: n, RepositoryID: 801, State: "closed", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil + }, } - return reviewprovider.Pull{Number: n, RepositoryID: 801, State: "closed", HeadSHA: strings.Repeat("a", 40), BaseSHA: strings.Repeat("b", 40), BaseRef: "main", ChangedFiles: 1}, nil - }, - } - selectionNext(t, f, reader) - after := selectionRead(t, f, before.ID) - var basis string - if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, before.ID).Scan(&basis); err != nil { - t.Fatal(err) - } - if readSix.Load() || after.State != "held" || after.Reason != "selection_changed" || basis != "" { - t.Fatalf("unacquired suffix retired: readSix=%t state=%s reason=%s basis=%s", readSix.Load(), after.State, after.Reason, basis) - } - schedulingGenerate(t, f, true) - reader.repository = nil - selectionNext(t, f, reader) - if !readSix.Load() { - t.Fatal("fresh selection did not acquire newly exposed pull") + selectionNext(t, f, reader) + after := selectionRead(t, f, before.ID) + var basis string + if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, before.ID).Scan(&basis); err != nil { + t.Fatal(err) + } + if readSix.Load() || after.State != "held" || after.Reason != "selection_changed" || basis != "" { + t.Fatalf("unacquired suffix retired: readSix=%t state=%s reason=%s basis=%s", readSix.Load(), after.State, after.Reason, basis) + } + generate(t, f, true) + reader.repository = nil + selectionNext(t, f, reader) + if !readSix.Load() { + t.Fatal("fresh selection did not acquire newly exposed pull") + } + }) } } @@ -1616,7 +1624,28 @@ func TestAutomaticCLISelectionKeepsExistingSourceLimit(t *testing.T) { t.Fatal(err) } choice, err := f.e.chooseRun(t.Context(), r, 801, c, &refreshTestReader{}) - if err != nil || choice.automaticHostedQueueLimit != nil || len(choice.prefix) != 1 || choice.prefix[0].Pull.Number != 2 { - t.Fatalf("CLI source remains limited to PR2, without a Hosted settlement pin: %+v err=%v", choice, err) + if err != nil || (choice.automaticQueueLimit == nil || *choice.automaticQueueLimit != 1) || len(choice.prefix) != 1 || choice.prefix[0].Pull.Number != 2 { + t.Fatalf("CLI source must retain a cutoff after acquiring only PR2: %+v err=%v", choice, err) + } +} + +func TestAutomaticSelectionDoesNotPublishShrinkingQueuePrefix(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4, 6}) + f.enqueue(t, attemptProject, "ordinary-later-boundary", "hosted", 6, 1) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + before := schedulingLatest(t, f) + frames := snapshotTable(t, f, "review_front_frames") + reader := &refreshTestReader{ + repository: func(_ context.Context, id int64) (reviewprovider.Repository, error) { + f.enqueue(t, attemptProject, "ordinary-new-boundary", "hosted", 2, 1) + return reviewprovider.Repository{ID: id, FullName: "owner/repo", DefaultBranch: "main"}, nil + }, + } + selectionNext(t, f, reader) + after := selectionRead(t, f, before.ID) + if after.State != "held" || after.Reason != "selection_changed" || after.OperationID != "" || + snapshotTable(t, f, "review_front_frames") != frames { + t.Fatalf("selection published against superseded cutoff: %+v", after) } } diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 8a7f74c95..ddbb0bc6d 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -674,6 +674,18 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr return e.processPendingBatch(ctx, drivers, releaseProbe, worker, operations, receipt) } +// A deterministic scheduling refusal requeues only unused preparation. Other +// candidate-local history failures keep their preparation and reservation. +func (e *Engine) classifyUnavailablePreparation(ctx context.Context, o Operation, a Attempt, err error) (bool, error) { + if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { + return true, nil + } + if schedulingRefused(err) { + return true, e.finishPreparation(a, "held", "automatic_scheduling_unavailable") + } + return automaticProjectRefused(err) || isStoredUnavailable(err, storedRoundHistory), nil +} + func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Driver, releaseProbe func(), worker int, operations []Operation, receipt pendingExhaustion) error { overloaded := false claimed := false @@ -750,6 +762,14 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if errors.As(err, &recoverable) { return err } + if ctx.Err() == nil { + if handled, settleErr := e.classifyUnavailablePreparation(ctx, o, a, err); handled { + if settleErr != nil { + return settleErr + } + continue + } + } state := "held" reason := preparationReason(err) if explicitCLI && reason == "pull_draft" { @@ -784,16 +804,9 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return e.finishPreparation(a, "cancelled", "supervisor_stopping") } - // Preserve the unused preparation and reservation on damaged retained - // history, without stopping unrelated candidates. Configuration damage - // also carries the broader project-local tag, so classify it first. - if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { - continue - } - if automaticProjectRefused(err) { - // Only proven scheduling-local corruption releases this unused preparation. - if err := e.finishPreparation(a, "held", "automatic_scheduling_unavailable"); err != nil { - return err + if handled, settleErr := e.classifyUnavailablePreparation(ctx, o, a, err); handled { + if settleErr != nil { + return settleErr } continue } diff --git a/internal/reviewexec/supervisor_classification_test.go b/internal/reviewexec/supervisor_classification_test.go new file mode 100644 index 000000000..f5b487c6b --- /dev/null +++ b/internal/reviewexec/supervisor_classification_test.go @@ -0,0 +1,40 @@ +package reviewexec + +import ( + "context" + "fmt" + "testing" +) + +func TestSupervisorTypedPreparationRefusals(t *testing.T) { + for _, tc := range []struct { + name, wantState, wantReason string + refusal func() error + reservations int + }{ + {"scheduling", "queued", "automatic_scheduling_unavailable", func() error { return schedulingRecordUnavailable(true) }, 0}, + {"round-history", "preparing", "", roundUnavailable, 1}, + {"retained-history", "preparing", "", func() error { + return automaticProjectStateFailure("storage_unavailable", "Synthetic retained history unavailable.", 503) + }, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + f := supervisorFixture(t) + receipt := f.enqueue(t, attemptProject, "typed-refusal", "cli", 2, 1) + driver := &controlledDriver{prepare: func(context.Context, Operation, Configuration, Attempt) (Preparation, error) { + return Preparation{}, fmt.Errorf("adapter context: %w", tc.refusal()) + }} + if err := f.e.processNext(context.Background(), map[string]Driver{"test-capability": driver, "other-account": driver}); err != nil { + t.Fatal(err) + } + var state, reason, attemptID string + if err := f.store.DB().QueryRow("SELECT state,reason,attempt_id FROM review_operations WHERE id=?", receipt.ID).Scan(&state, &reason, &attemptID); err != nil { + t.Fatal(err) + } + if state != tc.wantState || reason != tc.wantReason || (attemptID != "") != (tc.reservations > 0) || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || + attemptCount(t, f.store, "SELECT count(*) FROM review_execution_reservations") != tc.reservations { + t.Fatalf("state=%q reason=%q attempt=%q prepares=%d dispatches=%d", state, reason, attemptID, driver.prepares.Load(), driver.calls.Load()) + } + }) + } +} diff --git a/internal/reviewexec/types.go b/internal/reviewexec/types.go index e5dab1398..034bb75d5 100644 --- a/internal/reviewexec/types.go +++ b/internal/reviewexec/types.go @@ -115,6 +115,7 @@ type Engine struct { cliExhaustionRecovery CLIExhaustionRecoverySource automaticCursor string automaticCLICursor string + automaticCLIOtherCursor string automaticMu sync.Mutex automaticNext time.Time runSourceBudget time.Duration From 765dbee06379a9727ab79fd8b1080aa659f5ff27 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 06:28:31 +1300 Subject: [PATCH 23/41] Preserve adoption recovery and ordered review selection Detach unused preparation only for the existing typed adoption-storage outcome. Preserve the predecessor guard when a later pull has not been shown independent. --- internal/reviewexec/carried_obligations.go | 13 +++++++++- internal/reviewexec/hosted_priority.go | 5 ++-- internal/reviewexec/scheduling.go | 25 +++++++------------ internal/reviewexec/supervisor.go | 13 ++++++++-- .../supervisor_classification_test.go | 2 +- 5 files changed, 35 insertions(+), 23 deletions(-) diff --git a/internal/reviewexec/carried_obligations.go b/internal/reviewexec/carried_obligations.go index 489d518f1..15d8b3183 100644 --- a/internal/reviewexec/carried_obligations.go +++ b/internal/reviewexec/carried_obligations.go @@ -27,13 +27,24 @@ func sourceObligationCount(ctx context.Context, tx *sql.Tx, project string, pull return facts.Open, sourceObligationReadError(err) } +// 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 { var failure *core.Error if errors.As(err, &failure) && failure.Code == "repository_changed" { return sourceHold("repository_changed") } if adoptionholds.IsProjectStateError(err) { - return &automaticProjectStateError{err} + return &sourceObligationProjectStateError{&automaticProjectStateError{err}} } return err } diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 16d8d967c..295fcd420 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -82,9 +82,8 @@ 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 { - if pullSchedulingRefused(err) { - continue - } + // A refused earlier pull does not prove the later request is independent. + // Preserve this project's priority fence; callers isolate unrelated projects. return nil, err } if valid { diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index 23a1bccf3..eb7b4c7ce 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -71,12 +71,9 @@ type schedulingRecord struct { actor, credential string } -// Scheduling failures are a subset of project-local failures. A pull-local -// refusal is independent of other pulls; shared scheduling faults are not. -type schedulingStateError struct { - error - pullLocal bool -} +// 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 } @@ -84,8 +81,8 @@ func schedulingUnavailable() error { return automaticProjectStateFailure("storage_unavailable", "Stored review scheduling is unavailable.", 503) } -func schedulingRecordUnavailable(pullLocal bool) error { - return &schedulingStateError{error: schedulingUnavailable(), pullLocal: pullLocal} +func schedulingRecordUnavailable() error { + return &schedulingStateError{schedulingUnavailable()} } func schedulingRefused(err error) bool { @@ -93,10 +90,6 @@ func schedulingRefused(err error) bool { return errors.As(err, &scheduling) } -func pullSchedulingRefused(err error) bool { - var scheduling *schedulingStateError - return errors.As(err, &scheduling) && scheduling.pullLocal -} 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 @@ -118,11 +111,11 @@ func readScheduling(ctx context.Context, tx *sql.Tx, project string) (s scheduli 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(false) + 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(false) + return s, schedulingRecordUnavailable() } return s, nil } @@ -318,11 +311,11 @@ func readPullScheduling(ctx context.Context, tx *sql.Tx, project string, pull in s.ActorID, actorOK = actor.(string) s.UpdatedAt, updatedOK = updated.(string) if !revisionOK || !pausedOK || !reasonOK || !actorOK || !updatedOK || pausedValue < 0 || pausedValue > 1 { - return s, schedulingRecordUnavailable(true) + return s, schedulingRecordUnavailable() } s.Paused = pausedValue == 1 if s.Revision < 1 || !identifier.MatchString(s.ActorID) || !roundTime(s.UpdatedAt) || !validSchedulingReason(s.Reason) || !s.Paused && s.Reason != "" { - return s, schedulingRecordUnavailable(true) + return s, schedulingRecordUnavailable() } return s, nil } diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index ddbb0bc6d..f4bd7690b 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -674,8 +674,8 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr return e.processPendingBatch(ctx, drivers, releaseProbe, worker, operations, receipt) } -// A deterministic scheduling refusal requeues only unused preparation. Other -// candidate-local history failures keep their preparation and reservation. +// A typed scheduling refusal requeues only unused preparation. Other local +// history failures retain the preparation and reservation. func (e *Engine) classifyUnavailablePreparation(ctx context.Context, o Operation, a Attempt, err error) (bool, error) { if e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { return true, nil @@ -804,6 +804,15 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return e.finishPreparation(a, "cancelled", "supervisor_stopping") } + // 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 diff --git a/internal/reviewexec/supervisor_classification_test.go b/internal/reviewexec/supervisor_classification_test.go index f5b487c6b..d675d716c 100644 --- a/internal/reviewexec/supervisor_classification_test.go +++ b/internal/reviewexec/supervisor_classification_test.go @@ -12,7 +12,7 @@ func TestSupervisorTypedPreparationRefusals(t *testing.T) { refusal func() error reservations int }{ - {"scheduling", "queued", "automatic_scheduling_unavailable", func() error { return schedulingRecordUnavailable(true) }, 0}, + {"scheduling", "queued", "automatic_scheduling_unavailable", schedulingRecordUnavailable, 0}, {"round-history", "preparing", "", roundUnavailable, 1}, {"retained-history", "preparing", "", func() error { return automaticProjectStateFailure("storage_unavailable", "Synthetic retained history unavailable.", 503) From a15e40943cab0383acc064f338a08698a1ce47c0 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 08:31:03 +1300 Subject: [PATCH 24/41] Preserve current scheduling basis and reservation reporting Fence stale no-child settlement, let independent pulls proceed without touching already-denied children, and exercise concurrent retry nominations through the serialized writer. --- internal/reviewexec/next_ordinary_test.go | 61 +++++++++++++ internal/reviewexec/queued_diagnostic.go | 16 +++- internal/reviewexec/run_selection_worker.go | 39 +++++--- internal/reviewexec/scheduling_automatic.go | 89 ++++++++++++++----- .../scheduling_deauthorized_prefix_test.go | 63 +++++++++++++ .../scheduling_rearm_source_test.go | 60 +++++++++++++ .../reviewexec/scheduling_review84_test.go | 2 +- internal/reviewexec/scheduling_test.go | 4 +- 8 files changed, 294 insertions(+), 40 deletions(-) create mode 100644 internal/reviewexec/next_ordinary_test.go create mode 100644 internal/reviewexec/scheduling_deauthorized_prefix_test.go create mode 100644 internal/reviewexec/scheduling_rearm_source_test.go diff --git a/internal/reviewexec/next_ordinary_test.go b/internal/reviewexec/next_ordinary_test.go new file mode 100644 index 000000000..7526c8b62 --- /dev/null +++ b/internal/reviewexec/next_ordinary_test.go @@ -0,0 +1,61 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" +) + +func TestQueuedReservationRequiresCurrentCapability(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + t.Run(channel, func(t *testing.T) { + f := newAttemptFixture(t) + f.configure(t, attemptProject, "test-capability", 0, false) + holder := f.enqueue(t, attemptProject, "diagnostic-holder", channel, 2, 1) + f.start(t, attemptProject, holder) + waiting := f.enqueue(t, attemptProject, "diagnostic-waiter", channel, 4, 1) + op := roundOperation(t, f, waiting.ID) + scope := f.scope(t, attemptProject, f.writer, false) + cause, reservation := f.e.queuedDiagnosticDetails(t.Context(), scope, op.ID, op.Revision) + if cause != "reservation_busy" || reservation == nil || reservation.OperationID != holder.ID { + t.Fatalf("compatible reservation omitted: %q %+v", cause, reservation) + } + f.configure(t, attemptProject, "other-account", 1, false) + cause, reservation = f.e.queuedDiagnosticDetails(t.Context(), scope, op.ID, op.Revision) + if cause == "reservation_busy" || reservation != nil { + t.Fatalf("obsolete capability represented as current reservation: %q %+v", cause, reservation) + } + }) + } +} + +func TestAutomaticSourceRetryTwoNominatedPlansReachWriter(t *testing.T) { + f, original := sourceRetryFixture(t) + ageSourceRetry(t, f, original.ID) + readers := map[string]TargetReader{"test-capability": &refreshTestReader{}} + var plans [2]*automaticProjectPlan + for i := range plans { + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + plans[i], err = f.e.planAutomaticProject(ctx, tx, original.ProjectID, original.Channel, readers) + return err + }); err != nil { + t.Fatal(err) + } + if plan := plans[i]; plan == nil || plan.retry == nil || plan.retry.ID != original.ID || plan.retry.Revision != original.Revision { + t.Fatalf("snapshot %d did not independently nominate the same retained retry: %+v", i, plan) + } + } + for i, plan := range plans { + wrote, err := f.e.acceptAutomaticProject(t.Context(), original.ProjectID, original.Channel, readers, plan) + if err != nil || wrote != (i == 0) { + t.Fatalf("writer %d committed=%t, err=%v", i, wrote, err) + } + } + got := selectionRead(t, f, original.ID) + if got.State != "queued" || got.Revision != original.Revision+1 || got.OperationID != "" || + attemptCount(t, f.store, "SELECT count(*) FROM review_selections") != 1 || + attemptCount(t, f.store, "SELECT count(*) FROM review_operations") != 0 { + t.Fatalf("writer changed retry identity, revision or child state: %+v", got) + } +} diff --git a/internal/reviewexec/queued_diagnostic.go b/internal/reviewexec/queued_diagnostic.go index 3e181f6c1..57b10ac4a 100644 --- a/internal/reviewexec/queued_diagnostic.go +++ b/internal/reviewexec/queued_diagnostic.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "net/http" + "slices" "time" "github.com/benhook1013/FireController/internal/core" @@ -102,8 +103,9 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, cause = cliDraftWait return nil } + var compatible bool if op.Channel == "cli" { - compatible, err := compatibleQueuedConfiguration(ctx, tx, op, latest, latestRevision) + compatible, err = compatibleQueuedConfiguration(ctx, tx, op, latest, latestRevision) if err != nil { return err } @@ -132,8 +134,16 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, return nil } cause = "awaiting_scheduler" - capability, ok := e.capabilities[original.CapabilityID] - if !ok || capability.Fingerprint != op.CapabilityFingerprint { + if op.Channel != "cli" { + compatible, err = compatibleQueuedConfiguration(ctx, tx, op, latest, latestRevision) + if err != nil { + return err + } + } + capability, ok := e.capabilities[latest.CapabilityID] + if !compatible || !ok || e.validateConfiguration(latest) != nil || + !slices.Contains(latest.Queue, op.PullNumber) || !slices.Contains(latest.Channels, op.Channel) || + capability.Fingerprint != op.CapabilityFingerprint { cause = "" return nil } diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 163f7bc96..1e0f6a03a 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -163,12 +163,13 @@ func (r *runReads) ParentPull(ctx context.Context, repository, branch string) (r } type runChoice struct { - state, reason string - sourceReason string - prefix []SourcePlan - number int64 - head string - automaticQueueLimit *int + state, reason string + sourceReason string + prefix []SourcePlan + number int64 + head string + automaticQueueLimit *int + automaticBasisRevision int64 } // retryRunSelectionLocal retains completed source reads while only retrying @@ -219,13 +220,18 @@ func (e *Engine) chooseRun(ctx context.Context, r Run, repo int64, c Configurati func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int64, c Configuration, reader TargetReader, sourceBudget time.Duration) (result runChoice, resultErr error) { var automaticQueueLimit *int - defer func() { result.automaticQueueLimit = automaticQueueLimit }() + + var basisRevision int64 + defer func() { + result.automaticQueueLimit = automaticQueueLimit + result.automaticBasisRevision = basisRevision + }() // Bound source work before metadata lookahead. Local suppression still // rechecks the live prefix at admission if queued work changes afterward. limit, automatic := len(c.Queue), false err := retryRunSelectionRead(ctx, func() error { // An expired snapshot must not shorten a later retry's input. - limit, automatic = len(c.Queue), false + limit, automatic, basisRevision = len(c.Queue), false, 0 return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=? AND project_id=?)`, r.ID, r.ProjectID).Scan(&automatic); err != nil { return err @@ -234,14 +240,15 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 return nil } var err error - limit, err = automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + limit, err = e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) if err != nil { return err } if limit < 0 || limit > len(c.Queue) { return schedulingUnavailable() } - return nil + basisRevision, err = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) + return err }) }) if err != nil { @@ -655,7 +662,15 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat resultErr = err return } - if state != "queued" && reason != "selection_changed" { + settle := state != "queued" && reason != "selection_changed" + if settle && pull == 0 && choice.automaticBasisRevision != 0 { + var currentBasis int64 + currentBasis, resultErr = automaticChannelBasisRevision(ctx, tx, r.ProjectID, r.Channel) + // An old no-child result is still retained as history, but + // it cannot suppress the source read of a newly rearmed lane. + settle = resultErr == nil && currentBasis == choice.automaticBasisRevision + } + if settle { resultErr = e.settleAutomaticBasis(ctx, tx, r, pull) } } @@ -696,7 +711,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat // The existing binding pins the configured queue. If its // waiting boundary moved while reading source, do not settle // stale source bounds without an ordinary fresh read. - limit, err := automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + limit, err := e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) if err != nil { return err } diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index ec0055142..bd3d2d0b0 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -131,21 +131,27 @@ type automaticBasisRead struct { hasFrame bool } -// 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 +// 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 out, err + 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 } - out.revision = hosted - if channel == "cli" { - out.revision = cli - } 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 } @@ -372,12 +378,12 @@ func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project str // 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 automaticPlanningBasis(ctx context.Context, tx *sql.Tx, project string, c Configuration, ignoreSelection string) (string, bool, error) { - return automaticPlanningBasisChannel(ctx, tx, project, c, ignoreSelection, "hosted") +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 automaticPlanningBasisChannel(ctx context.Context, tx *sql.Tx, project string, c Configuration, ignoreSelection string, channel string) (string, bool, error) { - limit, err := automaticHostedQueuedPrefixChannel(ctx, tx, project, c, channel) +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 } @@ -428,21 +434,60 @@ func automaticPlanningBasisChannel(ctx context.Context, tx *sql.Tx, project stri // 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 automaticHostedQueuedPrefix(ctx context.Context, tx *sql.Tx, project string, c Configuration) (int, error) { - return automaticHostedQueuedPrefixChannel(ctx, tx, project, c, "hosted") +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 automaticHostedQueuedPrefixChannel(ctx context.Context, tx *sql.Tx, project string, c Configuration, channel string) (int, error) { +func (e *Engine) automaticHostedQueuedPrefixChannel(ctx context.Context, tx *sql.Tx, project string, c Configuration, channel string) (int, error) { queue, err := json.Marshal(c.Queue) if err != nil { return 0, err } - var limit int - err = tx.QueryRowContext(ctx, `SELECT COALESCE(MIN(q.key),?) FROM review_operations o JOIN json_each(?) q ON q.value=o.pull_number WHERE o.project_id=? AND o.channel='`+channel+`' AND o.state='queued' + rows, err := tx.QueryContext(ctx, `SELECT q.key,a.selection_id FROM review_operations o +JOIN json_each(?) q ON q.value=o.pull_number +LEFT JOIN review_selections s ON s.project_id=o.project_id AND s.operation_id=o.id +LEFT JOIN review_automatic_selections a ON a.project_id=s.project_id AND a.selection_id=s.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)`, len(c.Queue), string(queue), project).Scan(&limit) - return limit, err +AND NOT EXISTS(SELECT 1 FROM review_pull_scheduling s WHERE s.project_id=o.project_id AND s.pull_number=o.pull_number AND s.paused=1) +ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) + if err != nil { + return 0, err + } + defer rows.Close() + for count := 0; rows.Next(); count++ { + if count >= 100 { + return 0, schedulingUnavailable() + } + var position int + var selection sql.NullString + if err := rows.Scan(&position, &selection); err != nil { + return 0, err + } + // Explicit work has no automatic binding and keeps its position. + if !selection.Valid { + return position, nil + } + r, err := readRun(ctx, tx, project, selection.String) + if err != nil { + return 0, err + } + if err = e.requireAutomaticRun(ctx, tx, r); err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "automation_authorization_changed" { + // Only the cross-PR fence changes. The immutable bound + // child is still pending for duplicate suppression. + continue + } + return 0, err + } + return position, nil + } + if err = rows.Err(); err != nil { + return 0, err + } + return len(c.Queue), rows.Close() } func automaticHostedPendingPull(ctx context.Context, tx *sql.Tx, project string, pull int64) (bool, error) { @@ -471,7 +516,7 @@ func (e *Engine) automaticPullSuppressed(ctx context.Context, tx *sql.Tx, r Run, if err != nil { return false, err } - limit, err := automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + limit, err := e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) if err != nil { return false, err } @@ -498,7 +543,7 @@ func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pu if err != nil { return err } - basis, _, err := automaticPlanningBasisChannel(ctx, tx, r.ProjectID, c, r.ID, r.Channel) + basis, _, err := e.automaticPlanningBasisChannel(ctx, tx, r.ProjectID, c, r.ID, r.Channel) if err != nil { return err } @@ -656,7 +701,7 @@ func (e *Engine) planAutomaticProject(ctx context.Context, tx *sql.Tx, project, if busy { return nil, nil } - basis, candidates, err := automaticPlanningBasisChannel(ctx, tx, project, c, "", channel) + basis, candidates, err := e.automaticPlanningBasisChannel(ctx, tx, project, c, "", channel) if err != nil || !candidates { return nil, err } diff --git a/internal/reviewexec/scheduling_deauthorized_prefix_test.go b/internal/reviewexec/scheduling_deauthorized_prefix_test.go new file mode 100644 index 000000000..118138a89 --- /dev/null +++ b/internal/reviewexec/scheduling_deauthorized_prefix_test.go @@ -0,0 +1,63 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" +) + +func TestAutomaticPrefixRetainsChildButDoesNotBlockIndependentSuccessorAfterDisable(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + first := schedulingLatest(t, f) + if first.State != "selected" || first.OperationID == "" { + t.Fatal("ordinary automatic child missing", first) + } + schedulingEnable(t, f, 1, false) + schedulingEnable(t, f, 2, true) + before := snapshotTable(t, f, "review_operations") + var limit int + var oldPending bool + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + c, _, err := readConfiguration(ctx, tx, attemptProject) + if err != nil { + return err + } + limit, err = f.e.automaticHostedQueuedPrefixChannel(ctx, tx, attemptProject, c, "hosted") + if err != nil { + return err + } + oldPending, err = automaticHostedPendingPullChannel(ctx, tx, attemptProject, 2, "hosted") + return err + }); err != nil { + t.Fatal(err) + } + if limit != 2 || !oldPending { + t.Fatalf("old bound child still blocks unrelated queue: limit=%d retained same-PR pending=%v", limit, oldPending) + } + if snapshotTable(t, f, "review_operations") != before { + t.Fatal("prefix inspection changed an existing child") + } + schedulingGenerate(t, f, true) + later := schedulingLatest(t, f) + if later.ID == first.ID { + t.Fatal("independent later pull was not nominated") + } + selectionNext(t, f, &refreshTestReader{}) + later = selectionRead(t, f, later.ID) + if later.State != "selected" || later.OperationID == "" || later.OperationID == first.OperationID { + t.Fatal("later selection did not acquire its own child", later) + } + for _, pair := range []struct { + id string + pull int64 + }{{first.OperationID, 2}, {later.OperationID, 4}} { + var pull int64 + var state string + if err := f.store.DB().QueryRow("SELECT pull_number,state FROM review_operations WHERE id=?", pair.id).Scan(&pull, &state); err != nil || pull != pair.pull || state != "queued" { + t.Fatalf("child binding changed: want pull %d queued, got %d %s (%v)", pair.pull, pull, state, err) + } + } +} diff --git a/internal/reviewexec/scheduling_rearm_source_test.go b/internal/reviewexec/scheduling_rearm_source_test.go new file mode 100644 index 000000000..b2cb6fc9c --- /dev/null +++ b/internal/reviewexec/scheduling_rearm_source_test.go @@ -0,0 +1,60 @@ +package reviewexec + +import ( + "context" + "testing" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestAutomaticNoChildSourceDoesNotSettleRearmedChannel(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + old := schedulingLatest(t, f) + reader := &refreshTestReader{repository: func(_ context.Context, id int64) (reviewprovider.Repository, error) { + schedulingEnable(t, f, 1, true) + return reviewprovider.Repository{ID: id + 1, FullName: "owner/repo", DefaultBranch: "main"}, nil + }} + selectionNext(t, f, reader) + got := selectionRead(t, f, old.ID) + if got.State != "held" || got.Reason != "repository_changed" || got.OperationID != "" { + t.Fatalf("expected ordinary no-child hold: %+v", got) + } + var settled string + if err := f.store.DB().QueryRow("SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?", old.ID).Scan(&settled); err != nil { + t.Fatal(err) + } + if settled != "" { + t.Fatal("older source result consumed a fresh semantic basis") + } + schedulingGenerate(t, f, true) + fresh := schedulingLatest(t, f) + if fresh.ID == old.ID { + t.Fatal("rearm failed to acquire new source identity") + } + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, fresh.ID); got.State != "selected" || got.OperationID == "" { + t.Fatalf("fresh selection did not obtain its own source: %+v", got) + } +} + +func TestAutomaticNoChildSourceSettlesWhenChannelHasNotRearmed(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + old := schedulingLatest(t, f) + reader := &refreshTestReader{repository: func(_ context.Context, id int64) (reviewprovider.Repository, error) { + revision, enabled := int64(1), true + if _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "enable-other-channel-only", SchedulingRequest{ExpectedRevision: &revision, AutomaticHosted: &enabled, AutomaticCLI: &enabled}); err != nil { + t.Fatal(err) + } + return reviewprovider.Repository{ID: id + 1, FullName: "owner/repo", DefaultBranch: "main"}, nil + }} + selectionNext(t, f, reader) + var settled string + if err := f.store.DB().QueryRow("SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?", old.ID).Scan(&settled); err != nil || len(settled) != 64 { + t.Fatalf("other-channel change discarded valid settlement: %q %v", settled, err) + } + schedulingGenerate(t, f, false) +} diff --git a/internal/reviewexec/scheduling_review84_test.go b/internal/reviewexec/scheduling_review84_test.go index 919cad796..9939815a4 100644 --- a/internal/reviewexec/scheduling_review84_test.go +++ b/internal/reviewexec/scheduling_review84_test.go @@ -15,7 +15,7 @@ func TestReview84DraftWaitDoesNotFenceIndependentCLI(t *testing.T) { if err != nil { return err } - limit, err := automaticHostedQueuedPrefixChannel(ctx, tx, attemptProject, c, "cli") + limit, err := f.e.automaticHostedQueuedPrefixChannel(ctx, tx, attemptProject, c, "cli") if err == nil && limit != 2 { t.Fatalf("draft fenced independent successor: %d", limit) } diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index 6e08d470a..5f0a1ee60 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -384,7 +384,7 @@ func TestSchedulingProjectionRefreshDoesNotRegenerateAndValidatorPreservesRevoca if err != nil { return err } - before, _, err := automaticPlanningBasis(ctx, tx, attemptProject, c, "") + before, _, err := f.e.automaticPlanningBasis(ctx, tx, attemptProject, c, "") if err != nil { return err } @@ -406,7 +406,7 @@ func TestSchedulingProjectionRefreshDoesNotRegenerateAndValidatorPreservesRevoca if _, err = tx.ExecContext(ctx, `UPDATE review_front_frames SET checked_at=?,source_observed_at=?,prefix_json=? WHERE project_id=?`, at, at, string(body), attemptProject); err != nil { return err } - after, _, err := automaticPlanningBasis(ctx, tx, attemptProject, c, "") + after, _, err := f.e.automaticPlanningBasis(ctx, tx, attemptProject, c, "") if err != nil { return err } From 771b4c3815ec1d1a11a08e169d2e9c621c5f9a59 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 09:06:06 +1300 Subject: [PATCH 25/41] Keep queued diagnostics when reservations become incompatible Preserve the generic scheduler status without attributing a stale reservation. Keep nonlocal errors visible and scope retained local read refusals to their existing boundary. --- internal/reviewexec/carried_obligations.go | 12 +- .../local_refusal_boundaries_test.go | 108 ++++++++++++++++++ internal/reviewexec/next_ordinary_test.go | 4 +- internal/reviewexec/queued_diagnostic.go | 9 +- .../reviewexec/scheduling_cli_priority.go | 46 +++++--- internal/reviewexec/supervisor.go | 8 +- 6 files changed, 165 insertions(+), 22 deletions(-) create mode 100644 internal/reviewexec/local_refusal_boundaries_test.go diff --git a/internal/reviewexec/carried_obligations.go b/internal/reviewexec/carried_obligations.go index 15d8b3183..d185e6869 100644 --- a/internal/reviewexec/carried_obligations.go +++ b/internal/reviewexec/carried_obligations.go @@ -22,9 +22,17 @@ 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 diff --git a/internal/reviewexec/local_refusal_boundaries_test.go b/internal/reviewexec/local_refusal_boundaries_test.go new file mode 100644 index 000000000..2f3518882 --- /dev/null +++ b/internal/reviewexec/local_refusal_boundaries_test.go @@ -0,0 +1,108 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "reflect" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func TestDraftRereadRefusalOnlySkipsItsOwnCandidate(t *testing.T) { + for _, tt := range []struct { + name string + refusal error + wantChecks int + }{ + {"retained-decode", &retainedOperationDecodeError{errors.New("synthetic typed decoder refusal")}, 2}, + {"shared-storage", errors.New("synthetic unclassified SQL failure"), 1}, + } { + t.Run(tt.name, func(t *testing.T) { + e := &Engine{} + checks, releases := 0, 0 + batch := []Operation{{ProjectID: "project-first", ID: "op-first", Channel: "cli"}, {ProjectID: "project-next", ID: "op-next", Channel: "cli"}} + check := func(_ context.Context, got Operation, _ map[string]Driver) (bool, bool, bool, error) { + if got.ID != batch[checks].ID || got.ProjectID != batch[checks].ProjectID { + t.Fatalf("candidate %d changed identity: %+v", checks, got) + } + checks++ + if checks == 1 { + return false, false, false, tt.refusal + } + // Prove the next project's draft check runs; it remains waiting. + return false, false, false, nil + } + err := e.processPendingBatchWithDraftCheck(t.Context(), nil, func() { releases++ }, 0, batch, pendingExhaustion{}, check) + if tt.wantChecks == 1 { + attemptCode(t, err, "review_persistence_failed") + } else if err != nil { + t.Fatal(err) + } + if checks != tt.wantChecks || releases != checks { + t.Fatalf("checks=%d releases=%d want=%d", checks, releases, tt.wantChecks) + } + }) + } +} + +func TestAutomaticAdoptionCountRetainsLocalRepositoryRefusal(t *testing.T) { + f := selectionFixture(t) + retainObligationSource(t, f, attemptProject, "local-refusal-importer", "local-refusal-source", strings.Repeat("c", 64), 0) + if err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if count, err := sourceObligationCount(ctx, tx, attemptProject, 2); count != 1 || err != nil { + t.Fatalf("valid retained source count=%d err=%v", count, err) + } + repositoryChanged := core.Fail("repository_changed", "Synthetic retained source bound to a different repository.", 409) + for _, tt := range []struct { + failure error + local bool + }{ + {repositoryChanged, true}, + {errors.New("synthetic shared SQL failure"), false}, + {context.Canceled, false}, + {context.DeadlineExceeded, false}, + } { + count, err := sourceObligationCount(ctx, admissionObligationFailure{Tx: tx, failure: tt.failure}, attemptProject, 2) + if count != 0 || err == nil || automaticProjectRefused(err) != tt.local || isSourceObligationProjectStateError(err) { + t.Errorf("automatic read count=%d local=%t ordinary-admission marker=%t err=%v", count, automaticProjectRefused(err), isSourceObligationProjectStateError(err), err) + } + if tt.local { + attemptCode(t, err, "review_held") + attemptCode(t, sourceObligationReadError(tt.failure), "review_held") + if preparationReason(err) != "repository_changed" || automaticProjectRefused(sourceObligationReadError(tt.failure)) { + t.Errorf("public reason/ordinary admission changed: %v", err) + } + } else if !errors.Is(err, tt.failure) { + t.Errorf("shared error lost: got %v want %v", err, tt.failure) + } + } + return nil + }); err != nil { + t.Fatal(err) + } +} + +func TestPreferredSelectionKeysRequireNativeText(t *testing.T) { + f := selectionFixture(t) + // Synthetic row expression only. No malformed state is written to a store. + rows, err := f.store.DB().QueryContext(t.Context(), `SELECT 'first', CAST('one' AS BLOB) UNION ALL SELECT 'next', 'one' UNION ALL SELECT 'last', 'two'`) + if err != nil { + t.Fatal(err) + } + got, err := readPreferredSelectionIDs(rows) + want := []pendingCandidateID{{project: "next", operation: "one"}, {project: "last", operation: "two"}} + if err != nil || !reflect.DeepEqual(got, want) { + t.Errorf("preferred keys %+v, err=%v; want %+v", got, err, want) + } + + rows, err = f.store.DB().QueryContext(t.Context(), `SELECT 'first', 'one' UNION ALL SELECT 'next', abs(-9223372036854775808)`) + if err != nil { + t.Fatal(err) + } + if got, err := readPreferredSelectionIDs(rows); got != nil || err == nil { + t.Fatalf("real SQLite iteration failure became success: keys=%+v err=%v", got, err) + } +} diff --git a/internal/reviewexec/next_ordinary_test.go b/internal/reviewexec/next_ordinary_test.go index 7526c8b62..e46d5c7f9 100644 --- a/internal/reviewexec/next_ordinary_test.go +++ b/internal/reviewexec/next_ordinary_test.go @@ -22,8 +22,8 @@ func TestQueuedReservationRequiresCurrentCapability(t *testing.T) { } f.configure(t, attemptProject, "other-account", 1, false) cause, reservation = f.e.queuedDiagnosticDetails(t.Context(), scope, op.ID, op.Revision) - if cause == "reservation_busy" || reservation != nil { - t.Fatalf("obsolete capability represented as current reservation: %q %+v", cause, reservation) + if cause != "awaiting_scheduler" || reservation != nil { + t.Fatalf("obsolete capability must leave a generic diagnostic with no reservation: %q %+v", cause, reservation) } }) } diff --git a/internal/reviewexec/queued_diagnostic.go b/internal/reviewexec/queued_diagnostic.go index 57b10ac4a..96f493969 100644 --- a/internal/reviewexec/queued_diagnostic.go +++ b/internal/reviewexec/queued_diagnostic.go @@ -133,7 +133,15 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, cause = "cooldown" return nil } + // Keep the generic diagnostic for an otherwise valid retained receipt. + // The current configuration gates reservation attribution, not receipt + // visibility. Original capability drift still omits the diagnostic. cause = "awaiting_scheduler" + originalCapability, ok := e.capabilities[original.CapabilityID] + if !ok || originalCapability.Fingerprint != op.CapabilityFingerprint { + cause = "" + return nil + } if op.Channel != "cli" { compatible, err = compatibleQueuedConfiguration(ctx, tx, op, latest, latestRevision) if err != nil { @@ -144,7 +152,6 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, if !compatible || !ok || e.validateConfiguration(latest) != nil || !slices.Contains(latest.Queue, op.PullNumber) || !slices.Contains(latest.Channels, op.Channel) || capability.Fingerprint != op.CapabilityFingerprint { - cause = "" return nil } reservation, err = queuedReservationHolder(ctx, tx, op, capability, repositoryID) diff --git a/internal/reviewexec/scheduling_cli_priority.go b/internal/reviewexec/scheduling_cli_priority.go index db76bb62a..a4df61fde 100644 --- a/internal/reviewexec/scheduling_cli_priority.go +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -107,24 +107,10 @@ func (e *Engine) preferredCLISelection(ctx context.Context, tx *sql.Tx, o Operat if err != nil { return false, err } - var ids []pendingCandidateID - for rows.Next() { - var id pendingCandidateID - if err = rows.Scan(&id.project, &id.operation); err != nil { - break - } - ids = append(ids, id) - } - if err == nil { - err = rows.Err() - } - closeErr := rows.Close() + ids, err := readPreferredSelectionIDs(rows) if err != nil { return false, err } - if closeErr != nil { - return false, closeErr - } candidates: for _, id := range ids { r, err := readRun(ctx, tx, id.project, id.operation) @@ -170,3 +156,33 @@ candidates: } return false, nil } + +// Read candidate keys before other lookups; database/sql can otherwise coerce +// a non-text value to a different key. +func readPreferredSelectionIDs(rows *sql.Rows) ([]pendingCandidateID, error) { + var err error + var ids []pendingCandidateID + for rows.Next() { + var id pendingCandidateID + var rawID any + if err = rows.Scan(&id.project, &rawID); err != nil { + break + } + var text bool + if id.operation, text = rawID.(string); !text { + continue + } + ids = append(ids, id) + } + if err == nil { + err = rows.Err() + } + closeErr := rows.Close() + if err != nil { + return nil, err + } + if closeErr != nil { + return nil, closeErr + } + return ids, nil +} diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index f4bd7690b..d4cf81d85 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -687,13 +687,17 @@ func (e *Engine) classifyUnavailablePreparation(ctx context.Context, o Operation } func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Driver, releaseProbe func(), worker int, operations []Operation, receipt pendingExhaustion) error { + return e.processPendingBatchWithDraftCheck(ctx, drivers, releaseProbe, worker, operations, receipt, e.checkCLIDraft) +} + +func (e *Engine) processPendingBatchWithDraftCheck(ctx context.Context, drivers map[string]Driver, releaseProbe func(), worker int, operations []Operation, receipt pendingExhaustion, checkDraft func(context.Context, Operation, map[string]Driver) (bool, bool, bool, error)) error { overloaded := false claimed := false for _, o := range operations { if ctx.Err() != nil { return nil } - proceed, draftReady, explicitCLI, err := e.checkCLIDraft(ctx, o, drivers) + proceed, draftReady, explicitCLI, err := checkDraft(ctx, o, drivers) // Selection includes at most one Draft intent, ahead of ordinary work. // Its bounded source read is over; never retain the permit during a // potentially long preparation or dispatch. @@ -702,7 +706,7 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri if ctx.Err() != nil { return nil } - if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) { + if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { continue } var refusal *core.Error From 0039ce5d840e79db23f702169531a23290ae67d8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 10:31:52 +1300 Subject: [PATCH 26/41] Validate native revision type for orphan resume snapshots --- internal/reviewexec/scheduling_snapshot.go | 31 +++++++++++++------ ...cheduling_snapshot_event_integrity_test.go | 27 ++++++++++++++++ 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index ec294560e..d230fa4cb 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -184,6 +184,8 @@ func scanSchedulingSnapshot(row interface{ Scan(...any) error }, destinations .. // 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. func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { rows, err := tx.QueryContext(ctx, `WITH orphan AS ( SELECT e.project_id,e.resource_id,e.revision, @@ -195,23 +197,15 @@ func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { AND CAST(s.pull_number AS TEXT)=e.resource_id WHERE e.event_type='review.pull_scheduling_updated' AND s.pull_number IS NULL ) - SELECT resource_id,revision,payload,matches FROM orphan WHERE newest=1`) + SELECT resource_id,CASE WHEN typeof(revision)='integer' THEN revision END,payload,matches FROM orphan WHERE newest=1`) if err != nil { return err } defer rows.Close() for rows.Next() { - var resource string - var revision, matches int64 - var payload sql.NullString - if err := rows.Scan(&resource, &revision, &payload, &matches); err != nil { + if err := validateOrphanPullSchedulingEvent(rows); err != nil { return err } - pull, err := strconv.ParseInt(resource, 10, 32) - if err != nil || pull < 1 || strconv.FormatInt(pull, 10) != resource || revision < 1 || matches != 1 || - !validPullSchedulingPayload(payload, pull, false) { - return schedulingUnavailable() - } } if err := rows.Err(); err != nil { return err @@ -219,6 +213,23 @@ func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { return rows.Close() } +func validateOrphanPullSchedulingEvent(row interface{ Scan(...any) error }) error { + var resource string + var revision any + var matches int64 + var payload sql.NullString + if err := row.Scan(&resource, &revision, &payload, &matches); err != nil { + return err + } + 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) { + return schedulingUnavailable() + } + return nil +} + func validPullSchedulingPayload(payload sql.NullString, pull int64, paused bool) bool { var event struct { PullNumber int64 `json:"pull_number"` diff --git a/internal/reviewexec/scheduling_snapshot_event_integrity_test.go b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go index 7e89bfb2a..78994887c 100644 --- a/internal/reviewexec/scheduling_snapshot_event_integrity_test.go +++ b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go @@ -101,3 +101,30 @@ func TestSchedulingSnapshotPullEventStreamKeepsProjectIdentity(t *testing.T) { 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 '2', ?, '{"pull_number":2,"paused":false}', 1`, tc.revision) + err := validateOrphanPullSchedulingEvent(row) + if tc.valid { + if err != nil { + t.Fatal(err) + } + } else { + attemptCode(t, err, "storage_unavailable") + } + }) + } +} From 9127fe034cdefb32bff1ac9250f6fb921186d65b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 13:54:12 +1300 Subject: [PATCH 27/41] Preserve historical pull resume revisions on offline restore --- docs/review-scheduling.md | 2 +- internal/backup/restore.go | 11 +++ internal/backup/scheduling_test.go | 56 +++++++++++++++ internal/reviewexec/scheduling_snapshot.go | 80 ++++++++++++++++++++-- 4 files changed, 143 insertions(+), 6 deletions(-) diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index f81d2b17b..b09c2515a 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -64,7 +64,7 @@ MCP equivalents are `review_scheduling_read`, `review_scheduling_configure`, `re `GET`/`POST /api/v1/projects/{project_id}/reviews/scheduling` read/configure project scheduling. The write body is `{expected_revision, automatic_hosted, automatic_cli?}` and requires project management. `GET`/`POST /api/v1/projects/{project_id}/reviews/pulls/{number}/scheduling` read/update a PR pause. The write body is `{expected_revision, paused, reason?}` and requires project write access. Writes require the normal explicit idempotency key. Unconfigured records read as revision zero and off/unpaused; writes return a new revision. Project reads report unavailable authorization or provider holds without exposing credential identifiers or tokens. -Backups retain scheduling, PR pauses and automatic-intent attribution. Older bundles without this optional domain remain off; version-one Hosted-only records migrate with automatic CLI off. Restore remains inactive with provider execution held. Historical authorizers remain valid historical evidence after revocation or retirement. +Backups retain scheduling, PR pauses and automatic-intent attribution. Older bundles without this optional domain remain off; version-one Hosted-only records migrate with automatic CLI off. Restore remains inactive with provider execution held. Historical authorizers remain valid historical evidence after revocation or retirement. A legacy bundle may omit the PR control if its unique latest canonical event records an unpaused resume. Offline restore preserves that event’s actor, timestamp and revision in the inactive destination control, without changing the source bundle, event journal or authorization. A missing paused control or unresolved history remains invalid; a PR with no retained control history still reads at revision zero. ## Validation diff --git a/internal/backup/restore.go b/internal/backup/restore.go index ce5d2af9d..cd8549ef2 100644 --- a/internal/backup/restore.go +++ b/internal/backup/restore.go @@ -14,6 +14,7 @@ import ( "strings" "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewexec" ) const restoreMarker = ".restore-in-progress" @@ -243,6 +244,16 @@ func restoreIdentity(ctx context.Context, dir string, m Manifest, id, key string if _, err = tx.ExecContext(ctx, `UPDATE credentials SET revoked=1`); err != nil { return unavailable() } + if err = reviewexec.RestoreHistoricalPullResumes(ctx, tx); err != nil { + if interrupted := checkContext(ctx); interrupted != nil { + return interrupted + } + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "storage_unavailable" { + return invalid() + } + return unavailable() + } if err = tx.Commit(); err != nil { return unavailable() } diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index 008e62f70..cf976a2c2 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -134,6 +134,62 @@ func TestSchedulingBackupRetainsNativeControlsAndInactiveRestore(t *testing.T) { backupCode(t, err, "forbidden") } +func TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { + f := newRestoreFixture(t) + e := selectionInventoryEngine(t, f.store) + scope := routePolicyInventoryScope(t, f) + zero, one := int64(0), int64(1) + paused, resumed := true, false + for _, pull := range []int64{2, 4} { + if _, err := e.ConfigurePullScheduling(t.Context(), scope, "initial-pull-pause", pull, + reviewexec.PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused, Reason: "Fixture pause"}); err != nil { + t.Fatal(err) + } + } + if _, err := e.ConfigurePullScheduling(t.Context(), scope, "historical-pull-resume", 4, + reviewexec.PullSchedulingRequest{ExpectedRevision: &one, Paused: &resumed}); err != nil { + t.Fatal(err) + } + event := restoreRows(t, f.store.DB(), `SELECT project_id,4,revision,0,'',actor_id,created_at + FROM events WHERE event_type='review.pull_scheduling_updated' AND resource_id='4' AND revision=2`) + if len(event) != 1 || len(event[0]) != 7 { + t.Fatalf("expected one historical resume event, got %v", event) + } + if _, err := f.store.DB().Exec(`DELETE FROM review_pull_scheduling WHERE project_id=? AND pull_number=4`, f.project); err != nil { + t.Fatal(err) + } + const controls = `SELECT project_id,pull_number,revision,paused,reason,actor_id,updated_at FROM review_pull_scheduling ORDER BY pull_number` + const journal = `SELECT * FROM events ORDER BY sequence` + sourceControls, sourceJournal := restoreRows(t, f.store.DB(), controls), restoreRows(t, f.store.DB(), journal) + if len(sourceControls) != 1 { + t.Fatalf("expected one untouched control, got %v", sourceControls) + } + bundle := restoreBundle(t, f) + immutable := restoreTree(t, bundle.Path) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal("valid legacy bundle no longer inspectable", err) + } + destination := filepath.Join(t.TempDir(), "inactive-resume") + if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { + t.Fatal("valid legacy bundle no longer restorable", err) + } + dst, err := openSnapshot(t.Context(), filepath.Join(destination, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer dst.Close() + want := [][]any{sourceControls[0], event[0]} + if got := restoreRows(t, dst, controls); !reflect.DeepEqual(want, got) { + t.Fatalf("restored controls lost canonical revision or attribution: got %v, want %v", got, want) + } + if !reflect.DeepEqual(sourceJournal, restoreRows(t, dst, journal)) { + t.Fatal("offline restore appended or rewrote historical events") + } + if !reflect.DeepEqual(sourceControls, restoreRows(t, f.store.DB(), controls)) || !reflect.DeepEqual(immutable, restoreTree(t, bundle.Path)) { + t.Fatal("restore mutated source controls or validated bundle") + } +} + func TestSchedulingBackupHistoricalAuthorizersRemainHistory(t *testing.T) { f, _, credential := schedulingBackupFixture(t) for _, kind := range []string{"revoked", "demoted", "retired"} { diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index d230fa4cb..361d9bba3 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -3,11 +3,12 @@ package reviewexec import ( "context" "database/sql" - "github.com/benhook1013/FireController/internal/strictjson" + "errors" "strconv" "strings" "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/strictjson" ) // ValidateSchedulingSnapshot checks retained control/attribution, not current @@ -186,9 +187,8 @@ func scanSchedulingSnapshot(row interface{ Scan(...any) error }, destinations .. // retained event instead proves a pause or cannot be read as that identity. // Rank every event before projecting its native revision; never fall back to // an older valid resume when the winning revision cannot be trusted. -func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { - rows, err := tx.QueryContext(ctx, `WITH orphan AS ( - SELECT e.project_id,e.resource_id,e.revision, +const orphanPullSchedulingSQL = `WITH orphan AS ( + SELECT e.project_id,e.resource_id,e.revision,e.sequence, CASE WHEN typeof(e.payload_json)='text' AND length(CAST(e.payload_json AS BLOB))<=4096 THEN e.payload_json END AS payload, ROW_NUMBER() OVER (PARTITION BY e.project_id,e.resource_id ORDER BY e.revision DESC,e.sequence DESC) AS newest, COUNT(*) OVER (PARTITION BY e.project_id,e.resource_id,e.revision) AS matches @@ -196,7 +196,10 @@ func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { ON s.project_id=e.project_id AND s.pull_number=CAST(e.resource_id AS INTEGER) AND CAST(s.pull_number AS TEXT)=e.resource_id WHERE e.event_type='review.pull_scheduling_updated' AND s.pull_number IS NULL - ) + )` + +func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+` SELECT resource_id,CASE WHEN typeof(revision)='integer' THEN revision END,payload,matches FROM orphan WHERE newest=1`) if err != nil { return err @@ -221,6 +224,10 @@ func validateOrphanPullSchedulingEvent(row interface{ Scan(...any) error }) erro if err := row.Scan(&resource, &revision, &payload, &matches); err != nil { return err } + return validateOrphanPullResume(resource, revision, payload, matches) +} + +func validateOrphanPullResume(resource string, revision any, payload sql.NullString, matches int64) error { 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 || @@ -230,6 +237,69 @@ func validateOrphanPullSchedulingEvent(row interface{ Scan(...any) error }) erro return nil } +// RestoreHistoricalPullResumes preserves the CAS revision of valid legacy +// resume events on an offline restored copy. The caller owns its restore +// transaction. No event, credential, or project scheduling authority changes. +func RestoreHistoricalPullResumes(ctx context.Context, tx *sql.Tx) error { + var state string + if err := tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='restore:state'`).Scan(&state); err != nil { + return err + } + if state != "inactive" { + return schedulingUnavailable() + } + var version string + err := tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_scheduling'`).Scan(&version) + if errors.Is(err, sql.ErrNoRows) { + // Older backups may omit the scheduling domain altogether. + return nil + } + if err != nil { + return err + } + if version != "1" && version != "2" { + return schedulingUnavailable() + } + const candidates = ` + FROM orphan o JOIN events e ON e.sequence=o.sequence + WHERE o.newest=1` + rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+` + SELECT o.project_id,o.resource_id,CASE WHEN typeof(o.revision)='integer' THEN o.revision END,o.payload,o.matches, + CASE WHEN typeof(e.actor_id)='text' THEN e.actor_id END, + CASE WHEN typeof(e.created_at)='text' THEN e.created_at END`+candidates) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var project, resource string + var revision any + var resumePayload, actor, createdAt sql.NullString + var matches int64 + if err := rows.Scan(&project, &resource, &revision, &resumePayload, &matches, &actor, &createdAt); err != nil { + return err + } + if err := validateOrphanPullResume(resource, revision, resumePayload, matches); err != nil { + return err + } + if !identifier.MatchString(project) || !actor.Valid || !identifier.MatchString(actor.String) || !createdAt.Valid || !roundTime(createdAt.String) { + return schedulingUnavailable() + } + } + if err := rows.Err(); err != nil { + return err + } + if err := rows.Close(); err != nil { + return err + } + // Both reads are in the same transaction, and no projection was inserted + // until the complete set was validated. Keep the source event sequence. + _, err = tx.ExecContext(ctx, orphanPullSchedulingSQL+` + INSERT INTO review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at) + SELECT o.project_id,CAST(o.resource_id AS INTEGER),o.revision,0,'',e.actor_id,e.created_at`+candidates) + return err +} + func validPullSchedulingPayload(payload sql.NullString, pull int64, paused bool) bool { var event struct { PullNumber int64 `json:"pull_number"` From c088aa04d9d7491875d93f9aae2d3a5d2f28bdd2 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 16:31:19 +1300 Subject: [PATCH 28/41] Require exact scheduling events and prove independent queue claims --- internal/reviewexec/attempts.go | 6 +- internal/reviewexec/hosted_priority.go | 32 ++- .../reviewexec/independent_claim_witness.go | 138 ++++++++++++ .../independent_claim_witness_test.go | 211 ++++++++++++++++++ internal/reviewexec/scheduling.go | 16 +- ...cheduling_authorization_continuity_test.go | 36 +++ internal/reviewexec/scheduling_automatic.go | 7 + internal/reviewexec/supervisor.go | 24 +- internal/reviewexec/types.go | 5 + internal/reviewruntime/cli_driver.go | 7 + internal/reviewruntime/hosted_driver.go | 7 + 11 files changed, 482 insertions(+), 7 deletions(-) create mode 100644 internal/reviewexec/independent_claim_witness.go create mode 100644 internal/reviewexec/independent_claim_witness_test.go diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 322aae26e..02ae74098 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -77,6 +77,10 @@ func (e *Engine) StartAttempt(ctx context.Context, project, id string) (Attempt, } func (e *Engine) startAttempt(ctx context.Context, project, id string, draftReadyRevision int64, expectedRevision int64) (Attempt, error) { + return e.startAttemptWithWitness(ctx, project, id, draftReadyRevision, expectedRevision, nil) +} + +func (e *Engine) startAttemptWithWitness(ctx context.Context, project, id string, draftReadyRevision int64, expectedRevision int64, witness *independentClaimWitness) (Attempt, error) { var result Attempt err := e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { o, err := readOperation(ctx, tx, project, id) @@ -170,7 +174,7 @@ func (e *Engine) startAttempt(ctx context.Context, project, id string, draftRead return nil } var repositoryID int64 - if earlier, err := e.earlierQueuedReviewIntent(ctx, tx, o, c, revision); err != nil { + if earlier, err := e.earlierQueuedReviewIntentWithWitness(ctx, tx, o, c, revision, nil, witness); err != nil { return err } else if earlier != nil { return nil diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 295fcd420..39f3b6cbe 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -27,6 +27,20 @@ type queuePriorityKey struct { // An empty predecessor set can be reused only inside one read transaction. // Binding-dependent decisions still run separately for every candidate. func (e *Engine) earlierQueuedReviewIntentInSnapshot(ctx context.Context, tx *sql.Tx, o Operation, c Configuration, revision int64, empty map[queuePriorityKey]bool) (*Operation, error) { + return e.earlierQueuedReviewIntentWithWitness(ctx, tx, o, c, revision, empty, nil) +} + +type queuePriorityPreflight struct { + cause error + predecessor Operation + configuration Configuration + revision, repositoryID int64 +} + +func (p *queuePriorityPreflight) Error() string { return p.cause.Error() } +func (p *queuePriorityPreflight) Unwrap() error { return p.cause } + +func (e *Engine) earlierQueuedReviewIntentWithWitness(ctx context.Context, tx *sql.Tx, o Operation, c Configuration, revision int64, empty map[queuePriorityKey]bool, witness *independentClaimWitness) (*Operation, error) { position := slices.Index(c.Queue, o.PullNumber) if !validChannel(o.Channel) || o.State != "queued" || position < 1 || c.Paused || revision < o.ConfigurationRevision { return nil, nil @@ -82,9 +96,21 @@ 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 refused earlier pull does not prove the later request is independent. - // Preserve this project's priority fence; callers isolate unrelated projects. - return nil, err + var local *pullSchedulingStateError + if !errors.As(err, &local) || local.project != earlier.ProjectID || local.pull != earlier.PullNumber || + !independentClaimPair(c, revision, earlier, o) { + return nil, err + } + var repoID int64 + if readErr := tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, o.ProjectID).Scan(&repoID); readErr != nil { + return nil, readErr + } + if witness != nil && witness.matches(e.sampleExecutionTime(), repoID, c, revision, earlier, o) { + continue + } + // This still fences all non-supervisor callers. The supervisor + // may perform a separate bounded, trusted observation outside SQL. + return nil, &queuePriorityPreflight{err, earlier, c, revision, repoID} } if valid { return &earlier, nil diff --git a/internal/reviewexec/independent_claim_witness.go b/internal/reviewexec/independent_claim_witness.go new file mode 100644 index 000000000..2b9468ad5 --- /dev/null +++ b/internal/reviewexec/independent_claim_witness.go @@ -0,0 +1,138 @@ +package reviewexec + +import ( + "context" + "slices" + "time" +) + +// independentClaimWitness is one short-lived, internal observation. It is not +// a client input, persisted source cache, or permission to reserve a slot. +// The supervisor constructs it only for an exact typed per-pull refusal, +// and the serialized claim rechecks those identities before any exemption. +type independentClaimWitness struct { + predecessor Operation + successor Operation + configRevision int64 + repositoryID int64 + defaultRef string + baseSHA string + observed time.Time +} + +const independentClaimFreshness = 15 * time.Second + +func observeIndependentClaim(ctx context.Context, reader TargetReader, repositoryID int64, c Configuration, currentRevision int64, predecessor, successor Operation) (independentClaimWitness, error) { + if !independentClaimPair(c, currentRevision, predecessor, successor) { + return independentClaimWitness{}, nil + } + plan, err := ResolveSource(ctx, reader, repositoryID, c, Request{PullNumber: successor.PullNumber, HeadSHA: successor.HeadSHA, Channel: successor.Channel}) + if err != nil { + return independentClaimWitness{}, err + } + if plan.SourceReason != "" || plan.ParentPullNumber != 0 || plan.ParentSHA != plan.Pull.BaseSHA || + plan.Repository.DefaultBranch == "" || plan.Pull.BaseRef != plan.Repository.DefaultBranch || + plan.Pull.IsDraft == nil || *plan.Pull.IsDraft { + return independentClaimWitness{}, nil + } + at, err := time.Parse(time.RFC3339Nano, plan.ObservedAt) + if err != nil || at.IsZero() { + return independentClaimWitness{}, nil + } + return independentClaimWitness{predecessor: predecessor, successor: successor, configRevision: currentRevision, + repositoryID: repositoryID, defaultRef: plan.Repository.DefaultBranch, baseSHA: plan.Pull.BaseSHA, observed: at}, nil +} + +func independentClaimPair(c Configuration, currentRevision int64, predecessor, successor Operation) bool { + i, j := slices.Index(c.Queue, predecessor.PullNumber), slices.Index(c.Queue, successor.PullNumber) + return c.Mode == "independent" && !c.Paused && c.ExpectedRevision != nil && + currentRevision > 0 && *c.ExpectedRevision == currentRevision-1 && predecessor.ConfigurationRevision == currentRevision && successor.ConfigurationRevision == currentRevision && + predecessor.State == "queued" && successor.State == "queued" && + predecessor.ProjectID == successor.ProjectID && identifier.MatchString(successor.ProjectID) && + predecessor.Channel == successor.Channel && validChannel(successor.Channel) && slices.Contains(c.Channels, successor.Channel) && + predecessor.CapabilityFingerprint == successor.CapabilityFingerprint && predecessor.PolicyRevision == successor.PolicyRevision && + identifier.MatchString(predecessor.ID) && identifier.MatchString(successor.ID) && predecessor.ID != successor.ID && predecessor.Revision > 0 && successor.Revision > 0 && + i >= 0 && j > i && sha.MatchString(predecessor.HeadSHA) && sha.MatchString(successor.HeadSHA) +} + +// matches pins observations to the current operation and project revision in +// the eventual claim. The caller owns normal authorization and order checks +// and must have freshly re-observed this exact predecessor's typed refusal. +func (w independentClaimWitness) matches(now time.Time, repoID int64, c Configuration, rev int64, predecessor, successor Operation) bool { + return !w.observed.IsZero() && !now.Before(w.observed) && now.Sub(w.observed) <= independentClaimFreshness && + repoID > 0 && repoID == w.repositoryID && w.defaultRef != "" && sha.MatchString(w.baseSHA) && + w.configRevision == rev && independentClaimPair(c, rev, predecessor, successor) && + sameIndependentClaimOperation(predecessor, w.predecessor) && sameIndependentClaimOperation(successor, w.successor) +} + +func sameIndependentClaimOperation(a, b Operation) bool { + return a.ID == b.ID && a.Revision == b.Revision && a.ProjectID == b.ProjectID && + a.ConfigurationRevision == b.ConfigurationRevision && a.PolicyRevision == b.PolicyRevision && + a.ActorID == b.ActorID && a.WorkerID == b.WorkerID && a.Channel == b.Channel && + a.PullNumber == b.PullNumber && a.HeadSHA == b.HeadSHA && a.CapabilityFingerprint == b.CapabilityFingerprint +} + +// IndependentQueueSource is implemented only by trusted in-process drivers. +// It exposes an observation reader, not a preparation or provider trigger. +type IndependentQueueSource interface { + IndependentQueueTargetReader() TargetReader +} + +const ( + independentProbeInterval = 5 * time.Second + independentProbeTimeout = 10 * time.Second +) + +func (e *Engine) probeIndependentClaim(ctx context.Context, drivers map[string]Driver, p *queuePriorityPreflight, successor Operation) *independentClaimWitness { + driver, ok := drivers[p.configuration.CapabilityID].(IndependentQueueSource) + if !ok { + return nil + } + reader := driver.IndependentQueueTargetReader() + if reader == nil { + return nil + } + // One optional source probe process-wide. Provider I/O is outside all + // transactions; the interval also bounds repeated unavailable reads. + now := time.Now() + e.independentProbeMu.Lock() + if e.independentProbeActive || !e.independentProbeLast.IsZero() && now.Sub(e.independentProbeLast) < independentProbeInterval { + e.independentProbeMu.Unlock() + return nil + } + e.independentProbeActive, e.independentProbeLast = true, now + e.independentProbeMu.Unlock() + defer func() { + e.independentProbeMu.Lock() + e.independentProbeActive = false + e.independentProbeMu.Unlock() + }() + probeCtx, cancel := context.WithTimeout(ctx, independentProbeTimeout) + defer cancel() + w, err := observeIndependentClaim(probeCtx, reader, p.repositoryID, p.configuration, p.revision, p.predecessor, successor) + if err != nil || probeCtx.Err() != nil || !w.matches(e.sampleExecutionTime(), p.repositoryID, p.configuration, p.revision, p.predecessor, successor) { + return nil + } + return &w +} + +func (w independentClaimWitness) matchesPreparedAnchor(a Anchor) bool { + return a.RepositoryID == w.repositoryID && a.PullNumber == w.successor.PullNumber && + a.CandidateSHA == w.successor.HeadSHA && a.BaseSHA == w.baseSHA && a.ParentSHA == w.baseSHA && + a.BaseRef == w.defaultRef && a.ParentPullNumber == 0 +} + +// MatchesIndependentSourcePlan compares the immediately fresh trusted source +// read with the pre-reservation witness. Ordinary operations have no witness. +// Drivers use this before any provider work that could have side effects. +func (o Operation) MatchesIndependentSourcePlan(plan SourcePlan) bool { + w := o.independentClaim + if w == nil { + return true + } + return plan.SourceReason == "" && plan.Repository.DefaultBranch == w.defaultRef && + plan.Pull.IsDraft != nil && !*plan.Pull.IsDraft && + w.matchesPreparedAnchor(Anchor{RepositoryID: plan.Repository.ID, PullNumber: plan.Pull.Number, + CandidateSHA: plan.Pull.HeadSHA, BaseSHA: plan.Pull.BaseSHA, ParentSHA: plan.ParentSHA, + BaseRef: plan.Pull.BaseRef, ParentPullNumber: plan.ParentPullNumber}) +} diff --git a/internal/reviewexec/independent_claim_witness_test.go b/internal/reviewexec/independent_claim_witness_test.go new file mode 100644 index 000000000..2139372b2 --- /dev/null +++ b/internal/reviewexec/independent_claim_witness_test.go @@ -0,0 +1,211 @@ +package reviewexec + +import ( + "context" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +type witnessSource struct { + repo reviewprovider.Repository + pull reviewprovider.Pull +} + +func (s witnessSource) Repository(context.Context, int64) (reviewprovider.Repository, error) { + return s.repo, nil +} +func (s witnessSource) Pull(context.Context, string, int64) (reviewprovider.Pull, error) { + return s.pull, nil +} + +func TestIndependentClaimWitnessPinsFreshTrustedDefaultBranch(t *testing.T) { + previous := int64(2) + c := Configuration{ExpectedRevision: &previous, Mode: "independent", Queue: []int64{2, 4}, Channels: []string{"cli"}} + p := Operation{ID: "op_prior", ProjectID: "fixture", PullNumber: 2, Channel: "cli", State: "queued", HeadSHA: strings.Repeat("a", 40), ConfigurationRevision: 3, Revision: 2} + o := p + o.ID = "op_current" + o.PullNumber = 4 + o.HeadSHA = strings.Repeat("b", 40) + nonDraft := false + reader := witnessSource{repo: reviewprovider.Repository{ID: 701, FullName: "owner/canonical", DefaultBranch: "main"}, + pull: reviewprovider.Pull{Number: 4, RepositoryID: 701, State: "open", HeadSHA: o.HeadSHA, BaseSHA: strings.Repeat("c", 40), BaseRef: "main", IsDraft: &nonDraft, ChangedFiles: 1}} + w, err := observeIndependentClaim(t.Context(), reader, 701, c, 3, p, o) + now := time.Now().UTC() + if err != nil || !w.matches(now, 701, c, 3, p, o) { + t.Fatalf("fresh exact ordinary default-base observation refused: %v", err) + } + stale := w.observed.Add(independentClaimFreshness + time.Nanosecond) + if w.matches(stale, 701, c, 3, p, o) || w.matches(now, 702, c, 3, p, o) || w.matches(now, 701, c, 4, p, o) { + t.Fatal("wrong scope, revision or stale observation accepted") + } + skip := p + skip.Revision++ + if w.matches(now, 701, c, 3, skip, o) { + t.Fatal("different predecessor revision accepted") + } + target := o + target.HeadSHA = strings.Repeat("d", 40) + if w.matches(now, 701, c, 3, p, target) { + t.Fatal("different successor head accepted") + } + dependent := reader + dependent.pull.BaseRef = "branch-2" + skipped, _ := observeIndependentClaim(t.Context(), dependent, 701, c, 3, p, o) + if skipped.matches(now, 701, c, 3, p, o) { + t.Fatal("related source accepted as independent") + } + incomplete := reader + incomplete.pull.IsDraft = nil + skipped, _ = observeIndependentClaim(t.Context(), incomplete, 701, c, 3, p, o) + if skipped.matches(now, 701, c, 3, p, o) { + t.Fatal("unknown lifecycle accepted as exact") + } + anchor := Anchor{RepositoryID: 701, PullNumber: 4, CandidateSHA: o.HeadSHA, BaseSHA: reader.pull.BaseSHA, + ParentSHA: reader.pull.BaseSHA, BaseRef: "main"} + if !w.matchesPreparedAnchor(anchor) { + t.Fatal("ordinary fresh Prepare anchor was not bound to the witness") + } + refMoved := anchor + refMoved.BaseSHA = strings.Repeat("e", 40) + refMoved.ParentSHA = refMoved.BaseSHA + dependencyAdded := anchor + dependencyAdded.ParentPullNumber = 2 + if w.matchesPreparedAnchor(refMoved) || w.matchesPreparedAnchor(dependencyAdded) || + w.matches(w.observed.Add(-time.Nanosecond), 701, c, 3, p, o) { + t.Fatal("changed comparison or non-monotonic wall time accepted") + } + + active := o + active.independentClaim = &w + plan, err := ResolveSource(t.Context(), reader, 701, c, Request{PullNumber: 4, HeadSHA: o.HeadSHA, Channel: "cli"}) + if err != nil || !active.MatchesIndependentSourcePlan(plan) { + t.Fatal("fresh source did not reproduce the bound pre-reservation comparison", err) + } + plan.Repository.DefaultBranch = "changed-default" + if active.MatchesIndependentSourcePlan(plan) { + t.Fatal("changed default branch can no longer use the provisional witness") + } + if !o.MatchesIndependentSourcePlan(plan) { + t.Fatal("ordinary operation accidentally acquired the additional witness condition") + } + +} + +type witnessOnlyDriver struct{ reader TargetReader } + +func (d witnessOnlyDriver) IndependentQueueTargetReader() TargetReader { return d.reader } +func (d witnessOnlyDriver) Prepare(context.Context, Operation, Configuration, Attempt) (Preparation, error) { + panic("read-only probe must not prepare") +} +func (d witnessOnlyDriver) Dispatch(context.Context, Operation, Attempt, func(context.Context, string) error) (Result, error) { + panic("read-only probe must not dispatch") +} + +type blockedWitnessSource struct { + witnessSource + calls atomic.Int32 + started chan struct{} + release chan struct{} + deadline chan time.Time +} + +func (s *blockedWitnessSource) Repository(ctx context.Context, repo int64) (reviewprovider.Repository, error) { + if s.calls.Add(1) == 1 { + close(s.started) + if s.deadline != nil { + deadline, _ := ctx.Deadline() + s.deadline <- deadline + } + } + select { + case <-ctx.Done(): + return reviewprovider.Repository{}, ctx.Err() + case <-s.release: + } + return s.witnessSource.Repository(ctx, repo) +} + +func TestIndependentClaimWitnessProbeSingleReadAndNoPreparation(t *testing.T) { + previous := int64(2) + c := Configuration{ExpectedRevision: &previous, Mode: "independent", Queue: []int64{2, 4}, Channels: []string{"cli"}, CapabilityID: "authorized-adapter"} + p := Operation{ID: "op_prior", ProjectID: "fixture", PullNumber: 2, Channel: "cli", State: "queued", HeadSHA: strings.Repeat("a", 40), ConfigurationRevision: 3, Revision: 2} + o := p + o.ID = "op_current" + o.PullNumber = 4 + o.HeadSHA = strings.Repeat("b", 40) + isDraft := false + reader := &blockedWitnessSource{witnessSource: witnessSource{ + repo: reviewprovider.Repository{ID: 701, FullName: "owner/canonical", DefaultBranch: "main"}, + pull: reviewprovider.Pull{Number: 4, RepositoryID: 701, State: "open", HeadSHA: o.HeadSHA, BaseSHA: strings.Repeat("c", 40), BaseRef: "main", IsDraft: &isDraft, ChangedFiles: 1}}, + started: make(chan struct{}), release: make(chan struct{})} + drivers := map[string]Driver{c.CapabilityID: witnessOnlyDriver{reader: reader}} + probe := &queuePriorityPreflight{predecessor: p, configuration: c, revision: 3, repositoryID: 701} + e := &Engine{} + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + result := make(chan *independentClaimWitness, 1) + go func() { result <- e.probeIndependentClaim(ctx, drivers, probe, o) }() + select { + case <-reader.started: + case <-ctx.Done(): + t.Fatal("trusted source observation did not start") + } + if second := e.probeIndependentClaim(ctx, drivers, probe, o); second != nil || reader.calls.Load() != 1 { + t.Fatal("another worker used the bounded read slot before it was released") + } + close(reader.release) + select { + case w := <-result: + if w == nil { + t.Fatal("genuine source observation lost witness") + } + case <-ctx.Done(): + t.Fatal("trusted source observation did not finish") + } + if throttled := e.probeIndependentClaim(ctx, drivers, probe, o); throttled != nil || reader.calls.Load() != 1 { + t.Fatal("immediately repeated probe bypassed its shared throttle") + } +} + +func TestIndependentClaimWitnessProbeOwnDeadlineAndCancellation(t *testing.T) { + previous := int64(2) + c := Configuration{ExpectedRevision: &previous, Mode: "independent", Queue: []int64{2, 4}, Channels: []string{"cli"}, CapabilityID: "authorized-adapter"} + p := Operation{ID: "op_prior", ProjectID: "fixture", PullNumber: 2, Channel: "cli", State: "queued", HeadSHA: strings.Repeat("a", 40), ConfigurationRevision: 3, Revision: 2} + o := p + o.ID, o.PullNumber, o.HeadSHA = "op_current", 4, strings.Repeat("b", 40) + reader := &blockedWitnessSource{started: make(chan struct{}), release: make(chan struct{}), deadline: make(chan time.Time, 1)} + drivers := map[string]Driver{c.CapabilityID: witnessOnlyDriver{reader: reader}} + pending := &queuePriorityPreflight{predecessor: p, configuration: c, revision: 3, repositoryID: 701} + e := &Engine{} + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + result := make(chan *independentClaimWitness, 1) + go func() { result <- e.probeIndependentClaim(ctx, drivers, pending, o) }() + select { + case deadline := <-reader.deadline: + callerDeadline, _ := ctx.Deadline() + if deadline.IsZero() || !deadline.Before(callerDeadline) || time.Until(deadline) > independentProbeTimeout { + t.Fatal("trusted source reader inherited caller deadline instead of dedicated probe budget") + } + case <-time.After(5 * time.Second): + t.Fatal("trusted source read did not receive a bounded context") + } + cancel() + select { + case got := <-result: + if got != nil { + t.Fatal("a cancelled source read manufactured a witness") + } + case <-time.After(5 * time.Second): + t.Fatal("trusted read did not stop on cancellation") + } + e.independentProbeMu.Lock() + defer e.independentProbeMu.Unlock() + if e.independentProbeActive { + t.Fatal("cancelled probe did not release shared slot") + } +} diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index eb7b4c7ce..0b5c65147 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -293,6 +293,18 @@ func (e *Engine) ConfigureScheduling(ctx context.Context, scope core.Scope, key } return out, err } + +// A pull-specific retained control refusal is distinct from project +// scheduling, a query error, or another member of the queue. +type pullSchedulingStateError struct { + err error + project string + pull int64 +} + +func (e *pullSchedulingStateError) Error() string { return e.err.Error() } +func (e *pullSchedulingStateError) Unwrap() error { return e.err } + func readPullScheduling(ctx context.Context, tx *sql.Tx, project string, pull int64) (s PullScheduling, err error) { s.ProjectID = project s.PullNumber = pull @@ -311,11 +323,11 @@ func readPullScheduling(ctx context.Context, tx *sql.Tx, project string, pull in s.ActorID, actorOK = actor.(string) s.UpdatedAt, updatedOK = updated.(string) if !revisionOK || !pausedOK || !reasonOK || !actorOK || !updatedOK || pausedValue < 0 || pausedValue > 1 { - return s, schedulingRecordUnavailable() + 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, schedulingRecordUnavailable() + return s, &pullSchedulingStateError{schedulingRecordUnavailable(), project, pull} } return s, nil } diff --git a/internal/reviewexec/scheduling_authorization_continuity_test.go b/internal/reviewexec/scheduling_authorization_continuity_test.go index ec73db64c..b9519ec56 100644 --- a/internal/reviewexec/scheduling_authorization_continuity_test.go +++ b/internal/reviewexec/scheduling_authorization_continuity_test.go @@ -282,3 +282,39 @@ func TestAutomaticSameAuthorizerRevisionContinuity(t *testing.T) { } } } + +func TestAutomaticSameRevisionRetainsCanonicalAuthorizedIntent(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + t.Run(channel, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + if channel == "hosted" { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + } else { + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + } + r := schedulingLatest(t, f) + before := snapshotTable(t, f, "events") + if err := continuityGuard(t, f, r); err != nil { + t.Fatalf("current genuine scheduling event no longer proves the exact intent: %v", err) + } + if after := snapshotTable(t, f, "events"); after != before { + t.Fatal("authorization unexpectedly changed retained event history") + } + }) + } +} + +func TestSchedulingBasisRequiresExactEventForClaimedCurrentRevision(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + // The fixture has no scheduling history. Model an unsupported claimed + // revision solely as a validator input; don't modify retained state or + // invoke provider admission or an operation start. + claimed := schedulingRecord{Scheduling: Scheduling{ProjectID: attemptProject, Revision: 1, AutomaticHosted: true}} + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + _, _, err := schedulingBasisRevisions(ctx, tx, claimed) + return err + }) + attemptCode(t, err, "storage_unavailable") +} diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index bd3d2d0b0..d336aff34 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -76,6 +76,13 @@ func (e *Engine) requireAutomaticRun(ctx context.Context, tx *sql.Tx, r Run) err if !continuous { return automaticDenied() } + } else { + // A same-revision retry still requires the exact canonical event + // behind its enabled control. Use the same basis validation as + // a scheduling edit; 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 diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index d4cf81d85..e042aaa1e 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -326,6 +326,11 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL } earlier, err := e.earlierQueuedReviewIntentInSnapshot(ctx, tx, o, c, revision, emptyPredecessors) if err != nil { + var preflight *queuePriorityPreflight + if errors.As(err, &preflight) && preflight.repositoryID > 0 { + o.independentPreflight = preflight + return o, nil + } if automaticProjectRefused(err) || e.skipUnavailableConfiguration(ctx, o, err) || e.skipUnavailableWait(ctx, o, err) || e.skipUnavailableOperation(ctx, o, err) { return Operation{}, nil } @@ -723,7 +728,15 @@ func (e *Engine) processPendingBatchWithDraftCheck(ctx context.Context, drivers if draftReady { draftReadyRevision = o.Revision } - a, err := e.startAttempt(ctx, o.ProjectID, o.ID, draftReadyRevision, o.Revision) + var witness *independentClaimWitness + if pending := o.independentPreflight; pending != nil { + o.independentPreflight = nil + witness = e.probeIndependentClaim(ctx, drivers, pending, o) + if witness == nil { + continue + } + } + a, err := e.startAttemptWithWitness(ctx, o.ProjectID, o.ID, draftReadyRevision, o.Revision, witness) if err != nil { if ctx.Err() != nil { return nil @@ -758,6 +771,7 @@ func (e *Engine) processPendingBatchWithDraftCheck(ctx context.Context, drivers if driver == nil { return e.finishPreparation(a, "held", "capability_unavailable") } + o.independentClaim = witness prepareCtx, cancel := context.WithTimeout(ctx, 45*time.Second) prepared, err := driver.Prepare(prepareCtx, o, c, a) cancel() @@ -803,6 +817,14 @@ func (e *Engine) processPendingBatchWithDraftCheck(ctx context.Context, drivers } return e.finishPreparation(a, state, reason) } + if witness != nil && !witness.matchesPreparedAnchor(prepared.Anchor) { + // A later comparison cannot borrow the earlier default-branch + // observation. No journaled external intent exists yet. + if err := e.finishPreparation(a, "held", "target_changed"); err != nil { + return err + } + continue + } admitted, err := e.Admit(ctx, o.ProjectID, a.ID, a.Revision, prepared.Anchor, prepared.Intent) if err != nil { if ctx.Err() != nil { diff --git a/internal/reviewexec/types.go b/internal/reviewexec/types.go index 034bb75d5..4a054733b 100644 --- a/internal/reviewexec/types.go +++ b/internal/reviewexec/types.go @@ -75,6 +75,8 @@ type AllowanceObservation struct { } type Operation struct { + independentPreflight *queuePriorityPreflight + independentClaim *independentClaimWitness Wait *OperationWait `json:"wait,omitempty"` Allowance *AllowanceObservation `json:"allowance,omitempty"` AllowOutOfOrder bool `json:"allow_out_of_order,omitempty"` @@ -123,6 +125,9 @@ type Engine struct { configurationFailureMu sync.Mutex configurationFailureNext map[string]time.Time draftProbePermit atomic.Bool + independentProbeMu sync.Mutex + independentProbeActive bool + independentProbeLast time.Time draftProbeMu sync.Mutex draftProbeNext map[string]time.Time draftProbeCursor string diff --git a/internal/reviewruntime/cli_driver.go b/internal/reviewruntime/cli_driver.go index 732c45589..a2a270b05 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -125,6 +125,9 @@ func (d *CLIDriver) Prepare(ctx context.Context, operation reviewexec.Operation, if err != nil { return preparation, err } + if !operation.MatchesIndependentSourcePlan(plan) { + return preparation, reviewHold("target_changed") + } workspace, changedFiles, err := prepareReviewWorkspace(ctx, d.fetch, d.verify, d.manager, d.capability.GitHubCredential(), current, plan, attempt.ID) if err != nil { return preparation, err @@ -285,3 +288,7 @@ func retryCLIExhaustionSave(ctx context.Context, wait func(context.Context, time } return err } + +// IndependentQueueTargetReader provides read-only source observation before a +// reserved review attempt; ordinary preparation uses a separate fresh read. +func (d *CLIDriver) IndependentQueueTargetReader() reviewexec.TargetReader { return d.reader } diff --git a/internal/reviewruntime/hosted_driver.go b/internal/reviewruntime/hosted_driver.go index c253e3fcb..f6d411d35 100644 --- a/internal/reviewruntime/hosted_driver.go +++ b/internal/reviewruntime/hosted_driver.go @@ -178,6 +178,9 @@ func (d *HostedDriver) Prepare(ctx context.Context, operation reviewexec.Operati } return preparation, err } + if !operation.MatchesIndependentSourcePlan(plan) { + return preparation, reviewHold("target_changed") + } if err := d.checkIdle(ctx, plan); err != nil { return preparation, err } @@ -332,3 +335,7 @@ func (d *HostedDriver) Dispatch(ctx context.Context, operation reviewexec.Operat } return reviewexec.Result{State: "uncertain", Reason: "hosted_observation_pending", ExternalID: externalID}, nil } + +// IndependentQueueTargetReader provides read-only source observation before a +// reserved review attempt; ordinary preparation uses a separate fresh read. +func (d *HostedDriver) IndependentQueueTargetReader() reviewexec.TargetReader { return d.provider } From ede8d9da41d8b63b34675a029bfa264e844ccaf5 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 17:00:17 +1300 Subject: [PATCH 29/41] Fence quarantined review selection custody and preserve provenance --- docs/review-scheduling.md | 4 + internal/backup/inventory.go | 4 +- internal/backup/review_selection_test.go | 123 ++++++++++++++++- internal/reviewexec/cli_draft_wait.go | 6 + internal/reviewexec/hosted_priority.go | 8 ++ internal/reviewexec/run_selection.go | 96 +++++++++++-- internal/reviewexec/run_selection_schema.go | 55 +++++++- internal/reviewexec/run_selection_snapshot.go | 77 +++++++++++ internal/reviewexec/scheduling_automatic.go | 18 ++- internal/reviewexec/scheduling_snapshot.go | 19 ++- .../reviewexec/scheduling_source_retry.go | 2 +- .../selection_quarantine_custody_test.go | 126 ++++++++++++++++++ internal/reviewexec/supervisor.go | 6 + 13 files changed, 518 insertions(+), 26 deletions(-) create mode 100644 internal/reviewexec/selection_quarantine_custody_test.go diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index b09c2515a..18f5244a4 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -66,6 +66,10 @@ MCP equivalents are `review_scheduling_read`, `review_scheduling_configure`, `re Backups retain scheduling, PR pauses and automatic-intent attribution. Older bundles without this optional domain remain off; version-one Hosted-only records migrate with automatic CLI off. Restore remains inactive with provider execution held. Historical authorizers remain valid historical evidence after revocation or retirement. A legacy bundle may omit the PR control if its unique latest canonical event records an unpaused resume. Offline restore preserves that event’s actor, timestamp and revision in the inactive destination control, without changing the source bundle, event journal or authorization. A missing paused control or unresolved history remains invalid; a PR with no retained control history still reads at revision zero. +A proved linked selection custody hold retains its original child identifier and observed revision in a private versioned diagnostic record. It never changes the child, authorizer, retained evidence, or the existing provider action. Active capacity remains attributed as before; a demonstrably held child cannot obtain new admission or reserve an ordinary queued turn. Unproved or ambiguous provenance cannot establish eligibility and remains fail-closed. + +The selection custody schema upgrade is forward-only on the active database. Verify and retain a pre-upgrade version-one backup before upgrading. If binary rollback is required, restore that verified bundle to a separate inactive destination, with the existing recovery, activation and provider reconciliation procedure; do not run the old binary on the upgraded version-two database. Version-two backups are for compatible readers and preserve custody records indefinitely pending an explicit retention policy. There is no automatic deletion, retention expiry, or downgrade migration. + ## Validation The extracted source compiles across the repository. Focused tests pass for default-off behavior, exact authorizer withdrawal and continuity, writer/manager boundaries, pause before intent and dispatch, retained timer identity, cancellation suppression, independent progression, same-head dependency release, ordinary supervisor dispatch, bounded source retry, typed CLI/MCP help and diagnostics, exact-key recovery and backup/inactive restore. The focused execution group passed in 17.070 seconds with controlled providers and no live review allowance. diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index d1848c6ac..f8b9637c2 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -233,7 +233,7 @@ type tableVersion struct { // Fixed application schema bounds are intentionally independent of migration // execution. Inspection never opens a Store or installs/rewrites a schema. -var supportedDomains = map[string]int{"review_scheduling": 2, "review_fronts": 1, "project_management": 1, "worker_retirements": 1, "review_selection": 1, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 4, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} +var supportedDomains = map[string]int{"review_scheduling": 2, "review_fronts": 1, "project_management": 1, "worker_retirements": 1, "review_selection": 2, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 4, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} var tables = map[string]tableVersion{ "review_scheduling": {"review_scheduling", 1, "project_id revision automatic_hosted actor_id worker_id credential_id updated_at"}, "review_pull_scheduling": {"review_scheduling", 1, "project_id pull_number revision paused reason actor_id updated_at"}, @@ -241,6 +241,7 @@ var tables = map[string]tableVersion{ "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"}, @@ -1322,6 +1323,7 @@ var canonicalForeignKeys = map[string][]foreignKey{ "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")}, diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index 74b0ddc97..d3777fb19 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -239,7 +239,7 @@ func TestSelectionInventorySchemaAndPredecessor(t *testing.T) { // 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_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 { + 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) } } @@ -276,7 +276,7 @@ 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 NOT IN ('review_selections','review_scheduling','review_pull_scheduling','review_automatic_selections','review_front_frames') 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 NOT IN ('schema:review_selection','schema:review_scheduling','schema:review_fronts') ORDER BY key`); !reflect.DeepEqual(metadata, got) { @@ -287,19 +287,19 @@ 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)+5 { + if len(after) != len(before)+6 { t.Fatal("upgrade did not reinstall the newer optional domains", len(before), len(after)) } - for domain, version := range map[string]string{"review_selection": "1", "review_scheduling": "2", "review_fronts": "1"} { + 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_selections','review_scheduling','review_pull_scheduling','review_automatic_selections','review_front_frames')`).Scan(&count); err != nil || count != 5 { + 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 { @@ -314,3 +314,114 @@ func TestSelectionInventoryParentUpgradePreservesPhysicalSchemaAndRows(t *testin 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 TestSelectionQuarantineInventoryRetainsAutomaticChildWithoutAuthority(t *testing.T) { + f, _, _ := schedulingBackupFixture(t) + ctx := t.Context() + const children = `SELECT * FROM review_operations ORDER BY id` + const authors = `SELECT * FROM review_automatic_selections ORDER BY selection_id` + const journal = `SELECT * FROM events ORDER BY sequence` + beforeChildren, beforeAuthors, beforeJournal := restoreRows(t, f.store.DB(), children), restoreRows(t, f.store.DB(), authors), restoreRows(t, f.store.DB(), journal) + var selection, operation string + var revision int64 + if err := f.store.DB().QueryRow(`SELECT s.id,s.operation_id,s.revision FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id WHERE a.pull_number<>0`).Scan(&selection, &operation, &revision); err != nil { + t.Fatal(err) + } + // Construct only the canonical post-hold metadata for a normal synthetic + // selection. No inconsistent queued binding or provider dispatch is staged. + if err := f.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `INSERT INTO review_selection_quarantine + (selection_id,project_id,original_operation_id,original_state,observed_revision) VALUES(?,?,?,'selecting',?)`, selection, f.project, operation, revision); err != nil { + return err + } + _, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held',reason='linked_selection_quarantined', + revision=revision+1,operation_id=NULL WHERE id=?`, selection) + return err + }); err != nil { + t.Fatal(err) + } + bundle := restoreBundle(t, f) + destination := filepath.Join(t.TempDir(), "inactive-custody") + 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 !reflect.DeepEqual(beforeChildren, restoreRows(t, db, children)) || + !reflect.DeepEqual(beforeAuthors, restoreRows(t, db, authors)) || + !reflect.DeepEqual(beforeJournal, restoreRows(t, db, journal)) { + t.Fatal("restoring forensic custody changed the child, origin, or event history") + } + var got string + if err := db.QueryRow(`SELECT original_operation_id FROM review_selection_quarantine WHERE selection_id=?`, selection).Scan(&got); err != nil || got != operation { + t.Fatal("original automatic operation identity was not retained", got, err) + } +} diff --git a/internal/reviewexec/cli_draft_wait.go b/internal/reviewexec/cli_draft_wait.go index e621fa520..fbec0f85b 100644 --- a/internal/reviewexec/cli_draft_wait.go +++ b/internal/reviewexec/cli_draft_wait.go @@ -88,6 +88,9 @@ func (e *Engine) checkCLIDraft(ctx context.Context, o Operation, drivers map[str if current.State != "queued" || current.Revision != o.Revision { return conflict() } + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + return err + } if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections WHERE project_id=? AND operation_id=?)`, o.ProjectID, o.ID).Scan(&selected); err != nil || selected { return err } @@ -97,6 +100,9 @@ func (e *Engine) checkCLIDraft(ctx context.Context, o Operation, drivers map[str if err != nil { var refusal *core.Error if errors.As(err, &refusal) { + if refusal.Code == linkedSelectionCustodyHeld { + return false, false, false, err + } if refusal.Code == "overloaded" { // The worker still defers this row but must not acknowledge // exhausted work when storage prevented the readiness read. diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 39f3b6cbe..c5c7018b8 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -120,6 +120,14 @@ ORDER BY q.key,o.created_at,o.id`, string(queue), position, o.ProjectID, o.Chann } func (e *Engine) hostedPriorityBinding(ctx context.Context, tx *sql.Tx, o Operation) (bool, error) { + // A proved custody hold is already ineligible; do not let it consult or + // block unrelated source or provider evidence. + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + if isLinkedSelectionCustodyHeld(err) { + return false, nil + } + return false, err + } var err error if o.Channel == "hosted" { var installed bool diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index f04a68ade..98b50519b 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -318,7 +318,7 @@ func (e *Engine) RecoverReviewRuns(ctx context.Context) error { 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 { + if _, err := quarantineNativeSelection(ctx, tx, k.p, k.id, "selecting", k.revision); err != nil && !selectionCustodyUnproved(err) { return err } continue @@ -326,6 +326,11 @@ func (e *Engine) RecoverReviewRuns(ctx context.Context) error { 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 } @@ -437,7 +442,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 } @@ -484,28 +489,91 @@ func AbandonReviewRuns(ctx context.Context, tx *sql.Tx, at time.Time) (int64, er // 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. Keep its original damaged fields -// and any child link for diagnosis; do not fabricate a readable history entry. +// 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) { - if expected.State != "queued" && expected.State != "selecting" { - return false, nil - } - result, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held',reason='local_read_unavailable',revision=CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision+1 ELSE revision END WHERE project_id=? AND id=? AND state=? AND `+selectionClaimRevision+`=?`, expected.ProjectID, expected.ID, expected.State, expected.Revision) - if err != nil { - return false, err - } - n, err := result.RowsAffected() - return n == 1, err + 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 } - result, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held',reason='local_read_unavailable',revision=CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision+1 ELSE revision END WHERE project_id=? AND id=? AND state=? AND `+selectionClaimRevision+`=?`, project, id, state, revision) + const observed = ` WHERE project_id=? AND id=? AND state=? AND ` + selectionClaimRevision + `=?` + var originalLink, originalRevision any + err := tx.QueryRowContext(ctx, `SELECT operation_id,revision FROM review_selections`+observed, project, id, state, revision).Scan(&originalLink, &originalRevision) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + linkGuard := ` AND operation_id IS NULL` + holdReason := "local_read_unavailable" + args := []any{project, id, state, revision} + if originalLink != nil { + // Preserve only positively typed same-project custody. A missing + // child is valid diagnostic history; it cannot support a settled + // automatic binding or confer operation authority. + pid, projectOK := project.(string) + sid, selectionOK := id.(string) + op, linkOK := originalLink.(string) + native, revisionOK := originalRevision.(int64) + if !projectOK || !identifier.MatchString(pid) || !selectionOK || !validRunID(sid) || + !linkOK || !identifier.MatchString(op) || !revisionOK || native < 1 { + return false, &unprovedSelectionCustodyError{runUnavailable()} + } + // A retained child must still match the original immutable binding. + // Refuse foreign or inconsistent provenance rather than moving that + // record into a project where an unrelated operation could be held. + var inconsistent bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM review_selections s JOIN review_operations o ON o.id=s.operation_id + WHERE s.id=? AND s.project_id=? AND + (o.project_id<>s.project_id OR o.actor_id<>s.actor_id OR o.worker_id<>s.worker_id OR + o.channel<>s.channel OR o.configuration_revision<>s.configuration_revision OR + o.policy_revision<>s.policy_revision OR o.capability_fingerprint<>s.capability_fingerprint OR + (s.expected_pull_number<>0 AND o.pull_number<>s.expected_pull_number)) + UNION ALL + SELECT 1 FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id + LEFT JOIN review_operations o ON o.id=s.operation_id WHERE s.id=? AND s.project_id=? AND + (a.project_id<>s.project_id OR a.actor_id<>s.actor_id OR a.worker_id<>s.worker_id OR + typeof(a.pull_number)<>'integer' OR a.pull_number<0 OR a.pull_number>2147483647 OR + (a.pull_number<>0 AND (o.id IS NULL OR o.pull_number<>a.pull_number)) OR + (a.pull_number=0 AND a.pull_basis_sha256<>'')) + )`, sid, pid, sid, pid).Scan(&inconsistent); err != nil { + return false, err + } + if inconsistent { + return false, &unprovedSelectionCustodyError{runUnavailable()} + } + // Preserve the observed exact link without copying child or credential + // state. The outer transaction rolls this back if the hold fails. + if _, err := tx.ExecContext(ctx, `INSERT INTO review_selection_quarantine + (selection_id,project_id,original_operation_id,original_state,observed_revision) VALUES(?,?,?,?,?)`, sid, pid, op, state, native); err != nil { + return false, err + } + holdReason = "linked_selection_quarantined" + linkGuard = ` AND operation_id=?` + args = append(args, op) + } + result, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held',reason=?,operation_id=NULL, + revision=CASE WHEN typeof(revision)='integer' AND revision BETWEEN 1 AND 9223372036854775806 THEN revision+1 ELSE revision END`+observed+linkGuard, append([]any{holdReason}, args...)...) if err != nil { return false, err } n, err := result.RowsAffected() + if err == nil && n != 1 && originalLink != nil { + return false, runUnavailable() + } return n == 1, err } diff --git a/internal/reviewexec/run_selection_schema.go b/internal/reviewexec/run_selection_schema.go index a96fef207..b9bdc4c65 100644 --- a/internal/reviewexec/run_selection_schema.go +++ b/internal/reviewexec/run_selection_schema.go @@ -2,11 +2,13 @@ package reviewexec import ( "context" + "database/sql" + "errors" "github.com/benhook1013/FireController/internal/core" ) func EnsureSelectionSchema(ctx context.Context, store *core.Store) error { - return store.EnsureSchema(ctx, "review_selection", SelectionSchemaSQL()) + return store.EnsureSchema(ctx, "review_selection", SelectionSchemaSQL(), []string{selectionQuarantineTableSQL}) } // SelectionSchemaSQL returns an independent canonical DDL slice. @@ -23,3 +25,54 @@ func SelectionSchemaSQL() []string { `CREATE INDEX review_selections_pending ON review_selections(state,created_at,id)`, } } + +// The diagnostic binding is not an operation foreign key. It is only used for a +// well-typed historical link and cannot confer authority. +const selectionQuarantineTableSQL = `CREATE TABLE review_selection_quarantine( + selection_id TEXT NOT NULL PRIMARY KEY REFERENCES review_selections(id), + project_id TEXT NOT NULL REFERENCES projects(id), + original_operation_id TEXT NOT NULL CHECK(typeof(original_operation_id)='text' AND length(CAST(original_operation_id AS BLOB)) BETWEEN 1 AND 128), + original_state TEXT NOT NULL CHECK(original_state IN ('queued','selecting')), + observed_revision INTEGER NOT NULL CHECK(typeof(observed_revision)='integer' AND observed_revision>0), + UNIQUE(project_id,original_operation_id))` + +const linkedSelectionCustodyHeld = "selection_custody_quarantined" + +// requireUnquarantinedSelectionLink only denies work. The custody row cannot +// replace active selection attribution or authorize a new provider action. +func requireUnquarantinedSelectionLink(ctx context.Context, q EvidenceQuery, project, operation string) error { + var proved bool + err := q.QueryRowContext(ctx, `SELECT COALESCE(s.project_id=d.project_id AND s.state='held' AND + s.reason='linked_selection_quarantined' AND s.operation_id IS NULL AND + typeof(d.observed_revision)='integer' AND d.observed_revision>0 AND + typeof(s.revision)='integer' AND s.revision=CASE WHEN d.observed_revision=9223372036854775807 + THEN d.observed_revision ELSE d.observed_revision+1 END AND + d.original_state IN ('queued','selecting') AND + (o.id IS NULL OR (o.project_id=s.project_id AND o.actor_id=s.actor_id AND o.worker_id=s.worker_id AND + o.channel=s.channel AND o.configuration_revision=s.configuration_revision AND o.policy_revision=s.policy_revision AND + o.capability_fingerprint=s.capability_fingerprint AND (s.expected_pull_number=0 OR s.expected_pull_number=o.pull_number))) + AND NOT EXISTS(SELECT 1 FROM review_automatic_selections a WHERE a.selection_id=s.id AND + (a.project_id<>s.project_id OR a.actor_id<>s.actor_id OR a.worker_id<>s.worker_id OR + typeof(a.pull_number)<>'integer' OR a.pull_number<0 OR a.pull_number>2147483647 OR + (a.pull_number<>0 AND (o.id IS NULL OR o.pull_number<>a.pull_number)) OR + (a.pull_number=0 AND a.pull_basis_sha256<>''))), 0) + FROM review_selection_quarantine d LEFT JOIN review_selections s ON s.id=d.selection_id + LEFT JOIN review_operations o ON o.id=d.original_operation_id + WHERE d.project_id=? AND d.original_operation_id=?`, project, operation).Scan(&proved) + if errors.Is(err, sql.ErrNoRows) { + return nil + } + if err != nil { + return err + } + if !proved { + // An unknown custody row cannot establish ordinary ineligibility. + return runUnavailable() + } + return automaticProjectStateFailure(linkedSelectionCustodyHeld, "This review operation is held for selection custody recovery.", 403) +} + +func isLinkedSelectionCustodyHeld(err error) bool { + var failure *core.Error + return errors.As(err, &failure) && failure.Code == linkedSelectionCustodyHeld +} diff --git a/internal/reviewexec/run_selection_snapshot.go b/internal/reviewexec/run_selection_snapshot.go index acddb5483..1b7028e83 100644 --- a/internal/reviewexec/run_selection_snapshot.go +++ b/internal/reviewexec/run_selection_snapshot.go @@ -3,6 +3,7 @@ package reviewexec import ( "context" "fmt" + "math" "slices" "strings" @@ -16,6 +17,10 @@ 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 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 { @@ -152,3 +157,75 @@ 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' AND sql IS NOT NULL`).Scan(&objects); err != nil { + return err + } + if version == "1" && objects == 0 { + var danglingMarker bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections + WHERE reason='linked_selection_quarantined')`).Scan(&danglingMarker); err != nil { + return err + } + if danglingMarker { + return runUnavailable() + } + return nil + } + 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() + } + var inconsistent bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM review_selections s WHERE s.reason='linked_selection_quarantined' AND NOT EXISTS + (SELECT 1 FROM review_selection_quarantine d WHERE d.selection_id=s.id AND d.project_id=s.project_id) + UNION ALL + SELECT 1 FROM review_selection_quarantine d JOIN review_selections s ON s.operation_id=d.original_operation_id + UNION ALL + SELECT 1 FROM review_selection_quarantine d JOIN review_selections s ON s.id=d.selection_id + JOIN review_operations o ON o.id=d.original_operation_id + WHERE o.project_id<>s.project_id OR o.actor_id<>s.actor_id OR o.worker_id<>s.worker_id OR + o.channel<>s.channel OR o.configuration_revision<>s.configuration_revision OR + o.policy_revision<>s.policy_revision OR o.capability_fingerprint<>s.capability_fingerprint OR + (s.expected_pull_number<>0 AND o.pull_number<>s.expected_pull_number))`).Scan(&inconsistent); err != nil { + return err + } + if inconsistent { + return runUnavailable() + } + rows, err := q.QueryContext(ctx, `SELECT CASE WHEN typeof(d.original_operation_id)='text' AND length(CAST(d.original_operation_id AS BLOB))<=128 THEN d.original_operation_id END, + d.original_state,d.observed_revision,s.state,s.reason,s.operation_id,s.revision,s.project_id,d.project_id + FROM review_selection_quarantine d LEFT JOIN review_selections s ON s.id=d.selection_id`) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var link, oldState, state, reason, project, reportedProject string + var revision, observed, currentLink any + if err := rows.Scan(&link, &oldState, &observed, &state, &reason, ¤tLink, &revision, &project, &reportedProject); err != nil { + return err + } + old, oldOK := observed.(int64) + now, nowOK := revision.(int64) + if !identifier.MatchString(link) || oldState != "queued" && oldState != "selecting" || !oldOK || !nowOK || old < 1 || + (old < math.MaxInt64 && now != old+1 || old == math.MaxInt64 && now != old) || + state != "held" || reason != "linked_selection_quarantined" || currentLink != nil || project != reportedProject { + return runUnavailable() + } + } + return rows.Err() +} diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index d336aff34..11b8b544c 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -92,6 +92,9 @@ func (e *Engine) requireAutomaticRun(ctx context.Context, tx *sql.Tx, r Run) err return err } func (e *Engine) requireAutomaticOperation(ctx context.Context, tx *sql.Tx, o Operation) error { + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + return err + } var selection string err := tx.QueryRowContext(ctx, `SELECT s.id FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id AND a.project_id=s.project_id WHERE s.project_id=? AND s.operation_id=?`, o.ProjectID, o.ID).Scan(&selection) if errors.Is(err, sql.ErrNoRows) { @@ -450,7 +453,7 @@ func (e *Engine) automaticHostedQueuedPrefixChannel(ctx context.Context, tx *sql if err != nil { return 0, err } - rows, err := tx.QueryContext(ctx, `SELECT q.key,a.selection_id FROM review_operations o + rows, err := tx.QueryContext(ctx, `SELECT q.key,a.selection_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.project_id=o.project_id AND s.operation_id=o.id LEFT JOIN review_automatic_selections a ON a.project_id=s.project_id AND a.selection_id=s.id @@ -469,9 +472,20 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) } var position int var selection sql.NullString - if err := rows.Scan(&position, &selection); err != nil { + var operation string + var custodyPresent bool + if err := rows.Scan(&position, &selection, &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() + } // Explicit work has no automatic binding and keeps its position. if !selection.Valid { return position, nil diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 361d9bba3..92c9fe9f6 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -116,7 +116,24 @@ func ValidateSchedulingSnapshot(ctx context.Context, tx *sql.Tx) error { if bad { return schedulingUnavailable() } - err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections a LEFT JOIN review_selections s ON s.id=a.selection_id LEFT JOIN review_scheduling c ON c.project_id=a.project_id LEFT JOIN review_operations o ON o.id=s.operation_id WHERE s.id IS NULL OR s.project_id<>a.project_id OR s.channel NOT IN(`+channels+`) OR s.actor_id<>a.actor_id OR s.worker_id<>a.worker_id OR c.project_id IS NULL OR a.scheduling_revision>c.revision OR (a.pull_number=0 AND (a.pull_basis_sha256<>'' OR s.state='selected')) OR (a.pull_number<>0 AND (s.state<>'selected' OR o.id IS NULL OR o.pull_number<>a.pull_number OR o.project_id<>a.project_id OR o.channel<>s.channel OR o.actor_id<>a.actor_id OR o.worker_id<>a.worker_id)))`).Scan(&bad) + var selectionVersion string + if err := tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='schema:review_selection'`).Scan(&selectionVersion); err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + custodyJoin, linked, held := "", "s.operation_id", "0" + if selectionVersion == "2" { + custodyJoin = " LEFT JOIN review_selection_quarantine q ON q.selection_id=s.id AND q.project_id=s.project_id" + linked = "COALESCE(s.operation_id,q.original_operation_id)" + // The record is only a backup provenance exception. Runtime readers + // separately fence this operation; the held row cannot authorize it. + held = "(s.state='held' AND s.reason='linked_selection_quarantined' AND s.operation_id IS NULL AND q.selection_id IS NOT NULL)" + } + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections a LEFT JOIN review_selections s ON s.id=a.selection_id`+custodyJoin+` + LEFT JOIN review_scheduling c ON c.project_id=a.project_id LEFT JOIN review_operations o ON o.id=`+linked+` + WHERE s.id IS NULL OR s.project_id<>a.project_id OR s.channel NOT IN(`+channels+`) OR s.actor_id<>a.actor_id OR s.worker_id<>a.worker_id OR c.project_id IS NULL + OR a.scheduling_revision>c.revision OR (a.pull_number=0 AND (a.pull_basis_sha256<>'' OR s.state='selected')) + OR (a.pull_number<>0 AND ((s.state<>'selected' AND NOT `+held+`) OR o.id IS NULL OR o.pull_number<>a.pull_number + OR o.project_id<>a.project_id OR o.channel<>s.channel OR o.actor_id<>a.actor_id OR o.worker_id<>a.worker_id)))`).Scan(&bad) if err != nil { return err } diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index e1f02ae17..be8d4eadb 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -51,7 +51,7 @@ func (e *Engine) automaticSourceRetryCandidate(ctx context.Context, tx *sql.Tx, return nil, schedulingUnavailable() } var id string - err := tx.QueryRowContext(ctx, `SELECT s.id FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id AND a.project_id=s.project_id WHERE s.project_id=? AND s.channel=? AND s.state='held' AND s.operation_id IS NULL AND s.revision BETWEEN 3 AND 6 AND a.scheduling_revision=? AND (a.basis_sha256=? OR a.settled_basis_sha256=?) ORDER BY s.created_at DESC,s.id LIMIT 1`, project, channel, schedulingRevision, basis, basis).Scan(&id) + err := tx.QueryRowContext(ctx, `SELECT s.id FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id AND a.project_id=s.project_id WHERE s.project_id=? AND s.channel=? AND s.state='held' AND s.reason<>'linked_selection_quarantined' AND s.operation_id IS NULL AND s.revision BETWEEN 3 AND 6 AND a.scheduling_revision=? AND (a.basis_sha256=? OR a.settled_basis_sha256=?) ORDER BY s.created_at DESC,s.id LIMIT 1`, project, channel, schedulingRevision, basis, basis).Scan(&id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } diff --git a/internal/reviewexec/selection_quarantine_custody_test.go b/internal/reviewexec/selection_quarantine_custody_test.go new file mode 100644 index 000000000..6022eefea --- /dev/null +++ b/internal/reviewexec/selection_quarantine_custody_test.go @@ -0,0 +1,126 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" +) + +func TestSelectionQuarantineCustodyFencesOrdinaryReaders(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + t.Run(channel, func(t *testing.T) { checkSelectionQuarantineCustody(t, channel) }) + } +} + +func checkSelectionQuarantineCustody(t *testing.T, channel string) { + t.Helper() + f := schedulingFixtureWithQueue(t, []int64{2, 4}) + if channel == "hosted" { + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + } else { + schedulingCLIEnable(t, f, 0, true) + schedulingCLIGenerate(t, f, true) + } + selectionNext(t, f, &refreshTestReader{}) + r := schedulingLatest(t, f) + if r.State != "selected" || r.OperationID == "" { + t.Fatal("missing ordinary synthetic child") + } + children := snapshotTable(t, f, "review_operations") + actors := snapshotTable(t, f, "review_automatic_selections") + events := snapshotTable(t, f, "events") + // Exercise only the new canonical custody state, not corruption or an + // attempt to dispatch. The held record cannot create positive authority. + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `INSERT INTO review_selection_quarantine(selection_id,project_id,original_operation_id,original_state,observed_revision) + VALUES(?,?,?,'selecting',?)`, r.ID, r.ProjectID, r.OperationID, r.Revision); err != nil { + return err + } + _, err := tx.ExecContext(ctx, `UPDATE review_selections SET state='held',reason='linked_selection_quarantined',revision=revision+1, + operation_id=NULL WHERE id=?`, r.ID) + return err + }); err != nil { + t.Fatal(err) + } + var op Operation + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + var err error + op, err = readOperation(ctx, tx, r.ProjectID, r.OperationID) + if err != nil { + return err + } + return f.e.requireAutomaticOperation(ctx, tx, op) + }) + attemptCode(t, err, linkedSelectionCustodyHeld) + if channel == "cli" { + proceed, ready, explicit, err := f.e.checkCLIDraft(t.Context(), op, nil) + attemptCode(t, err, linkedSelectionCustodyHeld) + if proceed || ready || explicit { + t.Fatal("retained child was reclassified as an explicit CLI op") + } + } + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + c, _, err := readConfiguration(ctx, tx, r.ProjectID) + if err != nil { + return err + } + limit, err := f.e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, channel) + if err == nil && limit != len(c.Queue) { + t.Fatal("proven held child still blocked the ordinary queue prefix", limit, c.Queue) + } + return err + }) + if err != nil { + t.Fatal("proven held child blocked the ordinary prefix", err) + } + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + eligible, err := f.e.hostedPriorityBinding(ctx, tx, op) + if err == nil && eligible { + t.Fatal("proved held child occupied an ordinary queue turn") + } + return err + }) + if err != nil { + t.Fatal(err) + } + pending, err := f.e.pending(t.Context()) + if err != nil { + t.Fatal(err) + } + for _, candidate := range pending { + if candidate.ID == op.ID { + t.Fatal("proved held child reentered operation worker scan") + } + } + if children != snapshotTable(t, f, "review_operations") || actors != snapshotTable(t, f, "review_automatic_selections") || events != snapshotTable(t, f, "events") { + t.Fatal("custody fence rewrote child, authorizer, or event history") + } + // A valid-looking settled pull which no longer agrees with the exact + // retained child is unknown custody, not ordinary ineligibility. + admissionSQL(t, f, `UPDATE review_automatic_selections SET pull_number=4 WHERE selection_id=?`, r.ID) + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return f.e.requireAutomaticOperation(ctx, tx, op) + }) + attemptCode(t, err, "storage_unavailable") + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + _, err := f.e.hostedPriorityBinding(ctx, tx, op) + return err + }) + attemptCode(t, err, "storage_unavailable") + admissionSQL(t, f, `UPDATE review_automatic_selections SET pull_number=? WHERE selection_id=?`, op.PullNumber, r.ID) + + // A malformed diagnostic record cannot certify ordinary ineligibility + // in a read-only prefix; keep the existing conservative refusal. + admissionSQL(t, f, `UPDATE review_selection_quarantine SET observed_revision=observed_revision+1 WHERE selection_id=?`, r.ID) + err = f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + c, _, err := readConfiguration(ctx, tx, r.ProjectID) + if err != nil { + return err + } + _, err = f.e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, channel) + return err + }) + attemptCode(t, err, "storage_unavailable") + +} diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index e042aaa1e..a5f1237e6 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -279,6 +279,12 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL if o.State != "queued" { return Operation{}, nil } + if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { + if automaticProjectRefused(err) { + return Operation{}, nil + } + return Operation{}, err + } configuration, ok := configurations[o.ProjectID] if !ok { c, revision, err := readConfiguration(ctx, tx, o.ProjectID) From 1ef96a4e8087045e5ef4bf632d498da4d5b7af16 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 18:02:52 +1300 Subject: [PATCH 30/41] Preserve legacy backup inventory without linked custody --- internal/backup/review_selection_test.go | 8 +++++ internal/reviewexec/run_selection_snapshot.go | 32 +++++++++++++------ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index d3777fb19..160a704d8 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -425,3 +425,11 @@ func TestSelectionQuarantineInventoryRetainsAutomaticChildWithoutAuthority(t *te t.Fatal("original automatic operation identity was not retained", got, err) } } + +func TestSelectionQuarantineInventoryRejectsDanglingEmptyV2Marker(t *testing.T) { + f, _ := selectionInventoryFixture(t, "queued") + bundle := restoreBundle(t, f) + mutateBundleSQL(t, bundle.Path, `UPDATE review_selections + SET state='held',reason='linked_selection_quarantined',revision=2`) + assertCurrentSummaryInventoryRefused(t, bundle, false) +} diff --git a/internal/reviewexec/run_selection_snapshot.go b/internal/reviewexec/run_selection_snapshot.go index 1b7028e83..cadde15ac 100644 --- a/internal/reviewexec/run_selection_snapshot.go +++ b/internal/reviewexec/run_selection_snapshot.go @@ -168,15 +168,7 @@ func validateSelectionQuarantine(ctx context.Context, q EvidenceQuery) error { return err } if version == "1" && objects == 0 { - var danglingMarker bool - if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_selections - WHERE reason='linked_selection_quarantined')`).Scan(&danglingMarker); err != nil { - return err - } - if danglingMarker { - return runUnavailable() - } - return nil + return validateNoSelectionCustodyMarkers(ctx, q) } if version != "2" || objects != 1 { return runUnavailable() @@ -188,6 +180,16 @@ func validateSelectionQuarantine(ctx context.Context, q EvidenceQuery) error { 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 @@ -229,3 +231,15 @@ func validateSelectionQuarantine(ctx context.Context, q EvidenceQuery) error { } 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 +} From 79e2e62d1d3ca77e3de3b68093a4d71d2ec34f32 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 00:10:23 +1300 Subject: [PATCH 31/41] Preserve scheduling intent and queue claim continuity --- docs/review-scheduling.md | 4 +- internal/backup/review_fronts_test.go | 34 +++ internal/backup/review_selection_test.go | 11 + internal/reviewexec/attempts.go | 2 +- internal/reviewexec/hosted_priority.go | 35 ++- internal/reviewexec/hosted_wait.go | 11 +- .../reviewexec/independent_claim_witness.go | 70 ++++-- .../independent_claim_witness_test.go | 171 +++++++++++++- .../preferred_cli_wait_integrity_test.go | 129 +++++++++++ internal/reviewexec/queued_diagnostic.go | 28 ++- internal/reviewexec/run_http_test.go | 7 +- .../reviewexec/run_selection_capacity_test.go | 5 + internal/reviewexec/run_selection_snapshot.go | 4 +- internal/reviewexec/run_selection_worker.go | 3 + internal/reviewexec/scheduling.go | 20 +- ...g_adjudication_basis_compatibility_test.go | 44 ++-- .../scheduling_authorization_continuity.go | 8 +- ...cheduling_authorization_continuity_test.go | 5 +- internal/reviewexec/scheduling_cli.go | 7 + .../reviewexec/scheduling_cli_priority.go | 13 +- .../scheduling_recovery_regression_test.go | 23 +- internal/reviewexec/scheduling_snapshot.go | 60 ++--- ...cheduling_snapshot_event_integrity_test.go | 50 ++++- .../reviewexec/scheduling_source_retry.go | 18 +- .../scheduling_source_retry_test.go | 49 ++++ internal/reviewexec/scheduling_test.go | 209 +++++++++++------- .../reviewexec/selection_native_key_test.go | 103 +++++++-- internal/reviewexec/supervisor.go | 5 +- internal/reviewexec/types.go | 1 + internal/reviewexec/wait_deadline.go | 17 +- 30 files changed, 888 insertions(+), 258 deletions(-) create mode 100644 internal/reviewexec/preferred_cli_wait_integrity_test.go diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index 18f5244a4..a3f48e22e 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -4,7 +4,7 @@ This slice includes the scheduling engine, retained-state guards and HTTP API. Bound Go client, CLI and MCP controls and their packaged administration smoke are delivered in the dependent client slice. The current-review-progress browser consumer, its scoped live-event additions, generated assets and browser smoke workload are delivered in the dependent browser slice. Browser behavior and historical validation described below apply to that combined stack, not this intermediate scheduling tree. -Projects can independently opt in to automatic new Hosted or CLI requests. Both default to off. Explicit CLI requests continue to work without enabling automatic selection; a proven quota refusal retains any accepted request through [durable CLI waiting](retained-review-quota-controls.md), without replacing that operation. Automatic GitHub observation and automatic retry of an already authorized timer-backed request are independent of this setting; see [observation](github-observation.md) and [timer-backed waiting](retained-review-quota-controls.md). +Projects can independently opt in to automatic new Hosted or CLI requests. Both default to off. Explicit CLI requests continue to work without enabling automatic selection; a proven quota refusal retains any accepted request through [durable CLI waiting](retained-review-quota-controls.md), without replacing that operation. Automatic GitHub observation and timer-backed retries of explicit requests are independent of this setting. Retries of automatically selected requests still require their channel to be continuously enabled. See [observation](github-observation.md) and [timer-backed waiting](retained-review-quota-controls.md). ## Automatic Hosted requests @@ -46,6 +46,8 @@ The existing queue and PR detail views show current round allowance, closure or ## CLI and MCP +These scheduling commands and tools require the dependent client slice. The backend slice exposes the scheduling HTTP API. + Read the current scheduling revision before changing settings. Keep the exact request and key after an uncertain mutation outcome; replaying the same key cannot enable or pause twice. ```sh diff --git a/internal/backup/review_fronts_test.go b/internal/backup/review_fronts_test.go index 7995e641b..e90af049d 100644 --- a/internal/backup/review_fronts_test.go +++ b/internal/backup/review_fronts_test.go @@ -94,3 +94,37 @@ func TestFrontInventoryRejectsEmptyTableWithoutPrimaryKey(t *testing.T) { mutateBundleSQL(t, bundle.Path, `DROP TABLE review_front_frames;`+ddl) assertCurrentSummaryInventoryRefused(t, bundle, false) } + +func TestSchedulingUpgradePreservesExistingFrontInventory(t *testing.T) { + f, _ := selectionInventoryFixture(t, "held") + db := f.store.DB() + if _, err := db.Exec(` + DROP TABLE review_automatic_selections; + DROP TABLE review_pull_scheduling; + DROP TABLE review_scheduling; + DROP TABLE review_selection_quarantine; + UPDATE metadata SET value='1' WHERE key='schema:review_selection'; + DELETE FROM metadata WHERE key='schema:review_scheduling'; + `); err != nil { + t.Fatal(err) + } + var frontCount int + if err := db.QueryRow(`SELECT count(*) FROM review_front_frames`).Scan(&frontCount); err != nil || frontCount != 1 { + t.Fatal("predecessor front inventory", frontCount, err) + } + before := backupRows(t, db) + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal("front-aware predecessor refused", err) + } + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + after := backupRows(t, db) + if before["review_front_frames"] != after["review_front_frames"] { + t.Fatal("scheduling upgrade changed the retained front") + } + if err := reviewexec.ValidateFrontSnapshot(t.Context(), db); err != nil { + t.Fatal(err) + } +} diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index 160a704d8..3c8ee236a 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -380,6 +380,17 @@ func TestSelectionQuarantineInventoryKeepsV1Restore(t *testing.T) { 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 TestSelectionQuarantineInventoryRetainsAutomaticChildWithoutAuthority(t *testing.T) { f, _, _ := schedulingBackupFixture(t) ctx := t.Context() diff --git a/internal/reviewexec/attempts.go b/internal/reviewexec/attempts.go index 02ae74098..b10edc2bc 100644 --- a/internal/reviewexec/attempts.go +++ b/internal/reviewexec/attempts.go @@ -174,7 +174,7 @@ func (e *Engine) startAttemptWithWitness(ctx context.Context, project, id string return nil } var repositoryID int64 - if earlier, err := e.earlierQueuedReviewIntentWithWitness(ctx, tx, o, c, revision, nil, witness); err != nil { + if earlier, err := e.earlierQueuedReviewIntentWithWitness(ctx, tx, o, c, revision, nil, witness, false); err != nil { return err } else if earlier != nil { return nil diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index c5c7018b8..11a46a7d0 100644 --- a/internal/reviewexec/hosted_priority.go +++ b/internal/reviewexec/hosted_priority.go @@ -15,7 +15,7 @@ import ( // scheduler selection and the serialized attempt claim use this same snapshot // check; allow_out_of_order concerns dependencies, not scheduling priority. func (e *Engine) earlierQueuedReviewIntent(ctx context.Context, tx *sql.Tx, o Operation, c Configuration, revision int64) (*Operation, error) { - return e.earlierQueuedReviewIntentInSnapshot(ctx, tx, o, c, revision, nil) + return e.earlierQueuedReviewIntentWithWitness(ctx, tx, o, c, revision, nil, nil, false) } type queuePriorityKey struct { @@ -27,12 +27,12 @@ type queuePriorityKey struct { // An empty predecessor set can be reused only inside one read transaction. // Binding-dependent decisions still run separately for every candidate. func (e *Engine) earlierQueuedReviewIntentInSnapshot(ctx context.Context, tx *sql.Tx, o Operation, c Configuration, revision int64, empty map[queuePriorityKey]bool) (*Operation, error) { - return e.earlierQueuedReviewIntentWithWitness(ctx, tx, o, c, revision, empty, nil) + return e.earlierQueuedReviewIntentWithWitness(ctx, tx, o, c, revision, empty, nil, true) } type queuePriorityPreflight struct { cause error - predecessor Operation + predecessors []Operation configuration Configuration revision, repositoryID int64 } @@ -40,7 +40,7 @@ type queuePriorityPreflight struct { func (p *queuePriorityPreflight) Error() string { return p.cause.Error() } func (p *queuePriorityPreflight) Unwrap() error { return p.cause } -func (e *Engine) earlierQueuedReviewIntentWithWitness(ctx context.Context, tx *sql.Tx, o Operation, c Configuration, revision int64, empty map[queuePriorityKey]bool, witness *independentClaimWitness) (*Operation, error) { +func (e *Engine) earlierQueuedReviewIntentWithWitness(ctx context.Context, tx *sql.Tx, o Operation, c Configuration, revision int64, empty map[queuePriorityKey]bool, witness *independentClaimWitness, collectPreflight bool) (*Operation, error) { position := slices.Index(c.Queue, o.PullNumber) if !validChannel(o.Channel) || o.State != "queued" || position < 1 || c.Paused || revision < o.ConfigurationRevision { return nil, nil @@ -89,6 +89,8 @@ ORDER BY q.key,o.created_at,o.id`, string(queue), position, o.ProjectID, o.Chann if err != nil || !valid { return nil, err } + var preflight *queuePriorityPreflight + var repositoryID int64 for _, id := range ids { earlier, err := readOperation(ctx, tx, o.ProjectID, id) if err != nil { @@ -101,21 +103,32 @@ ORDER BY q.key,o.created_at,o.id`, string(queue), position, o.ProjectID, o.Chann !independentClaimPair(c, revision, earlier, o) { return nil, err } - var repoID int64 - if readErr := tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, o.ProjectID).Scan(&repoID); readErr != nil { - return nil, readErr + if repositoryID == 0 { + if readErr := tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, o.ProjectID).Scan(&repositoryID); readErr != nil { + return nil, readErr + } } - if witness != nil && witness.matches(e.sampleExecutionTime(), repoID, c, revision, earlier, o) { + if witness != nil && witness.matches(e.sampleExecutionTime(), repositoryID, c, revision, earlier, o) { continue } - // This still fences all non-supervisor callers. The supervisor - // may perform a separate bounded, trusted observation outside SQL. - return nil, &queuePriorityPreflight{err, earlier, c, revision, repoID} + if preflight == nil { + preflight = &queuePriorityPreflight{cause: err, configuration: c, revision: revision, repositoryID: repositoryID} + } + preflight.predecessors = append(preflight.predecessors, earlier) + // Only the supervisor's read pass collects additional pairs for + // one trusted observation outside the claim transaction. + if !collectPreflight { + return nil, preflight + } + continue } if valid { return &earlier, nil } } + if preflight != nil { + return nil, preflight + } return nil, nil } diff --git a/internal/reviewexec/hosted_wait.go b/internal/reviewexec/hosted_wait.go index b30bcfac0..0b01ee6a9 100644 --- a/internal/reviewexec/hosted_wait.go +++ b/internal/reviewexec/hosted_wait.go @@ -96,18 +96,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/independent_claim_witness.go b/internal/reviewexec/independent_claim_witness.go index 2b9468ad5..01b28332a 100644 --- a/internal/reviewexec/independent_claim_witness.go +++ b/internal/reviewexec/independent_claim_witness.go @@ -8,10 +8,10 @@ import ( // independentClaimWitness is one short-lived, internal observation. It is not // a client input, persisted source cache, or permission to reserve a slot. -// The supervisor constructs it only for an exact typed per-pull refusal, -// and the serialized claim rechecks those identities before any exemption. +// The supervisor constructs it only for exact typed per-pull refusals, +// and the serialized claim rechecks each identity before any exemption. type independentClaimWitness struct { - predecessor Operation + predecessors []Operation successor Operation configRevision int64 repositoryID int64 @@ -22,8 +22,10 @@ type independentClaimWitness struct { const independentClaimFreshness = 15 * time.Second -func observeIndependentClaim(ctx context.Context, reader TargetReader, repositoryID int64, c Configuration, currentRevision int64, predecessor, successor Operation) (independentClaimWitness, error) { - if !independentClaimPair(c, currentRevision, predecessor, successor) { +func observeIndependentClaim(ctx context.Context, reader TargetReader, repositoryID int64, c Configuration, currentRevision int64, predecessors []Operation, successor Operation) (independentClaimWitness, error) { + if len(predecessors) == 0 || slices.ContainsFunc(predecessors, func(predecessor Operation) bool { + return !independentClaimPair(c, currentRevision, predecessor, successor) + }) { return independentClaimWitness{}, nil } plan, err := ResolveSource(ctx, reader, repositoryID, c, Request{PullNumber: successor.PullNumber, HeadSHA: successor.HeadSHA, Channel: successor.Channel}) @@ -39,7 +41,7 @@ func observeIndependentClaim(ctx context.Context, reader TargetReader, repositor if err != nil || at.IsZero() { return independentClaimWitness{}, nil } - return independentClaimWitness{predecessor: predecessor, successor: successor, configRevision: currentRevision, + return independentClaimWitness{predecessors: slices.Clone(predecessors), successor: successor, configRevision: currentRevision, repositoryID: repositoryID, defaultRef: plan.Repository.DefaultBranch, baseSHA: plan.Pull.BaseSHA, observed: at}, nil } @@ -62,7 +64,8 @@ func (w independentClaimWitness) matches(now time.Time, repoID int64, c Configur return !w.observed.IsZero() && !now.Before(w.observed) && now.Sub(w.observed) <= independentClaimFreshness && repoID > 0 && repoID == w.repositoryID && w.defaultRef != "" && sha.MatchString(w.baseSHA) && w.configRevision == rev && independentClaimPair(c, rev, predecessor, successor) && - sameIndependentClaimOperation(predecessor, w.predecessor) && sameIndependentClaimOperation(successor, w.successor) + sameIndependentClaimOperation(successor, w.successor) && + slices.ContainsFunc(w.predecessors, func(observed Operation) bool { return sameIndependentClaimOperation(predecessor, observed) }) } func sameIndependentClaimOperation(a, b Operation) bool { @@ -81,36 +84,67 @@ type IndependentQueueSource interface { const ( independentProbeInterval = 5 * time.Second independentProbeTimeout = 10 * time.Second + independentProbeRetry = 30 * time.Second ) +type independentProbeKey struct { + project, operation string + revision int64 +} + +func independentProbeIdentity(o Operation) independentProbeKey { + return independentProbeKey{o.ProjectID, o.ID, o.Revision} +} + +func (e *Engine) independentProbeDeferred(o Operation) bool { + e.independentProbeMu.Lock() + defer e.independentProbeMu.Unlock() + return e.independentProbeNext[independentProbeIdentity(o)].After(time.Now()) +} + func (e *Engine) probeIndependentClaim(ctx context.Context, drivers map[string]Driver, p *queuePriorityPreflight, successor Operation) *independentClaimWitness { driver, ok := drivers[p.configuration.CapabilityID].(IndependentQueueSource) - if !ok { + if !ok || len(p.predecessors) == 0 { return nil } reader := driver.IndependentQueueTargetReader() if reader == nil { return nil } - // One optional source probe process-wide. Provider I/O is outside all - // transactions; the interval also bounds repeated unavailable reads. + // Keep the global source-read cadence. Defer a rejected target separately + // so it cannot take every probe slot from subsequent targets. Expiry and + // the global cadence bound the number of remembered targets. + key := independentProbeIdentity(successor) now := time.Now() e.independentProbeMu.Lock() - if e.independentProbeActive || !e.independentProbeLast.IsZero() && now.Sub(e.independentProbeLast) < independentProbeInterval { + if e.independentProbeActive || now.Sub(e.independentProbeLast) < independentProbeInterval || e.independentProbeNext[key].After(now) { e.independentProbeMu.Unlock() return nil } e.independentProbeActive, e.independentProbeLast = true, now + for candidate, next := range e.independentProbeNext { + if !next.After(now) { + delete(e.independentProbeNext, candidate) + } + } e.independentProbeMu.Unlock() - defer func() { - e.independentProbeMu.Lock() - e.independentProbeActive = false - e.independentProbeMu.Unlock() - }() + probeCtx, cancel := context.WithTimeout(ctx, independentProbeTimeout) defer cancel() - w, err := observeIndependentClaim(probeCtx, reader, p.repositoryID, p.configuration, p.revision, p.predecessor, successor) - if err != nil || probeCtx.Err() != nil || !w.matches(e.sampleExecutionTime(), p.repositoryID, p.configuration, p.revision, p.predecessor, successor) { + w, err := observeIndependentClaim(probeCtx, reader, p.repositoryID, p.configuration, p.revision, p.predecessors, successor) + valid := err == nil && probeCtx.Err() == nil && + w.matches(e.sampleExecutionTime(), p.repositoryID, p.configuration, p.revision, p.predecessors[0], successor) + + e.independentProbeMu.Lock() + e.independentProbeActive = false + if !valid && ctx.Err() == nil { + if e.independentProbeNext == nil { + e.independentProbeNext = make(map[independentProbeKey]time.Time) + } + e.independentProbeNext[key] = time.Now().Add(independentProbeRetry) + } + e.independentProbeMu.Unlock() + if !valid { return nil } return &w diff --git a/internal/reviewexec/independent_claim_witness_test.go b/internal/reviewexec/independent_claim_witness_test.go index 2139372b2..5c850343a 100644 --- a/internal/reviewexec/independent_claim_witness_test.go +++ b/internal/reviewexec/independent_claim_witness_test.go @@ -2,6 +2,10 @@ package reviewexec import ( "context" + "errors" + "fmt" + "reflect" + "slices" "strings" "sync/atomic" "testing" @@ -33,7 +37,7 @@ func TestIndependentClaimWitnessPinsFreshTrustedDefaultBranch(t *testing.T) { nonDraft := false reader := witnessSource{repo: reviewprovider.Repository{ID: 701, FullName: "owner/canonical", DefaultBranch: "main"}, pull: reviewprovider.Pull{Number: 4, RepositoryID: 701, State: "open", HeadSHA: o.HeadSHA, BaseSHA: strings.Repeat("c", 40), BaseRef: "main", IsDraft: &nonDraft, ChangedFiles: 1}} - w, err := observeIndependentClaim(t.Context(), reader, 701, c, 3, p, o) + w, err := observeIndependentClaim(t.Context(), reader, 701, c, 3, []Operation{p}, o) now := time.Now().UTC() if err != nil || !w.matches(now, 701, c, 3, p, o) { t.Fatalf("fresh exact ordinary default-base observation refused: %v", err) @@ -52,18 +56,20 @@ func TestIndependentClaimWitnessPinsFreshTrustedDefaultBranch(t *testing.T) { if w.matches(now, 701, c, 3, p, target) { t.Fatal("different successor head accepted") } + checkRefusal := func(source witnessSource, label string) { + t.Helper() + skipped, err := observeIndependentClaim(t.Context(), source, 701, c, 3, []Operation{p}, o) + checkedAt := time.Now().UTC() + if skipped.matches(checkedAt, 701, c, 3, p, o) || !reflect.DeepEqual(skipped, independentClaimWitness{}) { + t.Fatalf("%s returned a candidate witness: %+v (error: %v)", label, skipped, err) + } + } dependent := reader dependent.pull.BaseRef = "branch-2" - skipped, _ := observeIndependentClaim(t.Context(), dependent, 701, c, 3, p, o) - if skipped.matches(now, 701, c, 3, p, o) { - t.Fatal("related source accepted as independent") - } + checkRefusal(dependent, "non-default base") incomplete := reader incomplete.pull.IsDraft = nil - skipped, _ = observeIndependentClaim(t.Context(), incomplete, 701, c, 3, p, o) - if skipped.matches(now, 701, c, 3, p, o) { - t.Fatal("unknown lifecycle accepted as exact") - } + checkRefusal(incomplete, "unknown draft state") anchor := Anchor{RepositoryID: 701, PullNumber: 4, CandidateSHA: o.HeadSHA, BaseSHA: reader.pull.BaseSHA, ParentSHA: reader.pull.BaseSHA, BaseRef: "main"} if !w.matchesPreparedAnchor(anchor) { @@ -143,7 +149,7 @@ func TestIndependentClaimWitnessProbeSingleReadAndNoPreparation(t *testing.T) { pull: reviewprovider.Pull{Number: 4, RepositoryID: 701, State: "open", HeadSHA: o.HeadSHA, BaseSHA: strings.Repeat("c", 40), BaseRef: "main", IsDraft: &isDraft, ChangedFiles: 1}}, started: make(chan struct{}), release: make(chan struct{})} drivers := map[string]Driver{c.CapabilityID: witnessOnlyDriver{reader: reader}} - probe := &queuePriorityPreflight{predecessor: p, configuration: c, revision: 3, repositoryID: 701} + probe := &queuePriorityPreflight{predecessors: []Operation{p}, configuration: c, revision: 3, repositoryID: 701} e := &Engine{} ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() @@ -179,7 +185,7 @@ func TestIndependentClaimWitnessProbeOwnDeadlineAndCancellation(t *testing.T) { o.ID, o.PullNumber, o.HeadSHA = "op_current", 4, strings.Repeat("b", 40) reader := &blockedWitnessSource{started: make(chan struct{}), release: make(chan struct{}), deadline: make(chan time.Time, 1)} drivers := map[string]Driver{c.CapabilityID: witnessOnlyDriver{reader: reader}} - pending := &queuePriorityPreflight{predecessor: p, configuration: c, revision: 3, repositoryID: 701} + pending := &queuePriorityPreflight{predecessors: []Operation{p}, configuration: c, revision: 3, repositoryID: 701} e := &Engine{} ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) defer cancel() @@ -209,3 +215,146 @@ func TestIndependentClaimWitnessProbeOwnDeadlineAndCancellation(t *testing.T) { t.Fatal("cancelled probe did not release shared slot") } } + +func addWitnessQueue(t *testing.T, f *attemptFixture, project string, pulls ...int64) []Receipt { + t.Helper() + seedLegacyExecutionConfiguration(t, f, project, "witness-queue", enrollmentConfiguration(0, pulls, []string{"hosted"})) + var receipts []Receipt + for _, pull := range pulls { + receipts = append(receipts, f.enqueue(t, project, fmt.Sprintf("witness-pull-%d", pull), "hosted", pull, 1)) + } + return receipts +} + +func corruptWitnessPull(t *testing.T, f *attemptFixture, project string, pull int64) { + t.Helper() + if _, err := f.store.DB().Exec(`INSERT INTO review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at) + VALUES(?,?,1,0,'','synthetic-writer','invalid-time')`, project, pull); err != nil { + t.Fatal(err) + } +} + +type witnessQueueSource struct { + probed []int64 +} + +func (s *witnessQueueSource) Repository(_ context.Context, id int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{ID: id, FullName: fmt.Sprintf("owner/repo-%d", id), DefaultBranch: "main"}, nil +} + +func (s *witnessQueueSource) Pull(_ context.Context, repository string, pull int64) (reviewprovider.Pull, error) { + var id int64 + if _, err := fmt.Sscanf(repository, "owner/repo-%d", &id); err != nil { + return reviewprovider.Pull{}, err + } + s.probed = append(s.probed, pull) + base := "main" + if pull == 4 { + base = "non-default" + } + draft := false + return reviewprovider.Pull{Number: pull, RepositoryID: id, State: "open", HeadSHA: strings.Repeat("a", 40), + BaseSHA: strings.Repeat("b", 40), BaseRef: base, IsDraft: &draft, ChangedFiles: 1}, nil +} + +func TestIndependentClaimWitnessCoversEveryUnavailablePredecessor(t *testing.T) { + f := newAttemptFixture(t) + queue := addWitnessQueue(t, f, attemptProject, 2, 4, 6) + corruptWitnessPull(t, f, attemptProject, 2) + ops, err := f.e.pending(t.Context()) + if err != nil { + t.Fatal(err) + } + // An earlier healthy request keeps ordinary priority, even when another + // predecessor cannot be read. + if slices.ContainsFunc(ops, func(op Operation) bool { return op.ID == queue[2].ID }) { + t.Fatal("healthy predecessor lost priority") + } + corruptWitnessPull(t, f, attemptProject, 4) + ops, err = f.e.pending(t.Context()) + if err != nil { + t.Fatal(err) + } + i := slices.IndexFunc(ops, func(op Operation) bool { return op.ID == queue[2].ID }) + if i < 0 { + t.Fatal("successor was omitted after both earlier requests became unreadable") + } + successor := ops[i] + preflight := successor.independentPreflight + if preflight == nil || len(preflight.predecessors) != 2 || + preflight.predecessors[0].ID != queue[0].ID || preflight.predecessors[1].ID != queue[1].ID { + t.Fatalf("preflight did not retain both exact predecessors: %+v", preflight) + } + reader := &witnessQueueSource{} + drivers := map[string]Driver{"test-capability": witnessOnlyDriver{reader: reader}} + witness := f.e.probeIndependentClaim(t.Context(), drivers, preflight, successor) + if witness == nil || !slices.Equal(reader.probed, []int64{6}) { + t.Fatalf("wanted one trusted source observation for both pairs: %v", reader.probed) + } + partial := *witness + partial.predecessors = partial.predecessors[:1] + a, err := f.e.startAttemptWithWitness(t.Context(), attemptProject, successor.ID, 0, successor.Revision, &partial) + var missing *queuePriorityPreflight + if a.ID != "" || !errors.As(err, &missing) || len(missing.predecessors) != 1 || missing.predecessors[0].ID != queue[1].ID || + attemptCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatalf("partial witness did not leave the second predecessor fenced: %+v %v", a, err) + } + + a, err = f.e.startAttemptWithWitness(t.Context(), attemptProject, successor.ID, 0, successor.Revision, witness) + if err != nil || a.OperationID != successor.ID || a.State != "preparing" || + attemptCount(t, f.store, `SELECT count(*) FROM review_execution_attempts`) != 1 { + t.Fatalf("complete witness did not claim just the successor: %+v %v", a, err) + } + for _, earlier := range queue[:2] { + if supervisorOperationState(t, f, earlier.ID) != "queued" { + t.Fatal("source observation modified a predecessor") + } + } +} + +type witnessQueueDriver struct { + *controlledDriver + reader TargetReader +} + +func (d witnessQueueDriver) IndependentQueueTargetReader() TargetReader { return d.reader } + +func TestIndependentClaimWitnessRejectedProbeYieldsSharedSlot(t *testing.T) { + f := newAttemptFixture(t) + blocked := addWitnessQueue(t, f, attemptProject, 2, 4)[1] + later := addWitnessQueue(t, f, otherAttemptProject, 2, 6)[1] + corruptWitnessPull(t, f, attemptProject, 2) + corruptWitnessPull(t, f, otherAttemptProject, 2) + reader := &witnessQueueSource{} + driver := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + if o.ID != later.ID || o.independentClaim == nil { + t.Fatalf("the wrong candidate obtained an attempt: %+v", o) + } + return Preparation{}, errors.New("stop after proving local claim") + }} + drivers := map[string]Driver{"test-capability": witnessQueueDriver{controlledDriver: driver, reader: reader}} + runBatch := func() { + t.Helper() + ops, err := f.e.pending(t.Context()) + if err != nil { + t.Fatal(err) + } + if err := f.e.processPendingBatch(t.Context(), drivers, func() {}, 0, ops, pendingExhaustion{}); err != nil { + t.Fatal(err) + } + } + runBatch() + if !slices.Equal(reader.probed, []int64{4}) || driver.prepares.Load() != 0 { + t.Fatalf("the first nondefault candidate should consume just one source slot: %v", reader.probed) + } + // Advance just the shared interval while the failed target's retry + // remains deferred. No real sleep or dispatch is needed. + f.e.independentProbeMu.Lock() + f.e.independentProbeLast = f.e.independentProbeLast.Add(-independentProbeInterval) + f.e.independentProbeMu.Unlock() + runBatch() + if !slices.Equal(reader.probed, []int64{4, 6}) || driver.prepares.Load() != 1 || driver.calls.Load() != 0 || + supervisorOperationState(t, f, blocked.ID) != "queued" { + t.Fatalf("failed target took a second slot instead of yielding to the later candidate: %v", reader.probed) + } +} diff --git a/internal/reviewexec/preferred_cli_wait_integrity_test.go b/internal/reviewexec/preferred_cli_wait_integrity_test.go new file mode 100644 index 000000000..6a702a573 --- /dev/null +++ b/internal/reviewexec/preferred_cli_wait_integrity_test.go @@ -0,0 +1,129 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "testing" + "time" +) + +func TestPreferredCLIClaimWithExpiredCooldown(t *testing.T) { + for _, account := range []string{"test-capability", "other-account"} { + t.Run(account, func(t *testing.T) { + f, high, _, now := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, high.ID, high.Revision); err != nil { + t.Fatal(err) + } + *now = cliWaitDue(t, cliWaitRead(t, f, high.OperationID)).Add(time.Minute) + admissionSQL(t, f, `UPDATE projects SET repository=? WHERE id=?`, preferredCLIRepository, attemptProject) + f.configure(t, otherAttemptProject, account, 0, false) + low := f.enqueue(t, otherAttemptProject, "ordinary-claim", "cli", 2, 1) + if account == "test-capability" { + if a, err := f.e.StartAttempt(t.Context(), otherAttemptProject, low.ID); a.ID != "" || err != nil { + t.Fatalf("eligible preferred operation did not retain priority: %+v, %v", a, err) + } + } + admissionSQL(t, f, `DELETE FROM review_operation_waits WHERE operation_id=?`, high.OperationID) + if a, err := f.e.StartAttempt(t.Context(), attemptProject, high.OperationID); a.ID != "" || !isWaitUnavailable(err) { + t.Fatalf("preferred operation with missing wait was not refused: %+v, %v", a, err) + } + if a, err := f.e.StartAttempt(t.Context(), otherAttemptProject, low.ID); a.State != "preparing" || err != nil { + t.Fatalf("missing expired wait blocked a valid competing claim: %+v, %v", a, err) + } + }) + } +} + +func TestPreferredCLIMalformedNativeWaitPause(t *testing.T) { + f := schedulingFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + low := f.enqueue(t, attemptProject, "ordinary-claim", "cli", 2, 1) + high := f.enqueue(t, otherAttemptProject, "preferred-claim", "cli", 2, 1) + admissionSQL(t, f, `UPDATE projects SET repository=? WHERE id=?`, preferredCLIRepository, otherAttemptProject) + if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + // Corruption fixture only: the normal CHECK prevents storing this TEXT. + if _, err := tx.ExecContext(ctx, `PRAGMA ignore_check_constraints=ON`); err != nil { + return err + } + _, insertErr := tx.ExecContext(ctx, `INSERT INTO review_operation_waits(operation_id,paused) VALUES(?,'broken')`, high.ID) + _, resetErr := tx.ExecContext(ctx, `PRAGMA ignore_check_constraints=OFF`) + return errors.Join(insertErr, resetErr) + }); err != nil { + t.Fatal(err) + } + var storageClass string + if err := f.store.DB().QueryRowContext(t.Context(), `SELECT typeof(paused) FROM review_operation_waits WHERE operation_id=?`, high.ID).Scan(&storageClass); err != nil || storageClass != "text" { + t.Fatalf("expected native SQLite TEXT pause, got %q, %v", storageClass, err) + } + if _, err := readOperationBase(t.Context(), f.store.DB(), otherAttemptProject, high.ID); !isWaitUnavailable(err) { + t.Errorf("expected candidate-local malformed pause error, got %v", err) + } + if a, err := f.e.StartAttempt(t.Context(), attemptProject, low.ID); a.State != "preparing" || err != nil { + t.Fatalf("malformed preferred pause blocked a valid competing claim: %+v, %v", a, err) + } +} + +func TestPreferredCLIClaimSkipsWrongRoundBinding(t *testing.T) { + f := roundFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + admissionSQL(t, f, `UPDATE projects SET repository=? WHERE id=?`, preferredCLIRepository, attemptProject) + roundGrant(t, f, 2, "cli", 0, 0, 3, "preferred-round") + roundGrant(t, f, 4, "cli", 0, 0, 3, "other-round") + high := f.enqueue(t, attemptProject, "preferred", "cli", 2, 1) + low := f.enqueue(t, otherAttemptProject, "ordinary", "cli", 2, 1) + if a, err := f.e.StartAttempt(t.Context(), otherAttemptProject, low.ID); err != nil || a.ID != "" { + t.Fatalf("valid preferred request did not hold its turn: %+v %v", a, err) + } + admissionSQL(t, f, `UPDATE review_round_operation_bindings SET pull_number=4 WHERE operation_id=?`, high.ID) + if a, err := f.e.StartAttempt(t.Context(), attemptProject, high.ID); a.ID != "" || !isStoredUnavailable(err, storedRoundHistory) { + t.Fatalf("wrong round binding was not refused on its own claim: %+v %v", a, err) + } + if a, err := f.e.StartAttempt(t.Context(), otherAttemptProject, low.ID); err != nil || a.State != "preparing" { + t.Fatalf("malformed preferred request blocked the healthy claim: %+v %v", a, err) + } +} + +func TestOperationWaitPreservesOperationalErrors(t *testing.T) { + f := schedulingFixture(t) + r := f.enqueue(t, attemptProject, "wait-read", "cli", 2, 1) + o, err := readOperationIdentity(t.Context(), f.store.DB(), attemptProject, r.ID) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := readOperationWait(ctx, f.store.DB(), o); !errors.Is(err, context.Canceled) || isWaitUnavailable(err) { + t.Fatalf("cancellation lost its classification: %v", err) + } + admissionSQL(t, f, `ALTER TABLE review_operation_waits RENAME TO test_unavailable_waits`) + if _, err := readOperationWait(t.Context(), f.store.DB(), o); err == nil || isWaitUnavailable(err) { + t.Fatalf("missing table was not an operational failure: %v", err) + } +} + +func TestCLICooldownChecksDetachedPreparationJournal(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", cliDraftWait} { + t.Run(reason, func(t *testing.T) { + f, baseline, _, now := cliWaitFixture(t) + if _, err := f.e.ScheduleCLICooldown(t.Context(), attemptProject, baseline.ID, baseline.Revision); err != nil { + t.Fatal(err) + } + wait := cliWaitRead(t, f, baseline.OperationID).Wait + *now = mustWaitTime(wait.RetryNotBefore).Add(time.Minute) + retry := f.start(t, attemptProject, Receipt{ID: baseline.OperationID}) + if _, err := f.e.Advance(t.Context(), attemptProject, retry.ID, retry.Revision, "held", reason, ""); err != nil { + t.Fatal(err) + } + if got := cliWaitRead(t, f, baseline.OperationID); got.Wait == nil || got.Wait.BaselineAttemptID != baseline.ID || got.Wait.RetryNotBefore != wait.RetryNotBefore { + t.Fatalf("unused retry lost the original cooldown: %+v", got.Wait) + } + // Preserve the detached attempt and its final hold, but invalidate the + // exact first transition that should prove it was only a preparation. + admissionSQL(t, f, `UPDATE review_execution_transitions SET reason='not_preparing' WHERE attempt_id=? AND revision=1`, retry.ID) + if _, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, baseline.OperationID); !isWaitUnavailable(err) { + t.Fatalf("accepted detached hold with an invalid earlier transition: %v", err) + } + }) + } +} diff --git a/internal/reviewexec/queued_diagnostic.go b/internal/reviewexec/queued_diagnostic.go index 96f493969..9b254f0be 100644 --- a/internal/reviewexec/queued_diagnostic.go +++ b/internal/reviewexec/queued_diagnostic.go @@ -73,15 +73,20 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, } return err } - var originalJSON, latestJSON sql.NullString - var repositoryID, latestRevision int64 - err = tx.QueryRowContext(ctx, `SELECT CASE WHEN length(CAST(c.body_json AS BLOB))<=32768 THEN c.body_json END,CASE WHEN length(CAST(latest.body_json AS BLOB))<=32768 THEN latest.body_json END,p.github_repository_id,latest.revision FROM review_execution_config c JOIN projects p ON p.id=c.project_id JOIN review_execution_config latest ON latest.project_id=c.project_id AND latest.revision=(SELECT MAX(revision) FROM review_execution_config WHERE project_id=c.project_id) WHERE c.project_id=? AND c.revision=?`, op.ProjectID, op.ConfigurationRevision).Scan(&originalJSON, &latestJSON, &repositoryID, &latestRevision) + latest, latestRevision, err := readConfiguration(ctx, tx, op.ProjectID) if err != nil { return err } - var original, latest Configuration - if !originalJSON.Valid || !latestJSON.Valid || json.Unmarshal([]byte(originalJSON.String), &original) != nil || json.Unmarshal([]byte(latestJSON.String), &latest) != nil || validateConfigurationShape(original) != nil || validateConfigurationShape(latest) != nil { - return adjudicationStorageError() + original := latest + if latestRevision != op.ConfigurationRevision { + original, err = sourceConfiguration(ctx, tx, op.ProjectID, op.ConfigurationRevision) + if err != nil { + return err + } + } + originalCapability, ok := e.capabilities[original.CapabilityID] + if !ok || originalCapability.Fingerprint != op.CapabilityFingerprint { + return nil } switch { case op.Wait != nil && op.Wait.Paused: @@ -135,13 +140,8 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, } // Keep the generic diagnostic for an otherwise valid retained receipt. // The current configuration gates reservation attribution, not receipt - // visibility. Original capability drift still omits the diagnostic. + // visibility. The original capability was verified above. cause = "awaiting_scheduler" - originalCapability, ok := e.capabilities[original.CapabilityID] - if !ok || originalCapability.Fingerprint != op.CapabilityFingerprint { - cause = "" - return nil - } if op.Channel != "cli" { compatible, err = compatibleQueuedConfiguration(ctx, tx, op, latest, latestRevision) if err != nil { @@ -154,6 +154,10 @@ func (e *Engine) queuedDiagnosticDetails(ctx context.Context, scope core.Scope, capability.Fingerprint != op.CapabilityFingerprint { return nil } + var repositoryID int64 + if err := tx.QueryRowContext(ctx, `SELECT github_repository_id FROM projects WHERE id=?`, op.ProjectID).Scan(&repositoryID); err != nil { + return err + } reservation, err = queuedReservationHolder(ctx, tx, op, capability, repositoryID) if reservation != nil { cause = "reservation_busy" diff --git a/internal/reviewexec/run_http_test.go b/internal/reviewexec/run_http_test.go index 640c64a61..44376422c 100644 --- a/internal/reviewexec/run_http_test.go +++ b/internal/reviewexec/run_http_test.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "net/http/httptest" + "slices" "strings" "testing" "time" @@ -42,9 +43,11 @@ func TestRunHTTPWaitNegotiationVary(t *testing.T) { versions := []string{"", "1", "2", "3", "4", "5", "unsupported"} assertVary := func(t *testing.T, w *httptest.ResponseRecorder) { t.Helper() - vary := strings.Join(w.Header().Values("Vary"), ",") + vary := strings.Split(strings.Join(w.Header().Values("Vary"), ","), ",") for _, header := range []string{"Prefer", operationWaitHeader} { - if !strings.Contains(vary, header) { + if !slices.ContainsFunc(vary, func(field string) bool { + return strings.EqualFold(strings.TrimSpace(field), header) + }) { t.Errorf("missing Vary: %s in %v", header, w.Header()) } } diff --git a/internal/reviewexec/run_selection_capacity_test.go b/internal/reviewexec/run_selection_capacity_test.go index 475ebb49c..493bf0dab 100644 --- a/internal/reviewexec/run_selection_capacity_test.go +++ b/internal/reviewexec/run_selection_capacity_test.go @@ -170,13 +170,18 @@ func TestAutomaticSelectionCapacityDoesNotSettlePendingBasis(t *testing.T) { schedulingCLIEnable(t, f, 0, true) schedulingCLIGenerate(t, f, true) r := schedulingLatest(t, f) + var capacityHookReached bool reader := &refreshTestReader{ repository: func(_ context.Context, id int64) (reviewprovider.Repository, error) { selectionCapacityFill(t, f, attemptProject) + capacityHookReached = true return reviewprovider.Repository{ID: id, FullName: "owner/repo", DefaultBranch: "main"}, nil }, } selectionNext(t, f, reader) + if !capacityHookReached { + t.Fatal("first selection did not reach the capacity hook") + } var settled string if err := f.store.DB().QueryRow("SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?", r.ID).Scan(&settled); err != nil { t.Fatal(err) diff --git a/internal/reviewexec/run_selection_snapshot.go b/internal/reviewexec/run_selection_snapshot.go index cadde15ac..491da2f49 100644 --- a/internal/reviewexec/run_selection_snapshot.go +++ b/internal/reviewexec/run_selection_snapshot.go @@ -164,7 +164,9 @@ func validateSelectionQuarantine(ctx context.Context, q EvidenceQuery) error { return err } var objects int - if err := q.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_schema WHERE tbl_name='review_selection_quarantine' AND sql IS NOT NULL`).Scan(&objects); err != nil { + 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 { diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 1e0f6a03a..fd25f98ca 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -501,8 +501,11 @@ func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) ( // 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. + // A linked selection with a non-native key cannot prove custody. + // Leave it intact and allow unrelated selections to proceed. err := tx.QueryRowContext(ctx, `SELECT s.project_id,s.id,`+selectionClaimRevision+` FROM review_selections s WHERE s.state='queued' + AND (s.operation_id IS NULL OR (typeof(s.project_id)='text' AND typeof(s.id)='text')) AND (SELECT count(*) FROM review_operations WHERE state IN ('queued','preparing','posting','active','uncertain'))'' AND julianday(retry_not_before)>julianday(?))))`, earlier.ID, e.sampleExecutionTime().UTC().Format(time.RFC3339Nano)).Scan(&waiting); err != nil { + // An absent wait row is not proof that the candidate is fresh. A + // detached cooldown must still bind the original retry comparison. + if err := rejectMissingRetryWait(ctx, tx, earlier); err != nil { + if isWaitUnavailable(err) { + continue candidates + } return false, err } - if waiting { + if earlier.Wait != nil && earlier.Wait.RetryNotBefore != "" && e.sampleExecutionTime().Before(mustWaitTime(earlier.Wait.RetryNotBefore)) { continue } valid, err := e.hostedPriorityBinding(ctx, tx, earlier) if err != nil { - if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { + if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) || isStoredUnavailable(err, storedRoundHistory) { continue candidates } return false, err diff --git a/internal/reviewexec/scheduling_recovery_regression_test.go b/internal/reviewexec/scheduling_recovery_regression_test.go index ebe84f2fd..7f79e408c 100644 --- a/internal/reviewexec/scheduling_recovery_regression_test.go +++ b/internal/reviewexec/scheduling_recovery_regression_test.go @@ -239,12 +239,19 @@ func TestAutomaticGeneratorsIsolateRetainedParentCycle(t *testing.T) { } func TestAutomaticCLISourceRetryRechecksFencesAfterSourceIO(t *testing.T) { - for _, mode := range []string{"cancelled-operation", "scheduling", "configuration", "policy"} { + for _, tc := range []struct{ mode, reason string }{ + {"cancelled-operation", "selection_superseded"}, + {"scheduling", "automation_authorization_changed"}, + {"configuration", "configuration_changed"}, + {"policy", "policy_changed"}, + } { + mode := tc.mode t.Run(mode, func(t *testing.T) { f, r := cliSourceRetryFixture(t) ageSourceRetry(t, f, r.ID) schedulingCLIGenerate(t, f, true) var once sync.Once + var editApplied bool reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { once.Do(func() { switch mode { @@ -261,27 +268,31 @@ func TestAutomaticCLISourceRetryRechecksFencesAfterSourceIO(t *testing.T) { if err != nil { t.Fatal(err) } + editApplied = cliWaitRead(t, f, receipt.ID).State == "cancelled" case "scheduling": schedulingCLIEnable(t, f, 1, true) + editApplied = attemptCount(t, f.store, `SELECT count(*) FROM review_scheduling WHERE project_id=? AND revision=2`, r.ProjectID) == 1 case "configuration": f.configure(t, attemptProject, "test-capability", 1, false) + editApplied = attemptCount(t, f.store, `SELECT count(*) FROM review_execution_config WHERE project_id=? AND revision=2`, r.ProjectID) == 1 case "policy": assessmentPolicy(t, f, 1, []string{"cli"}, []string{}) + editApplied = attemptCount(t, f.store, `SELECT count(*) FROM review_policy_config WHERE project_id=? AND revision=2`, r.ProjectID) == 1 } }) return reviewprovider.Repository{ID: 801, FullName: "owner/repo", DefaultBranch: "main"}, nil }} selectionNext(t, f, reader) + if !editApplied { + t.Fatal("source callback did not apply the fence edit") + } got := selectionRead(t, f, r.ID) - if got.State != "held" || got.OperationID != "" { - t.Fatal("changed authority or cancelled successor ignored", got) + if got.State != "held" || got.Reason != tc.reason || got.OperationID != "" { + t.Fatalf("want hold reason %q and no child after the fence changed: %+v", tc.reason, got) } expected := 0 if mode == "cancelled-operation" { expected = 1 - if got.Reason != "selection_superseded" { - t.Fatal(got) - } } if attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != expected { t.Fatal("retry created a child after its fence changed") diff --git a/internal/reviewexec/scheduling_snapshot.go b/internal/reviewexec/scheduling_snapshot.go index 92c9fe9f6..0231bc6c2 100644 --- a/internal/reviewexec/scheduling_snapshot.go +++ b/internal/reviewexec/scheduling_snapshot.go @@ -215,9 +215,16 @@ const orphanPullSchedulingSQL = `WITH orphan AS ( WHERE e.event_type='review.pull_scheduling_updated' AND s.pull_number IS NULL )` +const latestOrphanPullResumesSQL = ` + FROM orphan o JOIN events e ON e.sequence=o.sequence + WHERE o.newest=1` + func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+` - SELECT resource_id,CASE WHEN typeof(revision)='integer' THEN revision END,payload,matches FROM orphan WHERE newest=1`) + SELECT CASE WHEN typeof(o.project_id)='text' THEN o.project_id END,o.resource_id, + CASE WHEN typeof(o.revision)='integer' THEN o.revision END,o.payload,o.matches, + CASE WHEN typeof(e.actor_id)='text' AND length(CAST(e.actor_id AS BLOB))<=128 THEN e.actor_id END, + CASE WHEN typeof(e.created_at)='text' AND length(CAST(e.created_at AS BLOB))<=64 THEN e.created_at END`+latestOrphanPullResumesSQL) if err != nil { return err } @@ -234,21 +241,21 @@ func validateOrphanPullSchedulingEvents(ctx context.Context, tx *sql.Tx) error { } func validateOrphanPullSchedulingEvent(row interface{ Scan(...any) error }) error { - var resource string - var revision any + var storedResource, revision any var matches int64 - var payload sql.NullString - if err := row.Scan(&resource, &revision, &payload, &matches); err != nil { + var project, payload, actor, createdAt sql.NullString + if err := row.Scan(&project, &storedResource, &revision, &payload, &matches, &actor, &createdAt); err != nil { return err } - return validateOrphanPullResume(resource, revision, payload, matches) -} - -func validateOrphanPullResume(resource string, revision any, payload sql.NullString, matches int64) error { + resource, ok := storedResource.(string) + if !ok || len(resource) > 10 { + return schedulingUnavailable() + } nativeRevision, revisionOK := revision.(int64) pull, err := strconv.ParseInt(resource, 10, 32) if err != nil || pull < 1 || strconv.FormatInt(pull, 10) != resource || !revisionOK || nativeRevision < 1 || matches != 1 || - !validPullSchedulingPayload(payload, pull, false) { + !validPullSchedulingPayload(payload, pull, false) || !project.Valid || !identifier.MatchString(project.String) || + !actor.Valid || !identifier.MatchString(actor.String) || !createdAt.Valid || !roundTime(createdAt.String) { return schedulingUnavailable() } return nil @@ -277,43 +284,14 @@ func RestoreHistoricalPullResumes(ctx context.Context, tx *sql.Tx) error { if version != "1" && version != "2" { return schedulingUnavailable() } - const candidates = ` - FROM orphan o JOIN events e ON e.sequence=o.sequence - WHERE o.newest=1` - rows, err := tx.QueryContext(ctx, orphanPullSchedulingSQL+` - SELECT o.project_id,o.resource_id,CASE WHEN typeof(o.revision)='integer' THEN o.revision END,o.payload,o.matches, - CASE WHEN typeof(e.actor_id)='text' THEN e.actor_id END, - CASE WHEN typeof(e.created_at)='text' THEN e.created_at END`+candidates) - if err != nil { - return err - } - defer rows.Close() - for rows.Next() { - var project, resource string - var revision any - var resumePayload, actor, createdAt sql.NullString - var matches int64 - if err := rows.Scan(&project, &resource, &revision, &resumePayload, &matches, &actor, &createdAt); err != nil { - return err - } - if err := validateOrphanPullResume(resource, revision, resumePayload, matches); err != nil { - return err - } - if !identifier.MatchString(project) || !actor.Valid || !identifier.MatchString(actor.String) || !createdAt.Valid || !roundTime(createdAt.String) { - return schedulingUnavailable() - } - } - if err := rows.Err(); err != nil { - return err - } - if err := rows.Close(); err != nil { + if err := validateOrphanPullSchedulingEvents(ctx, tx); err != nil { return err } // Both reads are in the same transaction, and no projection was inserted // until the complete set was validated. Keep the source event sequence. _, err = tx.ExecContext(ctx, orphanPullSchedulingSQL+` INSERT INTO review_pull_scheduling(project_id,pull_number,revision,paused,reason,actor_id,updated_at) - SELECT o.project_id,CAST(o.resource_id AS INTEGER),o.revision,0,'',e.actor_id,e.created_at`+candidates) + SELECT o.project_id,CAST(o.resource_id AS INTEGER),o.revision,0,'',e.actor_id,e.created_at`+latestOrphanPullResumesSQL) return err } diff --git a/internal/reviewexec/scheduling_snapshot_event_integrity_test.go b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go index 78994887c..eee412f6b 100644 --- a/internal/reviewexec/scheduling_snapshot_event_integrity_test.go +++ b/internal/reviewexec/scheduling_snapshot_event_integrity_test.go @@ -23,7 +23,7 @@ func schedulingEventSnapshotFixture(t *testing.T) *sql.Tx { 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)", + "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)", @@ -116,7 +116,7 @@ func TestOrphanResumeRequiresNativeRevisionWithoutChangingCompatibility(t *testi {"null", nil, false}, } { t.Run(tc.name, func(t *testing.T) { - row := tx.QueryRowContext(t.Context(), `SELECT '2', ?, '{"pull_number":2,"paused":false}', 1`, tc.revision) + 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 { @@ -128,3 +128,49 @@ func TestOrphanResumeRequiresNativeRevisionWithoutChangingCompatibility(t *testi }) } } + +func TestSchedulingSnapshotValidatesLatestOrphanResume(t *testing.T) { + for _, tc := range []struct { + name string + revision any + actor any + at any + }{ + {"text-revision", "1", "test-actor", stamp()}, + {"invalid-actor", int64(3), "invalid actor", stamp()}, + {"blob-actor", int64(3), []byte("test-actor"), stamp()}, + {"invalid-time", int64(3), "test-actor", "not-time"}, + {"blob-time", int64(3), "test-actor", []byte(stamp())}, + } { + t.Run(tc.name, func(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + const insert = `INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json,created_at) + VALUES ('test-project','2','review.pull_scheduling_updated',?,?,'{"pull_number":2,"paused":false}',?)` + if _, err := tx.ExecContext(t.Context(), insert, int64(2), "test-actor", stamp()); err != nil { + t.Fatal(err) + } + if err := ValidateSchedulingSnapshot(t.Context(), tx); err != nil { + t.Fatalf("valid legacy resume rejected: %v", err) + } + if _, err := tx.ExecContext(t.Context(), insert, tc.revision, tc.actor, tc.at); err != nil { + t.Fatal(err) + } + attemptCode(t, ValidateSchedulingSnapshot(t.Context(), tx), "storage_unavailable") + }) + } +} + +func TestOrphanResumeRejectsBlobResourceInSnapshotAndRestore(t *testing.T) { + tx := schedulingEventSnapshotFixture(t) + if _, err := tx.ExecContext(t.Context(), `INSERT INTO metadata VALUES('restore:state','inactive'); + INSERT INTO events(project_id,resource_id,event_type,revision,actor_id,payload_json,created_at) + VALUES ('test-project',X'32','review.pull_scheduling_updated',1,'test-actor','{"pull_number":2,"paused":false}',?)`, stamp()); err != nil { + t.Fatal(err) + } + attemptCode(t, ValidateSchedulingSnapshot(t.Context(), tx), "storage_unavailable") + attemptCode(t, RestoreHistoricalPullResumes(t.Context(), tx), "storage_unavailable") + var rows int + if err := tx.QueryRowContext(t.Context(), `SELECT count(*) FROM review_pull_scheduling`).Scan(&rows); err != nil || rows != 0 { + t.Fatalf("invalid resource produced a projection: %d %v", rows, err) + } +} diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index be8d4eadb..7dab1005d 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -91,19 +91,31 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin if !validChannel(r.Channel) || r.Revision < 4 { return "", nil } - var accepted, current int64 - err := tx.QueryRowContext(ctx, `SELECT a.scheduling_revision,s.revision FROM review_automatic_selections a JOIN review_scheduling s ON s.project_id=a.project_id WHERE a.project_id=? AND a.selection_id=?`, r.ProjectID, r.ID).Scan(&accepted, ¤t) + var retainedRevision any + err := tx.QueryRowContext(ctx, `SELECT scheduling_revision FROM review_automatic_selections WHERE project_id=? AND selection_id=?`, r.ProjectID, r.ID).Scan(&retainedRevision) if errors.Is(err, sql.ErrNoRows) { return "", nil } if err != nil { return "", err } + // Compare native SQLite integers, not values coerced by Scan into int64. + accepted, validRevision := retainedRevision.(int64) + if !validRevision || accepted < 1 { + return "", schedulingUnavailable() + } + current, err := readScheduling(ctx, tx, r.ProjectID) + if err != nil { + return "", err + } + if current.Revision == 0 { + return "automation_authorization_changed", nil + } initial, err := automaticSourceInitialRead(ctx, tx, r) if err != nil || initial { return "", err } - if accepted != current { + if accepted != current.Revision { return "automation_authorization_changed", nil } superseded, err := automaticSourceSuperseded(ctx, tx, r) diff --git a/internal/reviewexec/scheduling_source_retry_test.go b/internal/reviewexec/scheduling_source_retry_test.go index 6cffb7424..aa8d30a90 100644 --- a/internal/reviewexec/scheduling_source_retry_test.go +++ b/internal/reviewexec/scheduling_source_retry_test.go @@ -374,6 +374,55 @@ func TestAutomaticSourceRetryRechecksFencesAfterSourceIO(t *testing.T) { } } +func TestAutomaticCLISourceRetryRejectsBlobSchedulingRevisionAfterSourceIO(t *testing.T) { + f, r := cliSourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + schedulingCLIGenerate(t, f, true) + beforeBasis := snapshotTable(t, f, "review_automatic_selections") + beforeFront := snapshotTable(t, f, "review_front_frames") + var checked bool + reader := &refreshTestReader{repository: func(ctx context.Context, _ int64) (reviewprovider.Repository, error) { + admissionSQL(t, f, `UPDATE review_scheduling SET revision=CAST(revision AS BLOB) WHERE project_id=?`, r.ProjectID) + err := f.e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + current, err := readRun(ctx, tx, r.ProjectID, r.ID) + if err != nil { + return err + } + if current.State != "selecting" || current.Revision != 5 { + t.Fatalf("expected an in-flight source retry, got %+v", current) + } + var storageClass, revisionHex string + if err := tx.QueryRowContext(ctx, `SELECT typeof(revision),hex(revision) FROM review_scheduling WHERE project_id=?`, r.ProjectID).Scan(&storageClass, &revisionHex); err != nil { + return err + } + if storageClass != "blob" || revisionHex != "31" { + t.Fatal("expected a BLOB containing 1, got", storageClass, revisionHex) + } + checked = true + _, err = automaticSourceRecoveryFence(ctx, tx, current) + return err + }) + if !automaticProjectRefused(err) { + t.Errorf("source retry fence accepted a malformed scheduling revision: %v", err) + } + return reviewprovider.Repository{ID: 801, FullName: "owner/repo", DefaultBranch: "main"}, nil + }} + selectionNext(t, f, reader) + got := selectionRead(t, f, r.ID) + if !checked || got.State != "held" || got.Reason != "automatic_scheduling_unavailable" || got.Revision != 6 || got.OperationID != "" { + t.Fatal("expected a local refusal at retry settlement", got) + } + if beforeBasis != snapshotTable(t, f, "review_automatic_selections") || beforeFront != snapshotTable(t, f, "review_front_frames") || attemptCount(t, f.store, `SELECT count(*) FROM review_operations`) != 0 { + t.Fatal("refused retry retained front frame, basis, or child changes") + } + admissionSQL(t, f, `UPDATE review_scheduling SET revision=1 WHERE project_id=?`, r.ProjectID) + ageSourceRetry(t, f, r.ID) + schedulingCLIGenerate(t, f, false) + if afterRepair := selectionRead(t, f, r.ID); afterRepair.State != got.State || afterRepair.Reason != got.Reason || afterRepair.Revision != got.Revision { + t.Fatal("repair reopened the refused retry", afterRepair) + } +} + func TestAutomaticSourceRetryAcceptanceOrderSurvivesClockRollback(t *testing.T) { f, r := sourceRetryFixture(t) ageSourceRetry(t, f, r.ID) diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index 5f0a1ee60..db229b862 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -17,6 +17,7 @@ import ( "strings" "sync/atomic" "testing" + "testing/synctest" "time" ) @@ -60,6 +61,26 @@ func schedulingLatest(t *testing.T, f *attemptFixture) Run { } return selectionRead(t, f, id) } + +func TestSchedulingRequestRejectsExplicitCLINull(t *testing.T) { + for _, field := range []string{"automatic_cli", "AUTOMATIC_CLI", "Automatic_CLI"} { + t.Run(field, func(t *testing.T) { + var request SchedulingRequest + if err := json.Unmarshal([]byte(fmt.Sprintf(`{"automatic_hosted":false,%q:null}`, field)), &request); err == nil { + t.Fatal("accepted an explicit null CLI setting") + } + for _, literal := range []string{"true", "false"} { + if err := json.Unmarshal([]byte(fmt.Sprintf(`{"automatic_hosted":false,%q:%s}`, field, literal)), &request); err != nil || request.AutomaticCLI == nil || *request.AutomaticCLI != (literal == "true") { + t.Fatalf("did not preserve the explicit CLI choice: %v", err) + } + } + if err := json.Unmarshal([]byte(`{"automatic_hosted":false}`), &request); err != nil || request.AutomaticCLI != nil { + t.Fatalf("did not preserve omission: %v", err) + } + }) + } +} + func TestSchedulingHTTPDefaultsStrictCASAndPermissions(t *testing.T) { f := schedulingFixture(t) call := func(method, path, token, key, body string) *httptest.ResponseRecorder { @@ -77,15 +98,15 @@ func TestSchedulingHTTPDefaultsStrictCASAndPermissions(t *testing.T) { if w.Code != 200 || strings.TrimSpace(w.Body.String()) != `{"paused_pulls":[],"project_id":"exec-project-one","revision":0,"automatic_cli":false,"automatic_hosted":false}` { t.Fatal(w.Code, w.Body.String()) } - checkPullScheduling := func(w *httptest.ResponseRecorder, revision int64) { + checkPullScheduling := func(w *httptest.ResponseRecorder, revision int64, paused bool, reason string) { t.Helper() var p PullScheduling if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &p) != nil || - p.ProjectID != attemptProject || p.PullNumber != 2 || p.Paused || p.Revision != revision || p.Reason != "" { + p.ProjectID != attemptProject || p.PullNumber != 2 || p.Paused != paused || p.Revision != revision || p.Reason != reason { t.Fatal(w.Code, w.Body.String()) } } - checkPullScheduling(call("GET", "pulls/2/scheduling", f.reader, "", ""), 0) + checkPullScheduling(call("GET", "pulls/2/scheduling", f.reader, "", ""), 0, false, "") for _, path := range []string{"scheduling", "pulls/2/scheduling"} { head := call("HEAD", path, f.reader, "", "") if head.Code != http.StatusOK || !strings.HasPrefix(head.Header().Get("Content-Type"), "application/json") { @@ -125,10 +146,11 @@ func TestSchedulingHTTPDefaultsStrictCASAndPermissions(t *testing.T) { if w = call("POST", "pulls/2/scheduling", f.writer, "pause", `{"expected_revision":0,"paused":true,"reason":"Fixing"}`); w.Code != 200 { t.Fatal(w.Code, w.Body.String()) } + checkPullScheduling(call("GET", "pulls/2/scheduling", f.reader, "", ""), 1, true, "Fixing") if w = call("POST", "pulls/2/scheduling", f.writer, "resume", `{"expected_revision":1,"paused":false,"reason":"discarded"}`); w.Code != 200 { t.Fatal(w.Code, w.Body.String()) } - checkPullScheduling(call("GET", "pulls/2/scheduling", f.reader, "", ""), 2) + checkPullScheduling(call("GET", "pulls/2/scheduling", f.reader, "", ""), 2, false, "") admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) if w = call("POST", "scheduling", f.writer, "enable", `{"expected_revision":0,"automatic_hosted":true}`); w.Code != 403 { t.Fatal("replay bypassed current management", w.Code) @@ -848,11 +870,14 @@ func frontMergedPull() reviews.PullInput { p := projectionPull(1); p.State = "me func TestSchedulingAutomaticWorkspaceBasisUsesTargetFirstCurrentReferences(t *testing.T) { f := frontFixture(t) - for _, query := range []string{automaticCurrentRunsBasisQuery, automaticCurrentFindingsBasisQuery} { - if automaticBasisQuery(query, false) != query { + for _, tc := range []struct{ query, history, lookup string }{ + {automaticCurrentRunsBasisQuery, "v", "(project_id=? AND id=? AND version_revision=?)"}, + {automaticCurrentFindingsBasisQuery, "f", "(project_id=? AND run_id=? AND run_version_revision=?)"}, + } { + if automaticBasisQuery(tc.query, false) != tc.query { t.Fatal("ordinary query text changed") } - rows, err := f.store.DB().QueryContext(t.Context(), "EXPLAIN QUERY PLAN "+automaticBasisQuery(query, true), attemptProject, 2) + rows, err := f.store.DB().QueryContext(t.Context(), "EXPLAIN QUERY PLAN "+automaticBasisQuery(tc.query, true), attemptProject, 2) if err != nil { t.Fatal(err) } @@ -870,14 +895,25 @@ func TestSchedulingAutomaticWorkspaceBasisUsesTargetFirstCurrentReferences(t *te if err != nil { t.Fatal(err) } - joined := strings.Join(plan, "\n") - if !strings.Contains(joined, "SEARCH c USING INDEX") || !strings.Contains(plan[0], "project_id=? AND pull_number=?") { + if len(plan) == 0 || !strings.HasPrefix(plan[0], "SEARCH c USING INDEX") || !strings.Contains(plan[0], "project_id=? AND pull_number=?") { t.Fatal("basis starts from project-wide history instead of selected current PR", plan) } + lookedUpVersion := false for _, detail := range plan { - if (strings.Contains(detail, "SEARCH v ") || strings.Contains(detail, "SEARCH f ")) && strings.HasSuffix(detail, "(project_id=?)") { - t.Fatal("basis walks unrelated historical versions", plan) + scan := "SCAN " + tc.history + search := "SEARCH " + tc.history + " " + if detail == scan || strings.HasPrefix(detail, scan+" ") { + t.Fatal("basis scans historical versions", plan) } + if strings.HasPrefix(detail, search) { + if !strings.HasSuffix(detail, tc.lookup) { + t.Fatal("history lookup is not keyed to the current version", plan) + } + lookedUpVersion = true + } + } + if !lookedUpVersion { + t.Fatal("basis did not look up the current historical version", plan) } } } @@ -947,73 +983,84 @@ func TestAutomaticIdlePlanningDoesNotEnterWriter(t *testing.T) { for _, channel := range []string{"hosted", "cli"} { for _, idle := range []string{"paused", "pending", "cancelled", "held-source-not-due"} { t.Run(channel+"/"+idle, func(t *testing.T) { - f := schedulingFixtureWithQueue(t, []int64{2}) - on, zero := true, int64(0) - scope := selectionScope(t, f, attemptProject, f.writer, "write") - if _, err := f.e.ConfigureScheduling(t.Context(), scope, "idle-enable", SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { - t.Fatal(err) - } - reader := &refreshTestReader{} - readers := map[string]TargetReader{"test-capability": reader} - generate := f.e.generateAutomaticHosted - if channel == "cli" { - generate = f.e.generateAutomaticCLI - } - if idle == "paused" { - schedulingPause(t, f, 2, 0, true) - } else { - if worked, err := generate(t.Context(), readers); err != nil || !worked { - t.Fatal(worked, err) + synctest.Test(t, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + on, zero := true, int64(0) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + if _, err := f.e.ConfigureScheduling(t.Context(), scope, "idle-enable", SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { + t.Fatal(err) } - if idle == "cancelled" { - selectionNext(t, f, reader) - r := schedulingLatest(t, f) - if _, err := f.e.ControlOperation(t.Context(), scope, "cancel-idle", r.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}); err != nil { - t.Fatal(err) + reader := &refreshTestReader{} + readers := map[string]TargetReader{"test-capability": reader} + generate := f.e.generateAutomaticHosted + if channel == "cli" { + generate = f.e.generateAutomaticCLI + } + if idle == "paused" { + schedulingPause(t, f, 2, 0, true) + } else { + if worked, err := generate(t.Context(), readers); err != nil || !worked { + t.Fatal(worked, err) + } + if idle == "cancelled" { + selectionNext(t, f, reader) + r := schedulingLatest(t, f) + if _, err := f.e.ControlOperation(t.Context(), scope, "cancel-idle", r.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}); err != nil { + t.Fatal(err) + } + } else if idle == "held-source-not-due" { + selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + return reviewprovider.Repository{}, context.DeadlineExceeded + }}) } - } else if idle == "held-source-not-due" { - selectionNext(t, f, &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { - return reviewprovider.Repository{}, context.DeadlineExceeded - }}) } - } - beforeCalls := reader.calls.Load() - entered, release := make(chan struct{}), make(chan struct{}) - done := make(chan error, 1) - go func() { - done <- f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - if _, err := tx.ExecContext(ctx, `UPDATE projects SET name='writer held' WHERE id=?`, attemptProject); err != nil { - return err + beforeCalls := reader.calls.Load() + entered, release := make(chan struct{}), make(chan struct{}) + done := make(chan error, 1) + go func() { + done <- f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `UPDATE projects SET name='writer held' WHERE id=?`, attemptProject); err != nil { + return err + } + close(entered) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + }() + defer func() { + close(release) + if err := <-done; err != nil { + t.Error(err) } - close(entered) - select { - case <-release: - return nil - case <-ctx.Done(): - return ctx.Err() + }() + select { + case <-entered: + case <-time.After(time.Second): + t.Fatal("writer not held") + } + planned := make(chan struct{}) + go func() { + defer close(planned) + if worked, err := generate(t.Context(), readers); err != nil || worked { + t.Errorf("idle planning worked=%v: %v", worked, err) } - }) - }() - defer func() { - close(release) - if err := <-done; err != nil { - t.Error(err) + }() + // The holder acquired the sole writer slot. Wait for planning + // to finish or block while that slot is still occupied. + synctest.Wait() + select { + case <-planned: + default: + t.Fatal("idle scheduler waited for writer admission") } - }() - select { - case <-entered: - case <-time.After(time.Second): - t.Fatal("writer not held") - } - ctx, cancel := context.WithTimeout(t.Context(), 150*time.Millisecond) - defer cancel() - worked, err := generate(ctx, readers) - if err != nil || worked || ctx.Err() != nil { - t.Fatal("idle scheduler waited for writer", worked, err, ctx.Err()) - } - if reader.calls.Load() != beforeCalls { - t.Fatal("local planning contacted provider") - } + if reader.calls.Load() != beforeCalls { + t.Fatal("local planning contacted provider") + } + }) }) } } @@ -1099,9 +1146,9 @@ func TestAutomaticConcurrentProjectPlansAcceptOnce(t *testing.T) { }() } close(start) + first, second := <-results, <-results accepted := 0 - for range 2 { - r := <-results + for _, r := range []result{first, second} { if r.err != nil { t.Fatal(r.err) } @@ -1235,6 +1282,20 @@ func TestSchedulingQueuedPauseDiagnosticPrecedence(t *testing.T) { check("pull_scheduling_paused") admissionSQL(t, f, `UPDATE review_execution_config SET body_json=json_set(body_json,'$.paused',json('true')) WHERE project_id=?`, attemptProject) check("project_paused") + var originalBody string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_execution_config WHERE project_id=?`, attemptProject).Scan(&originalBody); err != nil { + t.Fatal(err) + } + for _, invalid := range []string{strings.TrimSuffix(originalBody, "}") + `,"paused":true}`, originalBody + strings.Repeat(" ", 9000)} { + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=? WHERE project_id=?`, invalid, attemptProject) + check("") + } + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=? WHERE project_id=?`, originalBody, attemptProject) + capability := f.e.capabilities["test-capability"] + delete(f.e.capabilities, "test-capability") + check("") + f.e.capabilities["test-capability"] = capability + check("project_paused") admissionSQL(t, f, `UPDATE review_operation_waits SET paused=1 WHERE operation_id=?`, r.ID) check("operation_paused") }) diff --git a/internal/reviewexec/selection_native_key_test.go b/internal/reviewexec/selection_native_key_test.go index 8301b2b94..d080cb6ca 100644 --- a/internal/reviewexec/selection_native_key_test.go +++ b/internal/reviewexec/selection_native_key_test.go @@ -1,29 +1,106 @@ package reviewexec -import "testing" +import ( + "context" + "database/sql" + "errors" + "testing" +) func TestSelectionNativeBlobKeyDoesNotStopRecovery(t *testing.T) { - for _, state := range []string{"queued", "selecting"} { - t.Run(state, func(t *testing.T) { + for _, tc := range []struct{ state, key string }{ + {"queued", "id"}, + {"selecting", "id"}, + {"selecting", "project_id"}, + } { + t.Run(tc.state+"/"+tc.key, func(t *testing.T) { f := selectionFixture(t) - r, _ := selectionEnqueue(t, f, "blob-selection", "hosted", nil) - admissionSQL(t, f, `UPDATE review_selections SET id=CAST(id AS BLOB),state=? WHERE id=?`, state, r.ID) - if state == "selecting" { + corrupt, _ := selectionEnqueue(t, f, "blob-selection", "hosted", nil) + healthy, _ := selectionEnqueue(t, f, "healthy-selection", "cli", nil) + // Queued scans order by age. Recovery orders by id, where SQLite + // sorts text before blobs. Use a malformed project key as well so + // a healthy selection can follow a malformed key in that scan. + const corruptID = "review_selection_00000000000000000000000000000000" + const healthyID = "review_selection_ffffffffffffffffffffffffffffffff" + admissionSQL(t, f, `UPDATE review_selections SET id=?,state=?,created_at=? WHERE id=?`, corruptID, tc.state, "2000-01-01T00:00:00Z", corrupt.ID) + admissionSQL(t, f, `UPDATE review_selections SET id=?,state=?,created_at=? WHERE id=?`, healthyID, tc.state, "2000-01-02T00:00:00Z", healthy.ID) + var corruptKey any = []byte(corruptID) + if tc.key == "id" { + admissionSQL(t, f, `UPDATE review_selections SET id=CAST(id AS BLOB) WHERE id=?`, corruptID) + } else { + corruptKey = corruptID + corruptSelectionProjectKey(t, f, corruptID) + } + + if tc.state == "selecting" { if err := f.e.RecoverReviewRuns(t.Context()); err != nil { t.Fatal(err) } - } else { - if _, err := f.e.runNext(t.Context(), nil); err != nil { - t.Fatal(err) + if got := selectionRead(t, f, healthyID); got.State != "queued" || got.Revision != 2 { + t.Fatalf("healthy selection was not recovered: %+v", got) } + } else if worked, err := f.e.runNext(t.Context(), nil); err != nil || !worked { + t.Fatal("malformed key did not complete an isolating worker pass", worked, err) } - var got, reason string - if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=CAST(? AS BLOB)`, r.ID).Scan(&got, &reason); err != nil { + + var state, reason string + if err := f.store.DB().QueryRow(`SELECT state,reason FROM review_selections WHERE id=?`, corruptKey).Scan(&state, &reason); err != nil { t.Fatal(err) } - if got != "held" || reason != "local_read_unavailable" { - t.Fatal(got, reason) + if state != "held" || reason != "local_read_unavailable" { + t.Fatal(state, reason) + } + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, healthyID); got.State != "selected" || got.OperationID == "" { + t.Fatalf("healthy selection did not progress: %+v", got) } }) } } + +func corruptSelectionProjectKey(t *testing.T, f *attemptFixture, id string) { + t.Helper() + conn, err := f.store.DB().Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if _, err := conn.ExecContext(t.Context(), `PRAGMA foreign_keys=OFF`); err != nil { + t.Fatal(err) + } + defer func() { + if _, err := conn.ExecContext(t.Context(), `PRAGMA foreign_keys=ON`); err != nil { + t.Error(err) + } + }() + if _, err := conn.ExecContext(t.Context(), `UPDATE review_selections SET project_id=CAST(project_id AS BLOB) WHERE id=?`, id); err != nil { + t.Fatal(err) + } +} + +func TestQueuedBlobSelectionWithChildDoesNotStopIndependentSelection(t *testing.T) { + f := selectionFixture(t) + broken, _ := selectionEnqueue(t, f, "linked-blob-selection", "hosted", nil) + healthy, _ := selectionEnqueue(t, f, "healthy-linked-blob-neighbor", "cli", nil) + child := f.enqueue(t, attemptProject, "retained-hosted-child", "hosted", 4, 1) + err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `PRAGMA ignore_check_constraints=ON`); err != nil { + return err + } + _, corruptErr := tx.ExecContext(ctx, `UPDATE review_selections + SET id=CAST(id AS BLOB),operation_id=?,created_at='2000-01-01T00:00:00Z' WHERE id=?`, child.ID, broken.ID) + _, resetErr := tx.ExecContext(ctx, `PRAGMA ignore_check_constraints=OFF`) + return errors.Join(corruptErr, resetErr) + }) + if err != nil { + t.Fatal(err) + } + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, healthy.ID); got.State != "selected" || got.OperationID == "" { + t.Fatalf("independent selection did not progress: %+v", got) + } + var state, linkedID string + if err := f.store.DB().QueryRowContext(t.Context(), `SELECT state,operation_id FROM review_selections WHERE id=?`, []byte(broken.ID)).Scan(&state, &linkedID); err != nil || state != "queued" || linkedID != child.ID { + t.Fatalf("unproved custody was rewritten: %q %q %v", state, linkedID, err) + } +} diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index a5f1237e6..1a53544dc 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -334,6 +334,9 @@ func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchL if err != nil { var preflight *queuePriorityPreflight if errors.As(err, &preflight) && preflight.repositoryID > 0 { + if e.independentProbeDeferred(o) { + return Operation{}, nil + } o.independentPreflight = preflight return o, nil } @@ -549,7 +552,7 @@ func preparationReason(err error) string { } 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 diff --git a/internal/reviewexec/types.go b/internal/reviewexec/types.go index 4a054733b..744025622 100644 --- a/internal/reviewexec/types.go +++ b/internal/reviewexec/types.go @@ -128,6 +128,7 @@ type Engine struct { independentProbeMu sync.Mutex independentProbeActive bool independentProbeLast time.Time + independentProbeNext map[independentProbeKey]time.Time draftProbeMu sync.Mutex draftProbeNext map[string]time.Time draftProbeCursor string diff --git a/internal/reviewexec/wait_deadline.go b/internal/reviewexec/wait_deadline.go index 80ce7e667..f5ae166b7 100644 --- a/internal/reviewexec/wait_deadline.go +++ b/internal/reviewexec/wait_deadline.go @@ -135,7 +135,7 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba return err } defer rows.Close() - var cancelled, scheduling []string + var cancelled, detachedHolds []string var first string var earliest time.Time tied := false @@ -153,11 +153,9 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba if !state.Valid || !retainedReason.Valid || state.String != "held" || attemptState != "held" { return waitUnavailable() } - if retainedReason.String == "pull_scheduling_paused" || retainedReason.String == "automation_authorization_changed" || retainedReason.String == "automatic_scheduling_unavailable" { - scheduling = append(scheduling, id) - continue - } - 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 { @@ -177,9 +175,10 @@ func validateFirstCooldown(ctx context.Context, q EvidenceQuery, o Operation, ba return err } rows.Close() - // Scheduling guards detach unused preparations without becoming quota - // baselines. Reuse the same strict journal proof as snapshot validation. - for _, id := range scheduling { + // 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) From 8a619e45fef3a090fe892d71c68caf8cd2ee68ff Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 00:47:31 +1300 Subject: [PATCH 32/41] Preserve scheduler origin and isolate candidate prefixes --- docs/review-scheduling.md | 6 +- internal/core/mutation.go | 8 +- internal/reviewexec/run_selection.go | 17 +- internal/reviewexec/run_selection_origin.go | 217 +++++++++++++++++ internal/reviewexec/run_selection_snapshot.go | 24 ++ internal/reviewexec/run_selection_worker.go | 35 ++- internal/reviewexec/scheduling_automatic.go | 143 ++++++----- .../reviewexec/scheduling_cli_priority.go | 17 ++ .../scheduling_origin_prefix_test.go | 224 ++++++++++++++++++ .../reviewexec/selection_native_key_test.go | 4 +- 10 files changed, 620 insertions(+), 75 deletions(-) create mode 100644 internal/reviewexec/run_selection_origin.go create mode 100644 internal/reviewexec/scheduling_origin_prefix_test.go diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index a3f48e22e..b22453dfc 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -8,11 +8,11 @@ Projects can independently opt in to automatic new Hosted or CLI requests. Both ## Automatic Hosted requests -A project manager enables scheduling through the HTTP API; bound CLI and MCP delivery follows in the dependent client slice. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. The HTTP contract also permits an authorized browser manager to explicitly select the authorizing worker while retaining the human session identity. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected queued intent may continue after an A-to-B-to-A authorizer sequence when the current authorizer again matches its original authorizer and complete history proves its channel stayed enabled throughout. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. +A project manager enables scheduling through the HTTP API; bound CLI and MCP delivery follows in the dependent client slice. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. The HTTP contract also permits an authorized browser manager to explicitly select the authorizing worker while retaining the human session identity. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected queued intent may continue after an A-to-B-to-A authorizer sequence when the current authorizer again matches its original authorizer and complete history proves its channel stayed enabled throughout. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. The acceptance event records whether a new selection is explicit or automatic. Automatic selections and their children require matching retained scheduling attribution before selection, recovery or dispatch. Missing or conflicting attribution holds those requests. For older selections, a caller-supplied PR pin, an exact retained explicit mutation receipt, or complete retained history showing acceptance before automatic scheduling for that channel can establish explicit origin. An ambiguous legacy selection stays held. Current explicit authorization still applies. The scheduler uses the existing configured queue and ordinary durable selection/operation path. It checks eligible work at most once per five-second coordinator interval; this is not a promised start time or another GitHub polling loop. Source, dependency, publication, findings, routes, imported obligations, round limits, taper and provider guards still apply. Independent PRs can proceed while another awaits fixes; real dependencies retain predecessor guards. Retained scheduling validation failures prevent planning for the affected project; malformed shared scheduling state or unavailable shared authorization can affect both channels. Channel-front and source-retry selection validation failures, a retained parent cycle, or a planning basis above its row limit remain local to the affected project and channel. Independent projects continue, and channel-specific failures do not block the other channel. The execution supervisor skips these typed project-local refusals, and a damaged competing priority candidate cannot block a healthy project’s account claim. A deterministic basis refusal during selection settlement rolls back source and child writes and holds the original selection as `automatic_scheduling_unavailable`; it is not transient contention and does not enter the writer retry loop. The accepted basis remains available for duplicate suppression across ticks and restart. Startup validates the shared front-cache table definition without scanning optional cache rows. Damaged rows remain isolated by project/channel readers; backup and restore still validate the complete retained snapshot. Shared storage and transaction failures remain errors rather than being suppressed; arbitrary SQL failures are not classified as project-local corruption. Automatic requests never inherit out-of-order or file-limit overrides. Each project first plans in a bounded read-only snapshot. Only a candidate for a new intent or a due retained source retry enters the writer, which repeats authorization, configuration, policy, pause, busy and basis checks before ordinary atomic acceptance or retry. A changed plan waits for a later pass. -Meaningful source, review or control changes can create another automatic intent. A waiting later PR does not prevent reconsideration of an earlier PR that becomes eligible; the earlier request can take priority while the later request retains its identity and cooldown. Existing queued work on a PR prevents a duplicate intent for that PR, and active provider work is not interrupted. Timer-backed requests retain their original operation and retry deadline. Ticks, restarts, observation timestamps and failed/cancelled operation transitions cannot recreate the same request. A clean CLI completion alone cannot restart a cancelled Hosted request. A dependent PR can become eligible when its actual predecessor completes at the same head. Cancellation stops that intent; use a PR pause to hold new reviews persistently. A setting change affecting only the other channel preserves this channel’s intent basis. Changing this channel’s setting or the authorizing principal, worker or credential changes its basis. Explicitly reasserting unchanged settings rearms only the supplied channels; an omitted CLI setting preserves its basis. The current scheduling event retains each channel’s basis revision independently of the shared authorization revision. Older events use their existing shared revision without rewriting any stored digests, so an upgrade alone cannot recreate cancelled work. +Meaningful source, review or control changes can create another automatic intent. A waiting later PR does not prevent reconsideration of an earlier PR that becomes eligible; the earlier request can take priority while the later request retains its identity and cooldown. Existing queued work on a PR prevents a duplicate intent for that PR, and active provider work is not interrupted. Timer-backed requests retain their original operation and retry deadline. Ticks, restarts, observation timestamps and failed/cancelled operation transitions cannot recreate the same request. A clean CLI completion alone cannot restart a cancelled Hosted request. A dependent PR can become eligible when its actual predecessor completes at the same head. Cancellation stops that intent; use a PR pause to hold new reviews persistently. Planning and settlement use semantic facts from the eligible queue prefix. A waiting request fences off later siblings and their local basis checks. A candidate still requires proof of any source-owned dependency. The full-queue digest and selected PR digests retain their original format. Older pre-child holds have only opaque full-queue digests. While a waiting request shortens the queue, an older hold with the same execution configuration, policy and channel basis can prevent accepting an unproved replacement. The scheduler can compare the original digest once the full queue is eligible. Explicitly rearming that channel changes its basis and permits fresh selection under the normal guards. A setting change affecting only the other channel preserves this channel’s intent basis. Changing this channel’s setting or the authorizing principal, worker or credential changes its basis. Explicitly reasserting unchanged settings rearms only the supplied channels; an omitted CLI setting preserves its basis. The current scheduling event retains each channel’s basis revision independently of the shared authorization revision. Older events use their existing shared revision without rewriting any stored digests, so an upgrade alone cannot recreate cancelled work. A pre-child automatic Hosted or CLI selection held only by `source_budget_exhausted`, `source_fetch_timeout` or `source_provider_unavailable` can retry its source selection after at least thirty seconds. It reuses the original selection and accepted configuration, policy, capability and authorizer, with the exact scheduling revision still current. At most two such delayed retries are permitted by a conservative durable transition budget; interrupted-selection recovery consumes that budget rather than resetting it. Existing recovery of an interrupted read remains separate from this bound on completed source holds. Restart and backup restore retain the budget and last-transition time. Restore/provider holds still prevent work. @@ -66,7 +66,7 @@ MCP equivalents are `review_scheduling_read`, `review_scheduling_configure`, `re `GET`/`POST /api/v1/projects/{project_id}/reviews/scheduling` read/configure project scheduling. The write body is `{expected_revision, automatic_hosted, automatic_cli?}` and requires project management. `GET`/`POST /api/v1/projects/{project_id}/reviews/pulls/{number}/scheduling` read/update a PR pause. The write body is `{expected_revision, paused, reason?}` and requires project write access. Writes require the normal explicit idempotency key. Unconfigured records read as revision zero and off/unpaused; writes return a new revision. Project reads report unavailable authorization or provider holds without exposing credential identifiers or tokens. -Backups retain scheduling, PR pauses and automatic-intent attribution. Older bundles without this optional domain remain off; version-one Hosted-only records migrate with automatic CLI off. Restore remains inactive with provider execution held. Historical authorizers remain valid historical evidence after revocation or retirement. A legacy bundle may omit the PR control if its unique latest canonical event records an unpaused resume. Offline restore preserves that event’s actor, timestamp and revision in the inactive destination control, without changing the source bundle, event journal or authorization. A missing paused control or unresolved history remains invalid; a PR with no retained control history still reads at revision zero. +Backups retain scheduling, PR pauses, selection acceptance events and automatic-intent attribution. Inspection rejects a recorded automatic origin whose attribution is missing or mismatched. Older bundles without this optional domain remain off; version-one Hosted-only records migrate with automatic CLI off. Restore remains inactive with provider execution held. Historical authorizers remain valid historical evidence after revocation or retirement. A legacy bundle may omit the PR control if its unique latest canonical event records an unpaused resume. Offline restore preserves that event’s actor, timestamp and revision in the inactive destination control, without changing the source bundle, event journal or authorization. A missing paused control or unresolved history remains invalid; a PR with no retained control history still reads at revision zero. A proved linked selection custody hold retains its original child identifier and observed revision in a private versioned diagnostic record. It never changes the child, authorizer, retained evidence, or the existing provider action. Active capacity remains attributed as before; a demonstrably held child cannot obtain new admission or reserve an ordinary queued turn. Unproved or ambiguous provenance cannot establish eligibility and remains fail-closed. 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/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 98b50519b..c8c8f2b0b 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -16,6 +16,7 @@ type RunRequest struct { Channel string `json:"channel"` ExpectedPullNumber *int64 `json:"expected_pull_number,omitempty"` ExpectedConfigurationRevision *int64 `json:"expected_configuration_revision,omitempty"` + origin string } type Run struct { ID string `json:"id"` @@ -117,6 +118,7 @@ func (e *Engine) EnqueueRun(ctx context.Context, scope core.Scope, key string, i v := *input.ExpectedConfigurationRevision input.ExpectedConfigurationRevision = &v } + input.origin = selectionOriginExplicit out, err := e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.run", Target: "channel-selection", Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { return e.enqueueRunTx(ctx, tx, scope, input) }) @@ -187,7 +189,7 @@ 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 @@ -342,7 +344,18 @@ func (e *Engine) RecoverReviewRuns(ctx context.Context) error { 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) diff --git a/internal/reviewexec/run_selection_origin.go b/internal/reviewexec/run_selection_origin.go new file mode 100644 index 000000000..4f3d6bf73 --- /dev/null +++ b/internal/reviewexec/run_selection_origin.go @@ -0,0 +1,217 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/strictjson" +) + +const ( + selectionOriginExplicit = "explicit" + selectionOriginAutomatic = "automatic" +) + +type selectionRequestedEvent struct { + Channel string `json:"channel"` + Origin string `json:"origin,omitempty"` + WorkerID string `json:"worker_id,omitempty"` + sequence int64 +} + +func readSelectionRequestedEvent(ctx context.Context, q EvidenceQuery, r Run) (selectionRequestedEvent, error) { + rows, err := q.QueryContext(ctx, `SELECT sequence,actor_id, + CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END + FROM events WHERE project_id=? AND event_type='review.selection_requested' AND resource_id=? AND revision=1 LIMIT 2`, r.ProjectID, r.ID) + if err != nil { + return selectionRequestedEvent{}, err + } + defer rows.Close() + if !rows.Next() { + return selectionRequestedEvent{}, rows.Err() + } + var actor any + var sequence int64 + var body sql.NullString + if err = rows.Scan(&sequence, &actor, &body); err != nil { + return selectionRequestedEvent{}, err + } + var event selectionRequestedEvent + if sequence < 1 || actor != r.ActorID || !body.Valid || strictjson.Decode([]byte(body.String), &event) != nil || event.Channel != r.Channel || body.String != encoded(event) { + return selectionRequestedEvent{}, schedulingUnavailable() + } + switch event.Origin { + case "": + if event.WorkerID != "" { + return selectionRequestedEvent{}, schedulingUnavailable() + } + case selectionOriginExplicit, selectionOriginAutomatic: + if event.WorkerID != r.WorkerID { + return selectionRequestedEvent{}, schedulingUnavailable() + } + default: + return selectionRequestedEvent{}, schedulingUnavailable() + } + if rows.Next() { + return selectionRequestedEvent{}, schedulingUnavailable() + } + event.sequence = sequence + return event, rows.Err() +} + +type automaticSelectionAttribution struct { + revision int64 + credential string +} + +func readAutomaticSelectionAttribution(ctx context.Context, q EvidenceQuery, r Run) (automaticSelectionAttribution, error) { + var attribution automaticSelectionAttribution + var project, revision, actor, worker, credential any + // Read by the unique selection ID so a wrongly scoped row cannot masquerade + // as missing attribution for an otherwise valid selection. + err := q.QueryRowContext(ctx, `SELECT project_id,scheduling_revision,actor_id,worker_id,credential_id + FROM review_automatic_selections WHERE selection_id=?`, r.ID).Scan(&project, &revision, &actor, &worker, &credential) + if err != nil { + return attribution, err + } + nativeRevision, validRevision := revision.(int64) + credentialID, validCredential := credential.(string) + if project != r.ProjectID || actor != r.ActorID || worker != r.WorkerID || !validRevision || nativeRevision < 1 || !validCredential || !identifier.MatchString(credentialID) { + return attribution, schedulingUnavailable() + } + return automaticSelectionAttribution{revision: nativeRevision, credential: credentialID}, nil +} + +func automaticSelectionBinding(ctx context.Context, tx *sql.Tx, r Run) (automaticSelectionAttribution, error) { + event, err := readSelectionRequestedEvent(ctx, tx, r) + if err != nil { + return automaticSelectionAttribution{}, err + } + attribution, err := readAutomaticSelectionAttribution(ctx, tx, r) + if !errors.Is(err, sql.ErrNoRows) && err != nil { + return automaticSelectionAttribution{}, err + } + hasAttribution := err == nil + switch event.Origin { + case selectionOriginAutomatic: + if !hasAttribution || r.ExpectedPullNumber != 0 { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + case selectionOriginExplicit: + if hasAttribution { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + default: + // The automatic scheduler never accepts a caller-supplied PR pin. + if r.ExpectedPullNumber != 0 { + if hasAttribution { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + return attribution, nil + } + if !hasAttribution { + explicit, err := legacyExplicitSelection(ctx, tx, r) + if err != nil { + return automaticSelectionAttribution{}, err + } + if !explicit && event.sequence != 0 { + explicit, err = selectionPredatesAutomation(ctx, tx, r, event.sequence) + if err != nil { + return automaticSelectionAttribution{}, err + } + } + if !explicit { + return automaticSelectionAttribution{}, schedulingUnavailable() + } + } + } + return attribution, nil +} + +// Explicit accepts wrote a canonical mutation receipt in the same transaction. +// Only a positive match proves legacy explicit origin; normal current +// authorization is still independently required to admit the retained work. +func legacyExplicitSelection(ctx context.Context, q EvidenceQuery, r Run) (bool, error) { + var hasHistory bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='restore_history')`).Scan(&hasHistory); err != nil { + return false, err + } + origins := `SELECT value FROM metadata WHERE key IN ('instance_id','restore:source_instance_id')` + if hasHistory { + // Startup validates the connected recovery provenance of this table. + origins += ` UNION SELECT instance_id FROM restore_history + UNION SELECT CASE WHEN json_valid(body_json) THEN json_extract(body_json,'$."restore:source_instance_id"') END FROM restore_history` + } + fingerprint, err := core.MutationRequestFingerprint(RunRequest{Channel: r.Channel}, r.WorkerID) + if err != nil { + return false, err + } + pinnedFingerprint, err := core.MutationRequestFingerprint(RunRequest{Channel: r.Channel, ExpectedConfigurationRevision: &r.ConfigurationRevision}, r.WorkerID) + if err != nil { + return false, err + } + response := encoded(Receipt{ID: r.ID, State: "queued", Revision: 1}) + var explicit bool + err = q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM receipts + WHERE instance_id IN (`+origins+`) AND principal_id=? AND project_id=? AND operation='reviews.run' + AND target='channel-selection' AND fingerprint IN (?,?) AND response_json=?)`, + r.ActorID, r.ProjectID, fingerprint, pinnedFingerprint, response).Scan(&explicit) + return explicit, err +} + +func selectionLocalHoldReason(ctx context.Context, q EvidenceQuery, r Run) (string, error) { + event, err := readSelectionRequestedEvent(ctx, q, r) + if err != nil && !automaticProjectRefused(err) { + return "", err + } + var attributionPresent bool + if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=?)`, r.ID).Scan(&attributionPresent); err != nil { + return "", err + } + if event.Origin == selectionOriginAutomatic || attributionPresent { + return "automatic_scheduling_unavailable", nil + } + return "local_read_unavailable", nil +} + +// An accepted event preceding every enabled revision of its channel is another +// positive distinction for older explicit requests with no exact receipt. +func selectionPredatesAutomation(ctx context.Context, tx *sql.Tx, r Run, acceptedSequence int64) (bool, error) { + projected, err := readScheduling(ctx, tx, r.ProjectID) + if err != nil || projected.Revision > 10000 { + return false, err + } + rows, err := tx.QueryContext(ctx, `SELECT sequence,revision, + CASE WHEN typeof(payload_json)='text' AND length(CAST(payload_json AS BLOB))<=4096 THEN payload_json END + FROM events WHERE project_id=? AND resource_id=? AND event_type='review.scheduling_updated' + ORDER BY sequence LIMIT 10001`, r.ProjectID, r.ProjectID) + if err != nil { + return false, err + } + defer rows.Close() + var expected int64 = 1 + for rows.Next() { + var sequence int64 + var revision any + var body sql.NullString + if err := rows.Scan(&sequence, &revision, &body); err != nil { + return false, err + } + var control schedulingEvent + if revision != expected || !body.Valid || strictjson.Decode([]byte(body.String), &control) != nil || control.Hosted == nil { + return false, nil + } + enabled := control.Hosted + if r.Channel == "cli" { + enabled = control.CLI + } + channelEnabled := enabled != nil && *enabled + if sequence < acceptedSequence && channelEnabled || expected == projected.Revision && channelEnabled != automaticChannelEnabled(projected, r.Channel) { + return false, nil + } + expected++ + } + return expected == projected.Revision+1, rows.Err() +} diff --git a/internal/reviewexec/run_selection_snapshot.go b/internal/reviewexec/run_selection_snapshot.go index 491da2f49..c7ccfcadd 100644 --- a/internal/reviewexec/run_selection_snapshot.go +++ b/internal/reviewexec/run_selection_snapshot.go @@ -2,6 +2,8 @@ package reviewexec import ( "context" + "database/sql" + "errors" "fmt" "math" "slices" @@ -21,6 +23,10 @@ func ValidateSelectionSnapshot(ctx context.Context, q EvidenceQuery) error { 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 { @@ -63,6 +69,24 @@ func ValidateSelectionSnapshot(ctx context.Context, q EvidenceQuery) error { if err != nil { return err } + + event, err := readSelectionRequestedEvent(ctx, q, r) + if err != nil { + return err + } + if event.Origin != "" { + attributed := false + if hasScheduling { + _, err := readAutomaticSelectionAttribution(ctx, q, r) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + attributed = err == nil + } + if (event.Origin == selectionOriginAutomatic) != attributed || attributed && r.ExpectedPullNumber != 0 { + return schedulingUnavailable() + } + } var configurationBody, policyBody string if err = q.QueryRowContext(ctx, `SELECT CASE WHEN typeof(body_json)='text' AND length(CAST(body_json AS BLOB))<=16384 THEN body_json END FROM review_execution_config WHERE project_id=? AND revision=?`, r.ProjectID, r.ConfigurationRevision).Scan(&configurationBody); err != nil { return runUnavailable() diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index fd25f98ca..8f0136fa9 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -233,13 +233,14 @@ func (e *Engine) chooseRunWithSourceBudget(ctx context.Context, r Run, repo int6 // An expired snapshot must not shorten a later retry's input. limit, automatic, basisRevision = len(c.Queue), false, 0 return e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=? AND project_id=?)`, r.ID, r.ProjectID).Scan(&automatic); err != nil { + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil { return err } + automatic = attribution.revision != 0 if !automatic { return nil } - var err error limit, err = e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) if err != nil { return err @@ -556,7 +557,19 @@ func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) ( return updateRun(ctx, tx, r, "held", reason, "") } if e.publishAttempt != nil { - metadataPins, err = reviews.PinSourceMetadata(ctx, tx, r.ProjectID, configuration.Queue) + queue := configuration.Queue + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil { + return err + } + if attribution.revision != 0 { + limit, err := e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, configuration, r.Channel) + if err != nil { + return err + } + queue = queue[:limit] + } + metadataPins, err = reviews.PinSourceMetadata(ctx, tx, r.ProjectID, queue) if err != nil { return err } @@ -621,14 +634,10 @@ func (e *Engine) holdRunLocalRefusal(ctx context.Context, expected Run) (bool, e if current.State != expected.State || current.Revision != expected.Revision { return nil } - var automatic bool - if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id=?)`, current.ProjectID, current.ID).Scan(&automatic); err != nil { + reason, err := selectionLocalHoldReason(ctx, tx, current) + if err != nil { return err } - reason := "local_read_unavailable" - if automatic { - reason = "automatic_scheduling_unavailable" - } if err = updateRun(ctx, tx, current, "held", reason, ""); err != nil { return err } @@ -678,12 +687,12 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } } if automaticProjectRefused(resultErr) { - var automatic bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=? AND project_id=?)`, r.ID, r.ProjectID).Scan(&automatic); err != nil { + reason, err := selectionLocalHoldReason(ctx, tx, current) + if err != nil { resultErr = err return } - if !automatic { + if reason != "automatic_scheduling_unavailable" { return // Explicit selections retain their original error and rollback. } // Settlement is part of atomic selection. Discard any source, @@ -693,7 +702,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat resultErr = err return } - resultErr = updateRun(ctx, tx, current, "held", "automatic_scheduling_unavailable", "") + resultErr = updateRun(ctx, tx, current, "held", reason, "") } if resultErr == nil { _, resultErr = tx.ExecContext(ctx, `RELEASE review_selection_finish`) diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 11b8b544c..87a71bd90 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -39,25 +39,17 @@ func automaticDenied() error { return core.Fail("automation_authorization_changed", "Automatic review scheduling is disabled or its original authorizer is no longer authorized.", 403) } func (e *Engine) requireAutomaticRun(ctx context.Context, tx *sql.Tx, r Run) error { - var retainedRevision any - var actor, worker, credential string - err := tx.QueryRowContext(ctx, `SELECT scheduling_revision,actor_id,worker_id,credential_id FROM review_automatic_selections WHERE project_id=? AND selection_id=?`, r.ProjectID, r.ID).Scan(&retainedRevision, &actor, &worker, &credential) - if errors.Is(err, sql.ErrNoRows) { - return nil - } - if err != nil { + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil || attribution.revision == 0 { return err } - // Preserve query failures while classifying malformed retained SQLite values. - revision, validRevision := retainedRevision.(int64) - if !validRevision || revision < 1 { - return schedulingUnavailable() - } + 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) || r.ActorID != actor || r.WorkerID != worker || !validChannel(r.Channel) { + if revision > s.Revision || !automaticChannelEnabled(s, r.Channel) || !validChannel(r.Channel) { return automaticDenied() } if s.actor != actor || s.AuthorizingWorkerID != worker || s.credential != credential { @@ -95,15 +87,19 @@ func (e *Engine) requireAutomaticOperation(ctx context.Context, tx *sql.Tx, o Op if err := requireUnquarantinedSelectionLink(ctx, tx, o.ProjectID, o.ID); err != nil { return err } - var selection string - err := tx.QueryRowContext(ctx, `SELECT s.id FROM review_selections s JOIN review_automatic_selections a ON a.selection_id=s.id AND a.project_id=s.project_id WHERE s.project_id=? AND s.operation_id=?`, o.ProjectID, o.ID).Scan(&selection) + var project, selection any + err := tx.QueryRowContext(ctx, `SELECT project_id,id FROM review_selections WHERE operation_id=?`, o.ID).Scan(&project, &selection) if errors.Is(err, sql.ErrNoRows) { return nil } if err != nil { return err } - r, err := readRun(ctx, tx, o.ProjectID, selection) + id, validID := selection.(string) + if project != o.ProjectID || !validID || !validRunID(id) { + return schedulingUnavailable() + } + r, err := readRun(ctx, tx, o.ProjectID, id) if err != nil { return err } @@ -397,24 +393,26 @@ func (e *Engine) automaticPlanningBasisChannel(ctx context.Context, tx *sql.Tx, 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(c.Queue) > 0 { + 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(c.Queue)) + values := make([]any, 0, len(queue)) remaining := []int64{} - for position, pull := range c.Queue { + for _, pull := range queue { basis, err := automaticPullBasisWithRead(ctx, tx, project, pull, channel, shared) if err != nil { return "", false, err } values = append(values, []any{pull, basis}) - if position >= limit { - continue - } p, err := readPullScheduling(ctx, tx, project, pull) if err != nil { return "", false, err @@ -441,6 +439,31 @@ func (e *Engine) automaticPlanningBasisChannel(ctx context.Context, tx *sql.Tx, return hex.EncodeToString(sum[:]), len(remaining) > 0, nil } +// Legacy pre-child intents have only an opaque whole-queue digest. At a +// shortened cutoff there is no proof that a new prefix digest falls outside +// the retained intent. Keep that scope held until an explicit rearm changes +// the channel basis, a configuration/policy revision changes, or the full +// queue becomes eligible for the original exact-digest comparison. +func automaticLegacyPrefixFence(ctx context.Context, tx *sql.Tx, project string, configurationRevision, policyRevision int64, channel string) (bool, error) { + basisRevision, err := automaticChannelBasisRevision(ctx, tx, project, channel) + if err != nil { + return false, err + } + var held 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 s.configuration_revision=? AND s.policy_revision=? + AND a.scheduling_revision>=? AND a.pull_number=0 AND s.operation_id IS NULL AND s.state IN ('held','empty') + 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 AND e.actor_id=s.actor_id + AND e.payload_json=json_object('channel',s.channel,'origin','automatic','worker_id',s.worker_id) + ) + )`, project, channel, configurationRevision, policyRevision, basisRevision).Scan(&held) + return held, err +} + // 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. @@ -453,10 +476,9 @@ func (e *Engine) automaticHostedQueuedPrefixChannel(ctx context.Context, tx *sql if err != nil { return 0, err } - rows, err := tx.QueryContext(ctx, `SELECT q.key,a.selection_id,o.id,EXISTS(SELECT 1 FROM review_selection_quarantine d WHERE d.project_id=o.project_id AND d.original_operation_id=o.id) FROM review_operations o + rows, err := tx.QueryContext(ctx, `SELECT q.key,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.project_id=o.project_id AND s.operation_id=o.id -LEFT JOIN review_automatic_selections a ON a.project_id=s.project_id AND a.selection_id=s.id +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) @@ -471,10 +493,10 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) return 0, schedulingUnavailable() } var position int - var selection sql.NullString + var selection, selectionProject any var operation string var custodyPresent bool - if err := rows.Scan(&position, &selection, &operation, &custodyPresent); err != nil { + if err := rows.Scan(&position, &selection, &selectionProject, &operation, &custodyPresent); err != nil { return 0, err } if custodyPresent { @@ -486,11 +508,15 @@ ORDER BY q.key,o.id LIMIT 101`, string(queue), project, channel) } return 0, runUnavailable() } - // Explicit work has no automatic binding and keeps its position. - if !selection.Valid { + // A direct operation has no parent selection and keeps its position. + if selection == nil { return position, nil } - r, err := readRun(ctx, tx, project, selection.String) + id, validID := selection.(string) + if selectionProject != project || !validID || !validRunID(id) { + return 0, schedulingUnavailable() + } + r, err := readRun(ctx, tx, project, id) if err != nil { return 0, err } @@ -522,13 +548,14 @@ func automaticHostedPendingPullChannel(ctx context.Context, tx *sql.Tx, project } func (e *Engine) automaticPullSuppressed(ctx context.Context, tx *sql.Tx, r Run, pull int64) (bool, error) { - var automatic bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=? AND project_id=?)`, r.ID, r.ProjectID).Scan(&automatic); err != nil { - return false, err - } - if !automatic { + // 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 @@ -553,13 +580,10 @@ func (e *Engine) automaticPullSuppressed(ctx context.Context, tx *sql.Tx, r Run, return seen, err } func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64) error { - var automatic bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE selection_id=? AND project_id=?)`, r.ID, r.ProjectID).Scan(&automatic); err != nil { + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil || attribution.revision == 0 { return err } - if !automatic { - return nil - } c, _, err := readConfiguration(ctx, tx, r.ProjectID) if err != nil { return err @@ -682,7 +706,7 @@ func (e *Engine) planAutomaticProject(ctx context.Context, tx *sql.Tx, project, } return nil, err } - c, _, err := readConfiguration(ctx, tx, project) + c, configurationRevision, err := readConfiguration(ctx, tx, project) if err != nil { var failure *core.Error if errors.As(err, &failure) && failure.Code == "reviews_unconfigured" { @@ -693,17 +717,6 @@ func (e *Engine) planAutomaticProject(ctx context.Context, tx *sql.Tx, project, if c.Paused || !slices.Contains(c.Channels, channel) || e.validateConfiguration(c) != nil || readers[c.CapabilityID] == nil || len(c.Queue) == 0 { return nil, nil } - unpaused := false - for _, pull := range c.Queue { - p, err := readPullScheduling(ctx, tx, project, pull) - if err != nil { - return nil, err - } - unpaused = unpaused || !p.Paused - } - if !unpaused { - return nil, nil - } policy, err := readPolicy(ctx, tx, project) if err != nil { var failure *core.Error @@ -722,7 +735,23 @@ func (e *Engine) planAutomaticProject(ctx context.Context, tx *sql.Tx, project, if busy { return nil, nil } - basis, candidates, err := e.automaticPlanningBasisChannel(ctx, tx, project, c, "", channel) + limit, err := e.automaticHostedQueuedPrefixChannel(ctx, tx, project, c, channel) + if err != nil || limit == 0 { + return nil, err + } + queue := c.Queue[:limit] + unpaused := false + for _, pull := range queue { + control, err := readPullScheduling(ctx, tx, project, pull) + if err != nil { + return nil, err + } + unpaused = unpaused || !control.Paused + } + if !unpaused { + return nil, nil + } + basis, candidates, err := automaticPlanningBasisForPrefix(ctx, tx, project, queue, "", channel) if err != nil || !candidates { return nil, err } @@ -737,6 +766,12 @@ func (e *Engine) planAutomaticProject(ctx context.Context, tx *sql.Tx, project, return nil, err } } + if !seen && limit < len(c.Queue) { + held, err := automaticLegacyPrefixFence(ctx, tx, project, configurationRevision, policy.Revision, channel) + if err != nil || held { + return nil, err + } + } return plan, nil } @@ -787,7 +822,7 @@ func (e *Engine) acceptAutomaticProjectWithEnqueue(ctx context.Context, project, err = updateRunAt(ctx, tx, *current.retry, "queued", "", "", time.Now()) } else { // Same ordinary acceptance path, fully reauthorized in this snapshot. - receipt, enqueueErr := enqueue(ctx, tx, current.scope, RunRequest{Channel: channel}) + receipt, enqueueErr := enqueue(ctx, tx, current.scope, RunRequest{Channel: channel, origin: selectionOriginAutomatic}) if enqueueErr != nil { var failure *core.Error if errors.As(enqueueErr, &failure) && failure.Status == 409 { diff --git a/internal/reviewexec/scheduling_cli_priority.go b/internal/reviewexec/scheduling_cli_priority.go index 8780670bd..b5f31c759 100644 --- a/internal/reviewexec/scheduling_cli_priority.go +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -138,6 +138,23 @@ candidates: continue } queue := c.Queue + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil { + if automaticProjectRefused(err) { + continue candidates + } + return false, err + } + if attribution.revision != 0 { + limit, err := e.automaticHostedQueuedPrefixChannel(ctx, tx, r.ProjectID, c, r.Channel) + if err != nil { + if automaticProjectRefused(err) { + continue candidates + } + return false, err + } + queue = queue[:limit] + } if r.ExpectedPullNumber != 0 { if !slices.Contains(queue, r.ExpectedPullNumber) { continue diff --git a/internal/reviewexec/scheduling_origin_prefix_test.go b/internal/reviewexec/scheduling_origin_prefix_test.go new file mode 100644 index 000000000..06425f5df --- /dev/null +++ b/internal/reviewexec/scheduling_origin_prefix_test.go @@ -0,0 +1,224 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestAutomaticSelectionOriginSurvivesMissingAttribution(t *testing.T) { + for _, state := range []string{"queued", "selecting", "selected"} { + t.Run(state, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + run := schedulingLatest(t, f) + reader := &refreshTestReader{} + switch state { + case "selecting": + admissionSQL(t, f, `UPDATE review_selections SET state='selecting',revision=2 WHERE id=?`, run.ID) + case "selected": + selectionNext(t, f, reader) + run = selectionRead(t, f, run.ID) + } + admissionSQL(t, f, `DELETE FROM review_automatic_selections WHERE selection_id=?`, run.ID) + schedulingEnable(t, f, 1, false) + err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + return ValidateSelectionSnapshot(ctx, tx) + }) + if !automaticProjectRefused(err) { + t.Fatal("snapshot accepted automatic selection without attribution", err) + } + switch state { + case "queued": + selectionNext(t, f, reader) + case "selecting": + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + case "selected": + err := f.e.readAdmission(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + op, err := readOperation(ctx, tx, attemptProject, run.OperationID) + if err != nil { + return err + } + return f.e.requireAutomaticOperation(ctx, tx, op) + }) + if !automaticProjectRefused(err) { + t.Fatal("automatic child inherited explicit admission", err) + } + return + } + if got := selectionRead(t, f, run.ID); got.State != "held" || got.Reason != "automatic_scheduling_unavailable" || got.OperationID != "" || reader.calls.Load() != 0 { + t.Fatal("missing attribution reached source or failed to hold", got) + } + }) + } +} + +func TestExplicitSelectionOriginRemainsUsableWithoutReceipt(t *testing.T) { + for _, mode := range []string{"marked", "legacy-pre-enable", "legacy-pinned", "legacy-exact-receipt"} { + t.Run(mode, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + if mode != "legacy-pre-enable" { + schedulingEnable(t, f, 0, true) + } + var expected *int64 + if mode == "legacy-pinned" { + number := int64(2) + expected = &number + } + run, _ := selectionEnqueue(t, f, mode, "hosted", expected) + if mode != "marked" { + admissionSQL(t, f, `UPDATE events SET payload_json='{"channel":"hosted"}' WHERE resource_id=? AND event_type='review.selection_requested'`, run.ID) + } + if mode != "legacy-exact-receipt" { + admissionSQL(t, f, `DELETE FROM receipts WHERE operation='reviews.run' AND key=?`, mode) + } + if mode == "legacy-pre-enable" { + schedulingEnable(t, f, 0, true) + } + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, run.ID); got.State != "selected" || got.OperationID == "" { + t.Fatal("proved explicit selection failed to progress", got) + } + }) + } +} + +func TestAutomaticPlanningIgnoresSemanticFaultBeyondQueuedCutoff(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, held := range []bool{false, true} { + name := channel + "/selected" + if held { + name = channel + "/held" + } + t.Run(name, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4, 6}) + f.enqueue(t, attemptProject, "cutoff-queued", channel, 4, 1) + // The ordinary retained route reader is unaffected on PR 2. At + // PR 6 this fixture exceeds the semantic basis row bound. + admissionSQL(t, f, `ALTER TABLE review_finding_routes RENAME TO saved_finding_routes`) + admissionSQL(t, f, `CREATE TABLE review_finding_routes AS SELECT * FROM saved_finding_routes`) + admissionSQL(t, f, `WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10001) + INSERT INTO review_finding_routes(project_id,id,revision,state,disposition,has_fix,source_pull_number,target_pull_number) + SELECT ?,printf('route-%d',x),1,'active','accepted',0,6,7 FROM n`, attemptProject) + var generate func(*testing.T, *attemptFixture, bool) + if channel == "hosted" { + schedulingEnable(t, f, 0, true) + generate = schedulingGenerate + } else { + schedulingCLIEnable(t, f, 0, true) + generate = schedulingCLIGenerate + } + generate(t, f, true) + run := schedulingLatest(t, f) + reader := &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + if number != 2 { + t.Errorf("source read escaped the cutoff to PR %d", number) + } + pull := schedulingPull(number) + pull.IsDraft = &held + return pull, nil + }} + selectionNext(t, f, reader) + got := selectionRead(t, f, run.ID) + if held { + if got.State != "held" || got.Reason != "pull_draft" || got.OperationID != "" { + t.Fatal("no-child hold did not settle", got) + } + } else { + if got.State != "selected" || got.OperationID == "" { + t.Fatal("earlier candidate did not settle", got) + } + } + if err := f.e.RecoverReviewRuns(t.Context()); err != nil { + t.Fatal(err) + } + generate(t, f, false) + }) + } + } +} + +func TestAutomaticPlanningStrictCutoffPreservesProoflessLegacyHold(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4, 6}) + f.enqueue(t, attemptProject, "legacy-cutoff-queued", "hosted", 4, 1) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + run := schedulingLatest(t, f) + draft := true + selectionNext(t, f, &refreshTestReader{pull: func(_ context.Context, _ string, number int64) (reviewprovider.Pull, error) { + pull := schedulingPull(number) + pull.IsDraft = &draft + return pull, nil + }}) + if got := selectionRead(t, f, run.ID); got.State != "held" || got.OperationID != "" { + t.Fatal("fixture did not retain a pre-child hold", got) + } + + admissionSQL(t, f, `UPDATE events SET payload_json='{"channel":"hosted"}' WHERE resource_id=? AND event_type='review.selection_requested'`, run.ID) + admissionSQL(t, f, `UPDATE review_automatic_selections SET + basis_sha256=printf('%064d',1),settled_basis_sha256=printf('%064d',2) WHERE selection_id=?`, run.ID) + schedulingGenerate(t, f, false) + + // Enabling only the other lane keeps Hosted's basis epoch intact. + schedulingCLIEnable(t, f, 1, true) + schedulingGenerate(t, f, false) + // Deliberately reasserting Hosted rearms its earlier prefix. + schedulingEnable(t, f, 2, true) + schedulingGenerate(t, f, true) + if latest := schedulingLatest(t, f); latest.ID == run.ID { + t.Fatal("rearm reused the earlier held intent", latest) + } +} + +func TestLegacyAutomaticOriginCannotBecomeExplicit(t *testing.T) { + for _, wrongProject := range []bool{false, true} { + name := "missing" + if wrongProject { + name = "wrong-project" + } + t.Run(name, func(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + run := schedulingLatest(t, f) + admissionSQL(t, f, `UPDATE events SET payload_json='{"channel":"hosted"}' WHERE resource_id=? AND event_type='review.selection_requested'`, run.ID) + if wrongProject { + admissionSQL(t, f, `UPDATE review_automatic_selections SET project_id=? WHERE selection_id=?`, otherAttemptProject, run.ID) + } else { + admissionSQL(t, f, `DELETE FROM review_automatic_selections WHERE selection_id=?`, run.ID) + } + schedulingEnable(t, f, 1, false) + reader := &refreshTestReader{} + selectionNext(t, f, reader) + if got := selectionRead(t, f, run.ID); got.State != "held" || got.OperationID != "" || reader.calls.Load() != 0 { + t.Fatal("unproved legacy selection inherited explicit authority", got) + } + }) + } +} + +func TestAutomaticPlanningKeepsLegacySelectedPullSuppressionAtCutoff(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2, 4, 6}) + f.enqueue(t, attemptProject, "legacy-attributable-cutoff", "hosted", 6, 1) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + run := schedulingLatest(t, f) + admissionSQL(t, f, `UPDATE events SET payload_json='{"channel":"hosted"}' WHERE resource_id=? AND event_type='review.selection_requested'`, run.ID) + _, err := f.e.ControlOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "cancel-legacy-selected", run.OperationID, OperationControl{ExpectedRevision: 1, Action: "cancel"}) + if err != nil { + t.Fatal(err) + } + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + next := schedulingLatest(t, f) + nextOp, err := f.e.ReadOperation(t.Context(), selectionScope(t, f, attemptProject, f.writer, "read"), next.OperationID) + if err != nil || nextOp.PullNumber != 4 { + t.Fatal("legacy selected basis was lost or blocked an independent PR", next, nextOp, err) + } +} diff --git a/internal/reviewexec/selection_native_key_test.go b/internal/reviewexec/selection_native_key_test.go index d080cb6ca..90a4878be 100644 --- a/internal/reviewexec/selection_native_key_test.go +++ b/internal/reviewexec/selection_native_key_test.go @@ -21,9 +21,9 @@ func TestSelectionNativeBlobKeyDoesNotStopRecovery(t *testing.T) { // sorts text before blobs. Use a malformed project key as well so // a healthy selection can follow a malformed key in that scan. const corruptID = "review_selection_00000000000000000000000000000000" - const healthyID = "review_selection_ffffffffffffffffffffffffffffffff" + healthyID := healthy.ID admissionSQL(t, f, `UPDATE review_selections SET id=?,state=?,created_at=? WHERE id=?`, corruptID, tc.state, "2000-01-01T00:00:00Z", corrupt.ID) - admissionSQL(t, f, `UPDATE review_selections SET id=?,state=?,created_at=? WHERE id=?`, healthyID, tc.state, "2000-01-02T00:00:00Z", healthy.ID) + admissionSQL(t, f, `UPDATE review_selections SET state=?,created_at=? WHERE id=?`, tc.state, "2000-01-02T00:00:00Z", healthyID) var corruptKey any = []byte(corruptID) if tc.key == "id" { admissionSQL(t, f, `UPDATE review_selections SET id=CAST(id AS BLOB) WHERE id=?`, corruptID) From eb1648145f0b03417cfeec29f209ee9661d59e66 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 00:36:23 +1300 Subject: [PATCH 33/41] Test durable acceptance order without a legacy timestamp --- .../hosted_control_batch_regression_test.go | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/internal/reviewexec/hosted_control_batch_regression_test.go b/internal/reviewexec/hosted_control_batch_regression_test.go index 772fe7139..697ff480b 100644 --- a/internal/reviewexec/hosted_control_batch_regression_test.go +++ b/internal/reviewexec/hosted_control_batch_regression_test.go @@ -52,21 +52,31 @@ func TestQueuedNativeSelectionWithUnprovedChildDoesNotStopIndependentSelection(t func TestSourceRecoveryRefusesUnknownEventlessAcceptanceOrder(t *testing.T) { for _, tc := range []struct { - name, createdAt string - keepEvent, want bool + name, createdAt string + keepEvent, neighborFirst, want bool }{ - {"eventless-earlier", "2001-01-01T00:00:00Z", false, false}, - {"eventless-unknown", "unknown", false, true}, - {"later-event-authoritative", "2001-01-01T00:00:00Z", true, true}, + {"eventless-earlier-wall-clock-unproved", "2001-01-01T00:00:00Z", false, false, true}, + {"eventless-unknown", "unknown", false, false, true}, + {"later-event-authoritative", "2001-01-01T00:00:00Z", true, false, true}, + {"earlier-event-authoritative", "2099-01-01T00:00:00Z", true, true, false}, } { t.Run(tc.name, func(t *testing.T) { f := selectionFixture(t) + enqueueNeighbor := func() string { + return f.enqueue(t, attemptProject, "retained-intent", "hosted", 2, 1).ID + } + var neighborID string + if tc.neighborFirst { + neighborID = enqueueNeighbor() + } base, _ := selectionEnqueue(t, f, "recovery-target", "hosted", nil) - neighbor := f.enqueue(t, attemptProject, "retained-intent", "hosted", 2, 1) + if !tc.neighborFirst { + neighborID = enqueueNeighbor() + } run := selectionRead(t, f, base.ID) - admissionSQL(t, f, `UPDATE review_operations SET created_at=? WHERE id=?`, tc.createdAt, neighbor.ID) + admissionSQL(t, f, `UPDATE review_operations SET created_at=? WHERE id=?`, tc.createdAt, neighborID) if !tc.keepEvent { - admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.requested' AND resource_id=?`, neighbor.ID) + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.requested' AND resource_id=?`, neighborID) } err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { got, err := automaticSourceSuperseded(ctx, tx, run) From 83d1030da50bb43c5c243c45760488107569cb72 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 25 Nov 2026 16:06:12 +1300 Subject: [PATCH 34/41] Use the full-plan helper signature in the scheduler fixture --- internal/reviewexec/scheduling_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index 5e2690c43..333ddb122 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -287,7 +287,7 @@ func TestSchedulingPausedFrontSkipsIndependentButNotDependency(t *testing.T) { plans[i].Repository.ID = 801 } plans[1].Pull.BaseSHA = head - front, reason, err := f.e.runFront(ctx, tx, Run{ProjectID: attemptProject, Channel: "hosted"}, 801, plans) + front, reason, err := f.e.runFront(ctx, tx, Run{ProjectID: attemptProject, Channel: "hosted"}, 801, plans, true) if err != nil { return err } From 10a6e5c9f3559e9098a8c42c7eadad1aa0829645 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 26 Nov 2026 01:54:19 +1300 Subject: [PATCH 35/41] Scope scheduling preference and document recovery boundaries --- docs/review-scheduling.md | 6 +- internal/reviewexec/run_selection_worker.go | 48 +++++++++--- internal/reviewexec/scheduling_cli.go | 5 +- .../reviewexec/scheduling_cli_priority.go | 13 +++- .../scheduling_cli_selection_account_test.go | 75 +++++++++++++++++++ 5 files changed, 131 insertions(+), 16 deletions(-) create mode 100644 internal/reviewexec/scheduling_cli_selection_account_test.go diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index b22453dfc..fe7d1bb27 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -8,7 +8,7 @@ Projects can independently opt in to automatic new Hosted or CLI requests. Both ## Automatic Hosted requests -A project manager enables scheduling through the HTTP API; bound CLI and MCP delivery follows in the dependent client slice. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. The HTTP contract also permits an authorized browser manager to explicitly select the authorizing worker while retaining the human session identity. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected queued intent may continue after an A-to-B-to-A authorizer sequence when the current authorizer again matches its original authorizer and complete history proves its channel stayed enabled throughout. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. The acceptance event records whether a new selection is explicit or automatic. Automatic selections and their children require matching retained scheduling attribution before selection, recovery or dispatch. Missing or conflicting attribution holds those requests. For older selections, a caller-supplied PR pin, an exact retained explicit mutation receipt, or complete retained history showing acceptance before automatic scheduling for that channel can establish explicit origin. An ambiguous legacy selection stays held. Current explicit authorization still applies. +A project manager enables scheduling through the HTTP API; bound CLI and MCP delivery follows in the dependent client slice. The separate browser scheduling control is not included in this source slice. Enabling binds authorization to that manager's exact credential and an active project worker. This project scheduling write requires bearer authentication and active project worker attribution. Browser sessions do not authorize this route. The controller rechecks that authorization before selection and dispatch. New selections use the current configured authorizer. An already selected automatic operation retains its original principal, worker and credential when a later manager changes settings. Any later scheduling revision requires complete durable history proving that the intent's own channel stayed enabled in every intervening revision, including when the authorizer is unchanged. Missing history or any disable/re-enable blocks continuation. An unchanged authorizer can finish a queued or selecting intent across a continuously enabled history, including unrelated-channel changes. When the current authorizer differs from the original authorizer, only an already selected operation can continue, and both authorizers must remain valid. An unselected queued intent may continue after an A-to-B-to-A authorizer sequence when the current authorizer again matches its original authorizer and complete history proves its channel stayed enabled throughout. This preserves the existing operation and any quota timer rather than creating a replacement. A blocked queued operation reports `automation_authorization_changed` as a current diagnostic for manager investigation. Revoked credentials, lost management access, retired workers and restored-provider holds cannot authorize new work. The acceptance event records whether a new selection is explicit or automatic. Automatic selections and their children require matching retained scheduling attribution before selection, recovery or dispatch. Missing or conflicting attribution holds those requests. For older selections, a caller-supplied PR pin, an exact retained explicit mutation receipt, or complete retained history showing acceptance before automatic scheduling for that channel can establish explicit origin. An ambiguous legacy selection stays held. Current explicit authorization still applies. The scheduler uses the existing configured queue and ordinary durable selection/operation path. It checks eligible work at most once per five-second coordinator interval; this is not a promised start time or another GitHub polling loop. Source, dependency, publication, findings, routes, imported obligations, round limits, taper and provider guards still apply. Independent PRs can proceed while another awaits fixes; real dependencies retain predecessor guards. Retained scheduling validation failures prevent planning for the affected project; malformed shared scheduling state or unavailable shared authorization can affect both channels. Channel-front and source-retry selection validation failures, a retained parent cycle, or a planning basis above its row limit remain local to the affected project and channel. Independent projects continue, and channel-specific failures do not block the other channel. The execution supervisor skips these typed project-local refusals, and a damaged competing priority candidate cannot block a healthy project’s account claim. A deterministic basis refusal during selection settlement rolls back source and child writes and holds the original selection as `automatic_scheduling_unavailable`; it is not transient contention and does not enter the writer retry loop. The accepted basis remains available for duplicate suppression across ticks and restart. Startup validates the shared front-cache table definition without scanning optional cache rows. Damaged rows remain isolated by project/channel readers; backup and restore still validate the complete retained snapshot. Shared storage and transaction failures remain errors rather than being suppressed; arbitrary SQL failures are not classified as project-local corruption. Automatic requests never inherit out-of-order or file-limit overrides. Each project first plans in a bounded read-only snapshot. Only a candidate for a new intent or a due retained source retry enters the writer, which repeats authorization, configuration, policy, pause, busy and basis checks before ordinary atomic acceptance or retry. A changed plan waits for a later pass. @@ -26,7 +26,7 @@ A project manager can explicitly enable `automatic_cli` through CLI, MCP or the Automatic CLI uses the ordinary durable channel-front selection and execution path, without out-of-order or file-limit overrides. Existing grants, maxima, taper, channel closure, exact current-head checks, source-owned predecessor dependencies, publication and adjudication requirements remain in force. No setting increases grants or adjudicates findings. A meaningful completed result or source/control change can authorize another selection; ticks, restart, failed attempts and cancellation alone cannot. CLI and Hosted results have separate intent digests, so a clean completion in the other channel does not recreate a cancelled request. -The current server policy fixes one repository preference in code; it is not a per-project setting. For competing CLI work on the same installed provider account, the repository `benhook1013/FireMUD` takes priority over other projects. The repository identity is case-insensitive; a project display name does not grant priority. Selection considers that repository first, and the serialized attempt claim also yields to its eligible queued requests. Paused, invalid, draft-waiting or not-yet-due requests do not reserve the account. Other accounts remain independent and active reviews are never preempted. This preference does not relax dependencies or change retained quota deadlines. It has no fairness or maximum-deferral guarantee: other projects on that account may wait indefinitely while the preferred repository continues to have eligible work. +The current server policy fixes one repository preference in code; it is not a per-project setting. For competing CLI work on the same installed provider account, the repository `benhook1013/FireMUD` takes priority over other projects. The repository identity is case-insensitive; a project display name does not grant priority. Selection takes the oldest eligible account group first, then considers that repository first inside the group. The serialized attempt claim also yields to its eligible queued requests. Paused, invalid, draft-waiting or not-yet-due requests do not reserve the account. Other accounts remain independent and active reviews are never preempted. This preference does not relax dependencies or change retained quota deadlines. It has no fairness or maximum-deferral guarantee: other projects on that account may wait indefinitely while the preferred repository continues to have eligible work. An already queued explicit or automatic CLI operation prevents a duplicate request for its PR. Proven quota exhaustion keeps that operation and its original comparison through the existing shared-account backoff. Disable automatic CLI to stop new automatic selection and authorization of its undispatched children; explicit pending requests retain their original authorization. Use an operation cancellation or PR pause when the intent itself must stop. Results and merge decisions remain operator work. @@ -70,7 +70,7 @@ Backups retain scheduling, PR pauses, selection acceptance events and automatic- A proved linked selection custody hold retains its original child identifier and observed revision in a private versioned diagnostic record. It never changes the child, authorizer, retained evidence, or the existing provider action. Active capacity remains attributed as before; a demonstrably held child cannot obtain new admission or reserve an ordinary queued turn. Unproved or ambiguous provenance cannot establish eligibility and remains fail-closed. -The selection custody schema upgrade is forward-only on the active database. Verify and retain a pre-upgrade version-one backup before upgrading. If binary rollback is required, restore that verified bundle to a separate inactive destination, with the existing recovery, activation and provider reconciliation procedure; do not run the old binary on the upgraded version-two database. Version-two backups are for compatible readers and preserve custody records indefinitely pending an explicit retention policy. There is no automatic deletion, retention expiry, or downgrade migration. +The selection custody schema upgrade is forward-only on the active database. Verify and retain a pre-upgrade version-one backup before upgrading. If binary rollback is required, restore that verified bundle to a separate inactive destination. Restoration recovers state only through the backup snapshot; subsequent operations and evidence are not in that destination. Preserve the upgraded state and account for later writes and provider actions using the existing recovery and provider reconciliation procedure before activation. Do not run the old binary on the upgraded version-two database. Version-two backups are for compatible readers and preserve custody records indefinitely pending an explicit retention policy. There is no automatic deletion, retention expiry, or downgrade migration. ## Validation diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index 256727fae..ad7d1d43d 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -3,6 +3,7 @@ package reviewexec import ( "context" "database/sql" + "encoding/json" "errors" "github.com/benhook1013/FireController/internal/core" "github.com/benhook1013/FireController/internal/reviewprovider" @@ -513,9 +514,10 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR } type runCandidateCursor struct { - priority int64 - createdAt any - id any + priority int64 + accountAt, accountID any + createdAt any + id any } func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) (bool, error) { @@ -542,6 +544,20 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target var project, id string var nativeProject, nativeID, nativeCreatedAt any var candidatePriority int64 + var accountAt, accountID any + accounts := make(map[string]string) + for _, capability := range e.capabilities { + if capability.Fingerprint == "" || capability.Provider == "" || capability.Account == "" { + continue + } + account := automaticAccountKey(capability) + if prior, exists := accounts[capability.Fingerprint]; exists && prior != account { + accounts[capability.Fingerprint] = "" + continue + } + accounts[capability.Fingerprint] = account + } + accountJSON, _ := json.Marshal(accounts) // map[string]string is always JSON encodable. var quarantined bool var expected int64 err := retryRunSelectionLocal(ctx, func() error { @@ -553,16 +569,29 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target // both selection workers or repeatedly reacquire provider facts. // A linked selection with a non-native key cannot prove custody. // Leave it intact and allow unrelated selections to proceed. - err := tx.QueryRowContext(ctx, `WITH candidates AS ( - SELECT s.*,CASE WHEN s.channel='cli' AND (SELECT lower(repository) FROM projects WHERE id=s.project_id)=? THEN 0 ELSE 1 END AS run_priority - FROM review_selections s) - SELECT s.project_id,s.id,`+selectionClaimRevision+`,s.created_at,s.run_priority FROM candidates s + err := tx.QueryRowContext(ctx, `WITH eligible AS ( + SELECT s.*,a.value AS installed_account, + CASE WHEN a.value<>'' AND lower(p.repository)=? THEN 0 ELSE 1 END AS run_priority + FROM review_selections s LEFT JOIN projects p ON p.id=s.project_id + LEFT JOIN json_each(?) a ON s.channel='cli' AND a.key=s.capability_fingerprint AND a.value<>'' WHERE s.state='queued' - AND (? IS NULL OR (s.run_priority,s.created_at,s.id)>(?,?,?)) 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'))(?,?,?,?,?)) + ORDER BY s.account_at,s.account_id,s.run_priority,s.created_at,s.id LIMIT 1`, preferredCLIRepository, string(accountJSON), requestGlobalCapacity, requestProjectCapacity, + cursor.id, cursor.accountAt, cursor.accountID, cursor.priority, cursor.createdAt, cursor.id). + Scan(&nativeProject, &nativeID, &expected, &nativeCreatedAt, &candidatePriority, &accountAt, &accountID) if errors.Is(err, sql.ErrNoRows) { return nil } @@ -573,6 +602,7 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target return false, err } cursor.priority, cursor.createdAt, cursor.id = candidatePriority, nativeCreatedAt, nativeID + cursor.accountAt, cursor.accountID = accountAt, accountID var projectOK, idOK bool project, projectOK = nativeProject.(string) id, idOK = nativeID.(string) diff --git a/internal/reviewexec/scheduling_cli.go b/internal/reviewexec/scheduling_cli.go index b34b6a4a9..7b2e37a0b 100644 --- a/internal/reviewexec/scheduling_cli.go +++ b/internal/reviewexec/scheduling_cli.go @@ -96,9 +96,8 @@ func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]Ta if err != nil { var failure *core.Error if errors.As(err, &failure) && failure.Code == "overloaded" && ctx.Err() == nil { - // Preserve this account's turn for the next pass while - // allowing other accounts to plan independent requests. - selectedAccounts[account] = true + // No intent was accepted. Other projects on the same + // account can still make progress during this bounded pass. continue } return generated, err diff --git a/internal/reviewexec/scheduling_cli_priority.go b/internal/reviewexec/scheduling_cli_priority.go index 12d6947fb..586ee2b02 100644 --- a/internal/reviewexec/scheduling_cli_priority.go +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -107,7 +107,18 @@ candidates: return false, err } if valid { - return true, nil + // A queued request cannot reserve priority when its exact + // target is already occupied, including by another account. + var busy bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 + FROM review_execution_reservations r JOIN projects p ON p.github_repository_id=r.repository_id + WHERE p.id=? AND r.provider=? AND r.action_class='cli' AND r.pull_number=?)`, + earlier.ProjectID, priorCapability.Provider, earlier.PullNumber).Scan(&busy); err != nil { + return false, err + } + if !busy { + return true, nil + } } } return e.preferredCLISelection(ctx, tx, o, capability) diff --git a/internal/reviewexec/scheduling_cli_selection_account_test.go b/internal/reviewexec/scheduling_cli_selection_account_test.go new file mode 100644 index 000000000..28564fc93 --- /dev/null +++ b/internal/reviewexec/scheduling_cli_selection_account_test.go @@ -0,0 +1,75 @@ +package reviewexec + +import ( + "encoding/json" + "testing" +) + +func TestSelectionRepositoryPreferenceRespectsInstalledAccount(t *testing.T) { + for _, tc := range []struct { + name, capability string + prefer bool + }{ + {"same-account", "test-capability", true}, + {"different-account", "other-account", false}, + } { + t.Run(tc.name, func(t *testing.T) { + f := schedulingFixture(t) + f.configure(t, otherAttemptProject, tc.capability, 0, false) + admissionSQL(t, f, `UPDATE projects SET repository='benhook1013/FireMUD' WHERE id=?`, otherAttemptProject) + ordinary, _ := selectionEnqueue(t, f, "account-ordinary", "cli", nil) + scope := selectionScope(t, f, otherAttemptProject, f.other, "write") + raw, err := f.e.EnqueueRun(t.Context(), scope, "account-preferred", RunRequest{Channel: "cli"}) + if err != nil { + t.Fatal(err) + } + var preferred Receipt + if err = json.Unmarshal(raw, &preferred); err != nil { + t.Fatal(err) + } + admissionSQL(t, f, `UPDATE review_selections SET created_at='2026-01-01T00:00:01Z' WHERE id=?`, ordinary.ID) + admissionSQL(t, f, `UPDATE review_selections SET created_at='2026-01-01T00:00:02Z' WHERE id=?`, preferred.ID) + reader := &refreshTestReader{} + worked, err := f.e.runNext(t.Context(), map[string]TargetReader{"test-capability": reader, tc.capability: reader}) + if !worked || err != nil { + t.Fatal(worked, err) + } + left, right := ordinary.ID, preferred.ID + if tc.prefer { + left, right = right, left + } + var first, second string + if err = f.store.DB().QueryRow(`SELECT state FROM review_selections WHERE id=?`, left).Scan(&first); err != nil { + t.Fatal(err) + } + if err = f.store.DB().QueryRow(`SELECT state FROM review_selections WHERE id=?`, right).Scan(&second); err != nil { + t.Fatal(err) + } + if first == "queued" || second != "queued" { + t.Fatalf("expected first selected pass for %s; got %s, %s", left, first, second) + } + }) + } +} + +// An ordinary local reservation remains authoritative without letting a +// conflicting preferred request consume priority on an independent account. +func TestPreferredCLIQueuedSkipsOccupiedTarget(t *testing.T) { + f := schedulingFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + low := f.enqueue(t, attemptProject, "priority-ordinary", "cli", 2, 1) + f.enqueue(t, otherAttemptProject, "priority-preferred", "cli", 2, 1) + admissionSQL(t, f, `UPDATE projects SET repository=? WHERE id=?`, preferredCLIRepository, otherAttemptProject) + if !schedulingCLI0030Priority(t, f, attemptProject, low.ID) { + t.Fatal("eligible preferred target lost priority") + } + // The fixture adds a synthetic existing reservation for the exact preferred + // comparison. No provider or worker is invoked. + admissionSQL(t, f, `INSERT INTO review_execution_attempts(id,operation_id,project_id,provider,account,state,revision,anchor_json,intent,external_id) + SELECT 'fixture-reservation',id,project_id,'coderabbit','second-account','preparing',1,'null','','' FROM review_operations WHERE id=?`, low.ID) + admissionSQL(t, f, `INSERT INTO review_execution_reservations(provider,repository_id,pull_number,action_class,account,attempt_id) + SELECT 'coderabbit',github_repository_id,2,'cli','second-account','fixture-reservation' FROM projects WHERE id=?`, otherAttemptProject) + if schedulingCLI0030Priority(t, f, attemptProject, low.ID) { + t.Fatal("occupied preferred target still consumes priority") + } +} From 03dff72dfe6fbf3b5d1c173875b8429467dad2ae Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 26 Nov 2026 06:24:24 +1300 Subject: [PATCH 36/41] Address Hosted scheduling and custody review findings --- internal/reviewexec/scheduling.go | 6 +- internal/reviewexec/scheduling_automatic.go | 8 +- internal/reviewexec/scheduling_cli.go | 45 +++++--- .../reviewexec/scheduling_cli_priority.go | 19 +++- .../scheduling_ef30_contract_test.go | 107 ++++++++++++++++++ .../scheduling_recovery_regression_test.go | 15 ++- .../selection_quarantine_custody_test.go | 11 ++ 7 files changed, 187 insertions(+), 24 deletions(-) create mode 100644 internal/reviewexec/scheduling_ef30_contract_test.go diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index 48c42049b..fcb1b57a9 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -260,11 +260,11 @@ func (e *Engine) ConfigureScheduling(ctx context.Context, scope core.Scope, key if input.AutomaticCLI != nil { automaticCLI = *input.AutomaticCLI } + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, scope.WorkerID); err != nil { + return nil, err + } credential := "" if *input.AutomaticHosted || automaticCLI { - if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, scope.WorkerID); err != nil { - return nil, err - } credential, err = e.store.AuthenticatedCredentialID(ctx, tx, scope) if err != nil { return nil, err diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 916efc2f8..92077cab8 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -734,7 +734,13 @@ func (e *Engine) generateAutomaticHosted(ctx context.Context, readers map[string } func (e *Engine) coordinateAutomaticHosted(ctx context.Context, readers map[string]TargetReader) (bool, error) { - e.automaticMu.Lock() + if err := ctx.Err(); err != nil { + return false, err + } + // Leave the other selection worker available for accepted intents. + if !e.automaticMu.TryLock() { + return false, ctx.Err() + } defer e.automaticMu.Unlock() if ctx.Err() != nil { return false, ctx.Err() diff --git a/internal/reviewexec/scheduling_cli.go b/internal/reviewexec/scheduling_cli.go index 7b2e37a0b..edd662f85 100644 --- a/internal/reviewexec/scheduling_cli.go +++ b/internal/reviewexec/scheduling_cli.go @@ -33,7 +33,31 @@ func automaticCLIProjects(ctx context.Context, tx *sql.Tx, preferred bool, curso return projects, rows.Close() } +func (e *Engine) automaticCLIAccount(ctx context.Context, project string) (string, error) { + var account string + err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { + c, _, err := readConfiguration(ctx, tx, project) + if err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "reviews_unconfigured" { + return nil + } + return err + } + capability, ok := e.capabilities[c.CapabilityID] + if ok { + account = automaticAccountKey(capability) + } + return nil + }) + return account, err +} + func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]TargetReader) (bool, error) { + return e.generateAutomaticCLIWithAccountLookup(ctx, readers, e.automaticCLIAccount) +} + +func (e *Engine) generateAutomaticCLIWithAccountLookup(ctx context.Context, readers map[string]TargetReader, lookupAccount func(context.Context, string) (string, error)) (bool, error) { var preferred, other []string if err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { const half = automaticCLITraversalLimit / 2 @@ -64,26 +88,15 @@ func (e *Engine) generateAutomaticCLI(ctx context.Context, readers map[string]Ta } else { e.automaticCLIOtherCursor = project } - var account string - err := e.readAdmission(ctx, func(ctx context.Context, tx *sql.Tx) error { - c, _, err := readConfiguration(ctx, tx, project) - if err != nil { - var failure *core.Error - if errors.As(err, &failure) && failure.Code == "reviews_unconfigured" { - return nil - } - return err - } - capability, ok := e.capabilities[c.CapabilityID] - if ok { - account = automaticAccountKey(capability) - } - return nil - }) + account, err := lookupAccount(ctx, project) if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { continue } if err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "overloaded" && ctx.Err() == nil { + continue // Bounded local lookup; no account turn was consumed. + } return generated, err } if account == "" || selectedAccounts[account] { diff --git a/internal/reviewexec/scheduling_cli_priority.go b/internal/reviewexec/scheduling_cli_priority.go index 586ee2b02..81ad75378 100644 --- a/internal/reviewexec/scheduling_cli_priority.go +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "encoding/json" + "errors" "slices" "strings" ) @@ -77,7 +78,7 @@ candidates: if earlier.Wait != nil && earlier.Wait.Paused { continue } - priorConfig, _, err := readConfiguration(ctx, tx, id.project) + priorConfig, revision, err := readConfiguration(ctx, tx, id.project) if err != nil { if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { continue candidates @@ -116,7 +117,21 @@ candidates: earlier.ProjectID, priorCapability.Provider, earlier.PullNumber).Scan(&busy); err != nil { return false, err } - if !busy { + if busy { + continue candidates + } + dependency, err := e.earlierQueuedReviewIntentWithWitness(ctx, tx, earlier, priorConfig, revision, nil, nil, false) + if err != nil { + if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) || isStoredUnavailable(err, storedRoundHistory) || selectionCustodyUnproved(err) { + continue candidates + } + var preflight *queuePriorityPreflight + if errors.As(err, &preflight) { + continue candidates // Priority does not collect or fabricate a witness. + } + return false, err + } + if dependency == nil { return true, nil } } diff --git a/internal/reviewexec/scheduling_ef30_contract_test.go b/internal/reviewexec/scheduling_ef30_contract_test.go new file mode 100644 index 000000000..35696d57e --- /dev/null +++ b/internal/reviewexec/scheduling_ef30_contract_test.go @@ -0,0 +1,107 @@ +package reviewexec + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func TestOccupiedPlannerLeavesExplicitSelectionAvailable(t *testing.T) { + f := schedulingFixture(t) + receipt, _ := selectionEnqueue(t, f, "without-planner-slot", "cli", nil) + f.e.automaticMu.Lock() + defer f.e.automaticMu.Unlock() + if worked, err := f.e.coordinateAutomaticHosted(t.Context(), nil); worked || err != nil { + t.Fatal(worked, err) + } + selectionNext(t, f, &refreshTestReader{}) + if got := selectionRead(t, f, receipt.ID); got.State != "selected" || got.OperationID == "" { + t.Fatal("explicit selection failed", got) + } +} + +func TestSchedulingAllOffRequiresAnActiveWorker(t *testing.T) { + f := schedulingFixture(t) + before := snapshotTable(t, f, "review_scheduling") + attempt := func(worker, key string) *httptest.ResponseRecorder { + r := httptest.NewRequest("POST", "/api/v1/projects/"+attemptProject+"/reviews/scheduling", strings.NewReader(`{"expected_revision":0,"automatic_hosted":false,"automatic_cli":false}`)) + r.Header.Set("Authorization", "Bearer "+f.admin) + if worker != "" { + r.Header.Set("X-FC-Worker", worker) + } + r.Header.Set("Idempotency-Key", key) + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + return w + } + if w := attempt("", "missing-with-all-off"); w.Code != http.StatusNotFound { + t.Fatal(w.Code, w.Body.String()) + } + if before != snapshotTable(t, f, "review_scheduling") { + t.Fatal("unattributed request wrote state") + } + if w := attempt("selection-worker", "bound-with-all-off"); w.Code != http.StatusOK { + t.Fatal(w.Code, w.Body.String()) + } +} + +func TestPreferredCLIQueuedDoesNotYieldForBlockedSuccessor(t *testing.T) { + f := schedulingFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + low := f.enqueue(t, attemptProject, "ordinary", "cli", 2, 1) + f.enqueue(t, otherAttemptProject, "first-preferred", "cli", 2, 1) + f.enqueue(t, otherAttemptProject, "second-preferred", "cli", 4, 1) + admissionSQL(t, f, `UPDATE projects SET repository=? WHERE id=?`, preferredCLIRepository, otherAttemptProject) + if !schedulingCLI0030Priority(t, f, attemptProject, low.ID) { + t.Fatal("eligible predecessor did not retain priority") + } + admissionSQL(t, f, `INSERT INTO review_execution_attempts(id,operation_id,project_id,provider,account,state,revision,anchor_json,intent,external_id) + SELECT 'prior-reservation',id,project_id,'coderabbit','second-account','preparing',1,'null','','' FROM review_operations WHERE id=?`, low.ID) + admissionSQL(t, f, `INSERT INTO review_execution_reservations(provider,repository_id,pull_number,action_class,account,attempt_id) + SELECT 'coderabbit',github_repository_id,2,'cli','second-account','prior-reservation' FROM projects WHERE id=?`, otherAttemptProject) + if schedulingCLI0030Priority(t, f, attemptProject, low.ID) { + t.Fatal("blocked successor still consumes priority") + } +} + +func TestAutomaticCLITransientAccountLookupDoesNotStarveOrdinaryProject(t *testing.T) { + for _, fatal := range []bool{false, true} { + t.Run(map[bool]string{false: "deadline", true: "shared-storage"}[fatal], func(t *testing.T) { + f := schedulingFixture(t) + f.configure(t, otherAttemptProject, "other-account", 0, false) + admissionSQL(t, f, `UPDATE projects SET repository=? WHERE id=?`, preferredCLIRepository, attemptProject) + schedulingCLIEnable(t, f, 0, true) + zero, off, on := int64(0), false, true + if _, err := f.e.ConfigureScheduling(t.Context(), selectionScope(t, f, otherAttemptProject, f.admin, "write"), "other-active", SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &off, AutomaticCLI: &on}); err != nil { + t.Fatal(err) + } + lookupErr := core.Fail("overloaded", "bounded local lookup fixture", 503) + if fatal { + lookupErr = core.Fail("storage_unavailable", "shared store lookup fixture", 500) + } + calls := []string{} + worked, err := f.e.generateAutomaticCLIWithAccountLookup(t.Context(), map[string]TargetReader{"other-account": &refreshTestReader{}}, func(ctx context.Context, project string) (string, error) { + calls = append(calls, project) + if project == attemptProject { + return "", lookupErr + } + return f.e.automaticCLIAccount(ctx, project) + }) + n := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections WHERE project_id=?`, otherAttemptProject) + if fatal { + if worked || !errors.Is(err, lookupErr) || len(calls) != 1 || n != 0 { + t.Fatal(worked, err, calls, n) + } + return + } + if !worked || err != nil || len(calls) != 2 || calls[0] != attemptProject || calls[1] != otherAttemptProject || n != 1 { + t.Fatal(worked, err, calls, n) + } + }) + } +} diff --git a/internal/reviewexec/scheduling_recovery_regression_test.go b/internal/reviewexec/scheduling_recovery_regression_test.go index 63b7c0050..3462dcc26 100644 --- a/internal/reviewexec/scheduling_recovery_regression_test.go +++ b/internal/reviewexec/scheduling_recovery_regression_test.go @@ -350,6 +350,9 @@ func TestAutomaticCoordinatorIsolatesProjectState(t *testing.T) { admissionSQL(t, f, `CREATE TABLE review_finding_routes(project_id TEXT,id TEXT,revision INTEGER,state TEXT,disposition TEXT,has_fix INTEGER,source_pull_number INTEGER,target_pull_number INTEGER)`) admissionSQL(t, f, `WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<10001) INSERT INTO review_finding_routes SELECT ?,printf('route-%d',x),1,'active','accepted',0,2,4 FROM n`, attemptProject) case "retry-selection": + if before := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections WHERE project_id=?`, otherAttemptProject); before != 0 { + t.Fatal("healthy project was selected before retry fixture", before) + } if worked, err := generate(t.Context(), readers); err != nil || !worked { t.Fatal(worked, err) } @@ -357,6 +360,12 @@ func TestAutomaticCoordinatorIsolatesProjectState(t *testing.T) { return reviewprovider.Repository{}, context.DeadlineExceeded }}) r := schedulingLatest(t, f) + if r.ProjectID != attemptProject || r.State != "held" || r.Channel != channel { + t.Fatalf("retry fixture targeted another project or was not held: %+v", r) + } + if before := attemptCount(t, f.store, `SELECT count(*) FROM review_automatic_selections WHERE project_id=?`, otherAttemptProject); before != 0 { + t.Fatal("healthy project already has an intent", before) + } admissionSQL(t, f, `UPDATE review_selections SET updated_at='malformed' WHERE id=?`, r.ID) // Ensure the bad project is considered before the healthy one again. f.e.automaticCursor, f.e.automaticCLICursor = "", "" @@ -578,8 +587,10 @@ func TestAutomaticSelectionSettlementRefusalIsAtomicAndLocal(t *testing.T) { _, err = f.e.finishRunChoice(ctx, r, 801, nil, choice) fatal := fault == "sql-after-child" || fault == "hold-write" if fatal { - if err == nil || automaticProjectRefused(err) { - t.Fatal("real persistence failure suppressed", err) + var wrapped *core.Error + if errors.Is(err, context.DeadlineExceeded) || ctx.Err() != nil || + !errors.As(err, &wrapped) || wrapped.Code != "storage_unavailable" || wrapped.Status != 500 || automaticProjectRefused(err) { + t.Fatal("expected normalized injected storage failure, not a retry timeout", err) } } else if err != nil { t.Fatal("local basis refusal escaped or retried", err) diff --git a/internal/reviewexec/selection_quarantine_custody_test.go b/internal/reviewexec/selection_quarantine_custody_test.go index 746bed4f5..55211b7ed 100644 --- a/internal/reviewexec/selection_quarantine_custody_test.go +++ b/internal/reviewexec/selection_quarantine_custody_test.go @@ -152,10 +152,21 @@ func TestSelectionQuarantineRefusesEqualNonTextActors(t *testing.T) { if _, err := tx.ExecContext(ctx, `PRAGMA ignore_check_constraints=OFF`); err != nil { return err } + const selectionState = `SELECT json_array(quote(id),quote(project_id),quote(actor_id),quote(worker_id),quote(channel),quote(configuration_revision),quote(policy_revision),quote(capability_fingerprint),quote(expected_pull_number),quote(state),quote(reason),quote(revision),quote(operation_id),quote(created_at),quote(updated_at)) FROM review_selections WHERE project_id=? AND id=?` + var before, after string + if err := tx.QueryRowContext(ctx, selectionState, r.ProjectID, r.ID).Scan(&before); err != nil { + return err + } moved, err := quarantineNativeSelection(ctx, tx, r.ProjectID, r.ID, "selecting", r.Revision) if moved || !selectionCustodyUnproved(err) { t.Fatalf("malformed retained actors proved custody: moved=%t err=%v", moved, err) } + if err := tx.QueryRowContext(ctx, selectionState, r.ProjectID, r.ID).Scan(&after); err != nil { + return err + } + if before != after { + t.Fatal("refused quarantine changed the original selection or child link") + } return nil }) if err != nil { From e9c7590e99e2b824faec5f7e3ec639380abea9ff Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 26 Nov 2026 08:33:44 +1300 Subject: [PATCH 37/41] Address retained scheduling review findings --- docs/review-scheduling.md | 2 +- internal/backup/review_selection_test.go | 7 ++++ internal/backup/scheduling_test.go | 6 ++-- internal/reviewexec/run_selection.go | 7 ++-- internal/reviewexec/run_selection_worker.go | 5 ++- .../reviewexec/scheduling_cli_priority.go | 12 ++++--- .../scheduling_repository_basis_test.go | 34 +++++++++++++++++++ .../scheduling_source_retry_test.go | 8 ++++- internal/reviewexec/scheduling_test.go | 2 ++ 9 files changed, 72 insertions(+), 11 deletions(-) create mode 100644 internal/reviewexec/scheduling_repository_basis_test.go diff --git a/docs/review-scheduling.md b/docs/review-scheduling.md index fe7d1bb27..bf7b2b11b 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -14,7 +14,7 @@ The scheduler uses the existing configured queue and ordinary durable selection/ Meaningful source, review or control changes can create another automatic intent. A waiting later PR does not prevent reconsideration of an earlier PR that becomes eligible; the earlier request can take priority while the later request retains its identity and cooldown. Existing queued work on a PR prevents a duplicate intent for that PR, and active provider work is not interrupted. Timer-backed requests retain their original operation and retry deadline. Ticks, restarts, observation timestamps and failed/cancelled operation transitions cannot recreate the same request. A clean CLI completion alone cannot restart a cancelled Hosted request. A dependent PR can become eligible when its actual predecessor completes at the same head. Cancellation stops that intent; use a PR pause to hold new reviews persistently. Planning and settlement use semantic facts from the eligible queue prefix. A waiting request fences off later siblings and their local basis checks. A candidate still requires proof of any source-owned dependency. The full-queue digest and selected PR digests retain their original format. Older pre-child holds have only opaque full-queue digests. While a waiting request shortens the queue, an older hold with the same execution configuration, policy and channel basis can prevent accepting an unproved replacement. The scheduler can compare the original digest once the full queue is eligible. Explicitly rearming that channel changes its basis and permits fresh selection under the normal guards. A setting change affecting only the other channel preserves this channel’s intent basis. Changing this channel’s setting or the authorizing principal, worker or credential changes its basis. Explicitly reasserting unchanged settings rearms only the supplied channels; an omitted CLI setting preserves its basis. The current scheduling event retains each channel’s basis revision independently of the shared authorization revision. Older events use their existing shared revision without rewriting any stored digests, so an upgrade alone cannot recreate cancelled work. -A pre-child automatic Hosted or CLI selection held only by `source_budget_exhausted`, `source_fetch_timeout` or `source_provider_unavailable` can retry its source selection after at least thirty seconds. It reuses the original selection and accepted configuration, policy, capability and authorizer, with the exact scheduling revision still current. At most two such delayed retries are permitted by a conservative durable transition budget; interrupted-selection recovery consumes that budget rather than resetting it. Existing recovery of an interrupted read remains separate from this bound on completed source holds. Restart and backup restore retain the budget and last-transition time. Restore/provider holds still prevent work. +A pre-child automatic Hosted or CLI selection held only by `source_budget_exhausted`, `source_fetch_timeout`, `source_provider_unavailable` or `routed_findings_unavailable` can retry its source selection after at least thirty seconds. A route-related hold is retryable only after no configured pull retains a route invalidation and the ordinary retry guards pass. It reuses the original selection and accepted configuration, policy, capability and authorizer, with the exact scheduling revision still current. At most two such delayed retries are permitted by a conservative durable transition budget; interrupted-selection recovery consumes that budget rather than resetting it. Existing recovery of an interrupted read remains separate from this bound on completed source holds. Restart and backup restore retain the budget and last-transition time. Restore/provider holds still prevent work. A later selection or direct operation in the same channel fences off this recovery, including a cancelled, failed or uncertain request. Explicit held selections, linked children, exhausted budgets, refusals, rate limits and invalid source responses are never reopened by it. The retry performs ordinary fresh source selection and normal admission; success may link at most one ordinary child operation under the original authority. It neither grants rounds nor bypasses any dispatch guard. A meaningful source or control change can still authorize a new automatic intent through the normal scheduler. diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index 3c8ee236a..1a4a5ed87 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -435,6 +435,13 @@ func TestSelectionQuarantineInventoryRetainsAutomaticChildWithoutAuthority(t *te if err := db.QueryRow(`SELECT original_operation_id FROM review_selection_quarantine WHERE selection_id=?`, selection).Scan(&got); err != nil || got != operation { t.Fatal("original automatic operation identity was not retained", got, err) } + var state, reason string + var heldRevision int64 + var link sql.NullString + if err := db.QueryRow(`SELECT state,reason,revision,operation_id FROM review_selections WHERE id=? AND project_id=?`, selection, f.project). + Scan(&state, &reason, &heldRevision, &link); err != nil || state != "held" || reason != "linked_selection_quarantined" || heldRevision != revision+1 || link.Valid { + t.Fatal("restore changed the held, unlinked selection", state, reason, heldRevision, link.Valid, err) + } } func TestSelectionQuarantineInventoryRejectsDanglingEmptyV2Marker(t *testing.T) { diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index cf976a2c2..a27be6736 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -221,9 +221,11 @@ func TestSchedulingBackupHistoricalAuthorizersRemainHistory(t *testing.T) { } _, err = f.store.ProjectAutomationScope(t.Context(), tx, f.project, f.principal, f.worker, credential) _ = tx.Rollback() - if err == nil { - t.Fatal("historical authorizer still authorized new automation") + want := "forbidden" + if kind == "retired" { + want = "worker_retired" } + backupCode(t, err, want) before := schedulingBackupRows(t, f.store.DB()) bundle := restoreBundle(t, f) if _, err := Inspect(t.Context(), bundle.Path); err != nil { diff --git a/internal/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 7bc7d49a2..aa43910df 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -553,9 +553,12 @@ func quarantineNativeSelection(ctx context.Context, tx *sql.Tx, project, id any, // 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 + WHERE s.id=? AND s.project_id=? AND typeof(s.actor_id)<>'text' + UNION ALL SELECT 1 FROM review_selections s JOIN review_operations o ON o.id=s.operation_id WHERE s.id=? AND s.project_id=? AND - (typeof(s.actor_id)<>'text' OR typeof(o.actor_id)<>'text' OR + (typeof(o.actor_id)<>'text' OR 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 @@ -567,7 +570,7 @@ func quarantineNativeSelection(ctx context.Context, tx *sql.Tx, project, id any, 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 { + )`, sid, pid, sid, pid, sid, pid).Scan(&inconsistent); err != nil { return false, err } if inconsistent { diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index ad7d1d43d..cc4e42e09 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -763,7 +763,10 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat // An exhausted local read did not verify the final front. Keep // the accepted basis for unchanged-work suppression, but don't // consume a new basis (e.g. a resumed PR) from this failed read. - if pull == 0 && reason == "local_read_unavailable" { + // A repository mismatch never proves the sampled comparison. + // Keep the accepted basis only; do not stamp any later round + // grant or planning facts as served by this read. + if pull == 0 && (reason == "local_read_unavailable" || reason == "repository_changed") { settle = false } if settle && pull == 0 && choice.automaticQueueLimit != nil && choice.automaticBasisRevision != 0 { diff --git a/internal/reviewexec/scheduling_cli_priority.go b/internal/reviewexec/scheduling_cli_priority.go index 81ad75378..40b74f44e 100644 --- a/internal/reviewexec/scheduling_cli_priority.go +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -50,11 +50,15 @@ func (e *Engine) preferredCLIQueued(ctx context.Context, tx *sql.Tx, o Operation } var ids []pendingCandidateID for rows.Next() { - var id pendingCandidateID - if err = rows.Scan(&id.project, &id.operation); err != nil { + var rawProject, rawOperation any + if err = rows.Scan(&rawProject, &rawOperation); err != nil { break } - ids = append(ids, id) + project, projectOK := rawProject.(string) + operation, operationOK := rawOperation.(string) + if projectOK && operationOK { + ids = append(ids, pendingCandidateID{project, operation}) + } } if err == nil { err = rows.Err() @@ -122,7 +126,7 @@ candidates: } dependency, err := e.earlierQueuedReviewIntentWithWitness(ctx, tx, earlier, priorConfig, revision, nil, nil, false) if err != nil { - if automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) || isStoredUnavailable(err, storedRoundHistory) || selectionCustodyUnproved(err) { + if automaticProjectRefused(err) || isRetainedOperationDecodeError(err) || isStoredUnavailable(err, storedConfigurationHistory) || isStoredUnavailable(err, storedRoundHistory) || selectionCustodyUnproved(err) { continue candidates } var preflight *queuePriorityPreflight diff --git a/internal/reviewexec/scheduling_repository_basis_test.go b/internal/reviewexec/scheduling_repository_basis_test.go new file mode 100644 index 000000000..ff6a85474 --- /dev/null +++ b/internal/reviewexec/scheduling_repository_basis_test.go @@ -0,0 +1,34 @@ +package reviewexec + +import ( + "context" + "testing" + + "github.com/benhook1013/FireController/internal/reviewprovider" +) + +func TestRepositoryMismatchLeavesConcurrentRoundGrantUnsettled(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + schedulingGenerate(t, f, true) + r := schedulingLatest(t, f) + read := false + reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { + read = true + roundGrant(t, f, 2, "hosted", 0, 1, 2, "new-local-grant-during-read") + return reviewprovider.Repository{ID: 802, FullName: "owner/alternate", DefaultBranch: "main"}, nil + }} + selectionNext(t, f, reader) + actual := selectionRead(t, f, r.ID) + if !read || actual.State != "held" || actual.Reason != "repository_changed" || actual.OperationID != "" { + t.Fatal("repository fixture failed", read, actual) + } + var settled string + if err := f.store.DB().QueryRow(`SELECT settled_basis_sha256 FROM review_automatic_selections WHERE selection_id=?`, r.ID).Scan(&settled); err != nil || settled != "" { + t.Fatal("unverified source read settled a later basis", settled, err) + } + schedulingGenerate(t, f, true) + if next := schedulingLatest(t, f); next.ID == r.ID || next.State != "queued" { + t.Fatal("new legitimate round basis cannot receive a fresh source read", next) + } +} diff --git a/internal/reviewexec/scheduling_source_retry_test.go b/internal/reviewexec/scheduling_source_retry_test.go index 550a057ef..021619e17 100644 --- a/internal/reviewexec/scheduling_source_retry_test.go +++ b/internal/reviewexec/scheduling_source_retry_test.go @@ -345,8 +345,10 @@ func TestAutomaticSourceRetryRechecksFencesAfterSourceIO(t *testing.T) { ageSourceRetry(t, f, r.ID) schedulingGenerate(t, f, true) var once sync.Once + edited := false reader := &refreshTestReader{repository: func(context.Context, int64) (reviewprovider.Repository, error) { once.Do(func() { + edited = true switch mode { case "cancelled-operation": raw, err := f.e.Enqueue(t.Context(), selectionScope(t, f, attemptProject, f.writer, "write"), "during-source", Request{ExpectedConfigurationRevision: 1, PullNumber: 2, HeadSHA: strings.Repeat("a", 40), Channel: "hosted"}) @@ -372,8 +374,12 @@ func TestAutomaticSourceRetryRechecksFencesAfterSourceIO(t *testing.T) { return reviewprovider.Repository{ID: 801, FullName: "owner/repo", DefaultBranch: "main"}, nil }} selectionNext(t, f, reader) + if !edited { + t.Fatal("Hosted retry never reached its repository callback") + } + want := map[string]string{"cancelled-operation": "selection_superseded", "scheduling": "automation_authorization_changed", "configuration": "configuration_changed", "policy": "policy_changed"}[mode] got := selectionRead(t, f, r.ID) - if got.State != "held" || got.OperationID != "" { + if got.State != "held" || got.OperationID != "" || got.Reason != want { t.Fatal("changed authority or cancelled successor ignored", got) } expected := 0 diff --git a/internal/reviewexec/scheduling_test.go b/internal/reviewexec/scheduling_test.go index 923dc48e4..f0480ac4b 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -1466,6 +1466,8 @@ func TestValidateSchedulingSnapshotAcceptsSupportedVersions(t *testing.T) { schedulingEnable(t, f, 0, true) if tc.legacyPhysical { admissionSQL(t, f, `ALTER TABLE review_scheduling DROP COLUMN automatic_cli`) + admissionSQL(t, f, `UPDATE events SET payload_json='{"automatic_hosted":true}' + WHERE project_id=? AND event_type='review.scheduling_updated' AND revision=1`, attemptProject) } admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_scheduling'`, tc.version) if err := validateSchedulingSnapshotForTest(t, f); err != nil { From 84eebef50478ca53bf03770fbcd2140c6dcfefa8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 26 Nov 2026 09:25:03 +1300 Subject: [PATCH 38/41] Keep unchanged no-child review settlement on accepted basis --- internal/reviewexec/run_selection_worker.go | 4 ++-- internal/reviewexec/scheduling_automatic.go | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/internal/reviewexec/run_selection_worker.go b/internal/reviewexec/run_selection_worker.go index cc4e42e09..e8854197b 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -766,7 +766,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat // A repository mismatch never proves the sampled comparison. // Keep the accepted basis only; do not stamp any later round // grant or planning facts as served by this read. - if pull == 0 && (reason == "local_read_unavailable" || reason == "repository_changed") { + if pull == 0 && reason == "local_read_unavailable" { settle = false } if settle && pull == 0 && choice.automaticQueueLimit != nil && choice.automaticBasisRevision != 0 { @@ -784,7 +784,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat } } if settle { - resultErr = e.settleAutomaticBasis(ctx, tx, r, pull) + resultErr = e.settleAutomaticBasis(ctx, tx, r, pull, pull == 0 && reason == "repository_changed") } } if automaticProjectRefused(resultErr) { diff --git a/internal/reviewexec/scheduling_automatic.go b/internal/reviewexec/scheduling_automatic.go index 92077cab8..c900b759a 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -672,7 +672,7 @@ func (e *Engine) automaticPullSuppressed(ctx context.Context, tx *sql.Tx, r Run, err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM review_automatic_selections WHERE project_id=? AND selection_id<>? AND pull_number=? AND pull_basis_sha256=?)`, r.ProjectID, r.ID, pull, basis).Scan(&seen) return seen, err } -func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64) error { +func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64, acceptedOnly bool) error { attribution, err := automaticSelectionBinding(ctx, tx, r) if err != nil || attribution.revision == 0 { return err @@ -692,7 +692,13 @@ func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pu 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) + if acceptedOnly { + // A repository mismatch proves no new source facts. Retain the + // original suppression only if the same basis is still current. + _, err = tx.ExecContext(ctx, `UPDATE review_automatic_selections SET settled_basis_sha256=basis_sha256 WHERE selection_id=? AND project_id=? AND basis_sha256=?`, r.ID, r.ProjectID, basis) + } else { + _, 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 } From ae387ec5b2ce3b3a63b414e90c0cbf3ec1aee631 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 23:02:19 +1300 Subject: [PATCH 39/41] Keep final scheduling refusals local and atomic --- internal/reviewexec/front_evaluator.go | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/internal/reviewexec/front_evaluator.go b/internal/reviewexec/front_evaluator.go index f1cc0ea07..501cd6865 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -175,15 +175,9 @@ func (e *Engine) runFront(ctx context.Context, q *sql.Tx, r Run, repo int64, pre 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 - } + // Traverse past local refusals while considering other PRs. A final + // refusal retains the original hold without publishing partial source. + return 0, "", result.localRefusal } return 0, result.reason, nil } From c11eda5ba41637b42e353c13c2ee61c0b6f6f7ac Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 00:06:00 +1300 Subject: [PATCH 40/41] Require completed source history for Hosted continuity --- .../reviewexec/scheduling_source_retry.go | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/internal/reviewexec/scheduling_source_retry.go b/internal/reviewexec/scheduling_source_retry.go index 9b894e832..2b7b481fa 100644 --- a/internal/reviewexec/scheduling_source_retry.go +++ b/internal/reviewexec/scheduling_source_retry.go @@ -3,6 +3,7 @@ package reviewexec import ( "context" "database/sql" + "encoding/json" "errors" "time" ) @@ -153,6 +154,13 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin if r.Channel != "hosted" || r.State == "selected" || r.OperationID != "" || accepted >= current.Revision { return "automation_authorization_changed", nil } + completed, err := verifiedCompletedAutomaticSourceHistory(ctx, tx, r) + if err != nil { + return "", err + } + if !completed { + return "automation_authorization_changed", nil + } generation, err := schedulingAuthorityContinuity(ctx, tx, r.ProjectID, r.ActorID, accepted, current.Revision, true) if err != nil { return "", err @@ -171,6 +179,77 @@ func automaticSourceRecoveryFence(ctx context.Context, tx *sql.Tx, r Run) (strin return "", nil } +// Only a complete canonical source journal distinguishes a completed retry +// from an unproved interrupted read. Settings authority cannot supply that proof. +func verifiedCompletedAutomaticSourceHistory(ctx context.Context, tx *sql.Tx, r Run) (bool, error) { + if r.Revision < 4 || r.Revision > 10000 { + return false, nil + } + acceptance, err := readSelectionRequestedEvent(ctx, tx, r) + if err != nil || acceptance.sequence == 0 || acceptance.Origin != selectionOriginAutomatic { + return false, err + } + rows, err := tx.QueryContext(ctx, `SELECT revision,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 resource_id=? AND (event_type='review.selection_updated' + OR (typeof(event_type)='blob' AND CAST(event_type AS TEXT)='review.selection_updated')) + ORDER BY revision,sequence LIMIT ?`, r.ProjectID, r.ID, r.Revision+1) + if err != nil { + return false, err + } + defer rows.Close() + previous, sequence, next, completed := "queued", acceptance.sequence, int64(2), false + for rows.Next() { + var revision, order, actor any + var eventType string + var body sql.NullString + if err := rows.Scan(&revision, &order, &actor, &eventType, &body); err != nil { + return false, err + } + ord, ok := order.(int64) + if revision != next || next > r.Revision || !ok || ord <= sequence || actor != r.ActorID || eventType != "text" || !body.Valid { + return false, nil + } + var event struct { + Reason string `json:"reason"` + State string `json:"state"` + } + if json.Unmarshal([]byte(body.String), &event) != nil || encoded(event) != body.String { + return false, nil + } + switch event.State { + case "selecting": + if previous != "queued" || event.Reason != "" { + return false, nil + } + case "queued": + if (previous != "selecting" && previous != "held") || event.Reason != "" { + return false, nil + } + case "held": + if previous != "selecting" { + return false, nil + } + switch event.Reason { + case "source_budget_exhausted", "source_fetch_timeout", "source_provider_unavailable", "routed_findings_unavailable": + completed = true + default: + return false, nil + } + default: + return false, nil + } + if next == r.Revision && (event.State != r.State || event.Reason != r.Reason) { + return false, nil + } + previous, sequence, next = event.State, ord, next+1 + } + if err := rows.Err(); err != nil { + return false, err + } + return completed && next == r.Revision+1, 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. From 1240468487b76aa950551644ec50b97322de68f4 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 30 Nov 2026 01:51:11 +1300 Subject: [PATCH 41/41] Retain exact historical Hosted cooldown without admitting work --- internal/reviewexec/hosted_preflight.go | 34 ++++- internal/reviewexec/policy_admission.go | 60 ++++++++- internal/reviewexec/preparation_recovery.go | 18 ++- .../hosted_cooldown_retry_test.go | 116 +++++++++++++++++- internal/reviewruntime/hosted_preflight.go | 11 +- 5 files changed, 225 insertions(+), 14 deletions(-) diff --git a/internal/reviewexec/hosted_preflight.go b/internal/reviewexec/hosted_preflight.go index ca79f5954..fd96d8768 100644 --- a/internal/reviewexec/hosted_preflight.go +++ b/internal/reviewexec/hosted_preflight.go @@ -89,7 +89,7 @@ func (e *Engine) RecordHostedAllowance(ctx context.Context, project, attemptID s if !validHostedAllowanceInput(input) { return invalid() } - return e.recordHostedAllowance(ctx, project, attemptID, expectedRevision, input) + return e.recordHostedAllowance(ctx, project, attemptID, expectedRevision, input, "") } // RecordHostedCooldown retains attributed cooldown facts, never positive admission. @@ -97,10 +97,27 @@ func (e *Engine) RecordHostedCooldown(ctx context.Context, project, attemptID st if input.Observation.State != "cooldown_observed" { return invalid() } - return e.recordHostedAllowance(ctx, project, attemptID, expectedRevision, input) + return e.recordHostedAllowance(ctx, project, attemptID, expectedRevision, input, "") } -func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID string, expectedRevision int64, input HostedAllowanceInput) error { +// RetainRecoveredHostedCooldown is an exact negative-only recovery write. +// Only Engine's private startup callback can supply the original custody +// binding. Other callers keep the ordinary retention checks. +func (e *Engine) RetainRecoveredHostedCooldown(ctx context.Context, project, attemptID string, expectedRevision int64, input HostedAllowanceInput) error { + if ctx == nil || input.Observation.State != "cooldown_observed" { + return invalid() + } + custody, ok := ctx.Value(hostedPreparationRecoveryKey{}).(hostedPreparationRecovery) + if !ok { + return e.RecordHostedCooldown(ctx, project, attemptID, expectedRevision, input) + } + if custody.engine != e || custody.project != project || custody.attempt != attemptID || custody.revision != expectedRevision || custody.operation == "" { + return conflict() + } + return e.recordHostedAllowance(ctx, project, attemptID, expectedRevision, input, custody.operation) +} + +func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID string, expectedRevision int64, input HostedAllowanceInput, recoveryOperation string) error { if ctx == nil || e == nil || e.store == nil || !identifier.MatchString(project) || !hostedObservationID(attemptID, "review_attempt_") || expectedRevision != 1 || !validHostedAllowanceObservation(input) { return invalid() } @@ -114,6 +131,15 @@ func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID s return invalid() } return e.store.BackgroundWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if recoveryOperation != "" { + a, err := readAttempt(ctx, tx, project, attemptID) + if err != nil { + return err + } + if a.OperationID != recoveryOperation { + return conflict() + } + } 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 err == nil { @@ -179,7 +205,7 @@ func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID s if query.ID != owned.QueryID || query.Comment == nil || query.Comment.ID != observation.QueryCommentID || !query.Comment.CreatedAt.Equal(observation.QueryCreatedAt) || !hostedAllowanceSameSource(query.Anchor, owned.Anchor) { return conflict() } - current, err := e.executionContext(ctx, tx, operation, observation.State == "cooldown_observed") + current, err := e.executionContextForRetention(ctx, tx, operation, observation.State == "cooldown_observed", recoveryOperation != "") if err != nil { return err } diff --git a/internal/reviewexec/policy_admission.go b/internal/reviewexec/policy_admission.go index 74dbea265..077fc8b9b 100644 --- a/internal/reviewexec/policy_admission.go +++ b/internal/reviewexec/policy_admission.go @@ -52,12 +52,30 @@ func (e *Engine) currentExecutionContext(ctx context.Context, tx *sql.Tx, operat // A cooldown is retained negative evidence, not admission. Project pause may // delay its retry without discarding it; all other authority checks still apply. func (e *Engine) executionContext(ctx context.Context, tx *sql.Tx, operation Operation, retainCooldown bool) (ExecutionContext, error) { + return e.executionContextForRetention(ctx, tx, operation, retainCooldown, false) +} + +func (e *Engine) executionContextForRetention(ctx context.Context, tx *sql.Tx, operation Operation, retainCooldown, recoverCooldown bool) (ExecutionContext, error) { + recoverCooldown = recoverCooldown && retainCooldown && operation.Channel == "hosted" + acceptsNegativeHold := func(err error, code string) bool { + var failure *core.Error + return recoverCooldown && errors.As(err, &failure) && failure.Code == code + } result := ExecutionContext{Operation: operation} - if err := requirePullScheduling(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil { + if err := requirePullScheduling(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil && !acceptsNegativeHold(err, "pull_scheduling_paused") { return ExecutionContext{}, err } if err := e.requireAutomaticOperation(ctx, tx, operation); err != nil { - return ExecutionContext{}, err + if !acceptsNegativeHold(err, "automation_authorization_changed") { + return ExecutionContext{}, err + } + disabled, proofErr := provedHostedAutomaticDisableForCooldown(ctx, tx, operation) + if proofErr != nil { + return ExecutionContext{}, proofErr + } + if !disabled { + return ExecutionContext{}, err + } } if err := requireSourceObligationsClear(ctx, tx, operation.ProjectID, operation.PullNumber); err != nil { return ExecutionContext{}, err @@ -114,6 +132,44 @@ func (e *Engine) executionContext(ctx context.Context, tx *sql.Tx, operation Ope return result, nil } +// A valid later settings event explicitly disabling automatic Hosted is +// negative scheduling evidence, not a new grant. Never reinterpret a missing, +// structurally inconsistent or merely unproved authorization as this case. +func provedHostedAutomaticDisableForCooldown(ctx context.Context, tx *sql.Tx, operation Operation) (bool, error) { + var id string + err := tx.QueryRowContext(ctx, `SELECT id FROM review_selections WHERE project_id=? AND operation_id=?`, + operation.ProjectID, operation.ID).Scan(operationValue(&id)) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + r, err := readRun(ctx, tx, operation.ProjectID, id) + if err != nil { + return false, err + } + if r.Channel != "hosted" || r.State != "selected" || r.OperationID != operation.ID || + r.ActorID != operation.ActorID || r.WorkerID != operation.WorkerID { + return false, nil + } + attribution, err := automaticSelectionBinding(ctx, tx, r) + if err != nil || attribution.revision == 0 { + return false, err + } + current, err := readScheduling(ctx, tx, operation.ProjectID) + if err != nil { + return false, err + } + if current.AutomaticHosted || current.Revision <= attribution.revision { + return false, nil + } + if _, _, err := schedulingBasisRevisions(ctx, tx, current); err != nil { + return false, err + } + return true, nil +} + // readAdmission uses one finite read-only snapshot without retaining credentials // or changing any journal state. These methods are for trusted in-process use. func (e *Engine) readAdmission(ctx context.Context, read func(context.Context, *sql.Tx) error) error { diff --git a/internal/reviewexec/preparation_recovery.go b/internal/reviewexec/preparation_recovery.go index 5f25a46b9..56adeb57b 100644 --- a/internal/reviewexec/preparation_recovery.go +++ b/internal/reviewexec/preparation_recovery.go @@ -15,6 +15,14 @@ func (e *PreparationRecoveryError) Error() string { } func (e *PreparationRecoveryError) Unwrap() error { return e.Err } +type hostedPreparationRecoveryKey struct{} + +type hostedPreparationRecovery struct { + engine *Engine + project, operation, attempt string + revision int64 +} + type preparationRecoveryDriver interface { RecoverPreparation(context.Context, Operation, Attempt) error } @@ -87,7 +95,15 @@ func (e *Engine) reconcilePreparingDrivers(ctx context.Context, drivers map[stri } if driver, ok := drivers[key].(preparationRecoveryDriver); ok { replayed = true - if err := driver.RecoverPreparation(ctx, o, a); err != nil { + recoveryCtx, cancelRecovery := context.WithCancel(ctx) + if id.hasRecoveryEvidence { + recoveryCtx = context.WithValue(recoveryCtx, hostedPreparationRecoveryKey{}, hostedPreparationRecovery{ + engine: e, project: o.ProjectID, operation: o.ID, attempt: a.ID, revision: a.Revision, + }) + } + err := driver.RecoverPreparation(recoveryCtx, o, a) + cancelRecovery() + if err != nil { return nil, err } } diff --git a/internal/reviewruntime/hosted_cooldown_retry_test.go b/internal/reviewruntime/hosted_cooldown_retry_test.go index c0a5764d5..c1226f4b8 100644 --- a/internal/reviewruntime/hosted_cooldown_retry_test.go +++ b/internal/reviewruntime/hosted_cooldown_retry_test.go @@ -2,8 +2,10 @@ package reviewruntime import ( "context" + "database/sql" "encoding/json" "errors" + "net/http/httptest" "os" "os/exec" "path/filepath" @@ -379,11 +381,82 @@ func TestHostedCooldownRetentionRetriesOnlyStorageFailures(t *testing.T) { } } +// Only credentials and worker are synthetic fixture setup. The review +// selection, child and grant are authored through the normal scheduling APIs. +func startOrdinaryAutomaticHostedCooldown(t *testing.T, f *hostedDriverFixture) (reviewexec.Operation, reviewexec.Attempt, reviewexec.Configuration, core.Scope) { + t.Helper() + const worker = "cooldown-recovery-worker" + if _, err := f.store.DB().Exec(`INSERT INTO workers(project_id,id,name) VALUES(?,?,?); + UPDATE grants SET can_manage=1 WHERE project_id=? AND credential_id='runtime-evidence-writer'`, f.project, worker, worker, f.project); err != nil { + t.Fatal(err) + } + r := httptest.NewRequest("POST", "/", nil) + r.SetPathValue("project_id", f.project) + r.Header.Set("Authorization", "Bearer "+f.writer) + r.Header.Set("X-FC-Worker", worker) + scope, err := f.store.Scope(r, "write") + if err != nil { + t.Fatal(err) + } + zero, enabled := int64(0), true + if _, err := f.engine.ConfigureScheduling(t.Context(), scope, "recover-auto-enable", reviewexec.SchedulingRequest{ExpectedRevision: &zero, AutomaticHosted: &enabled}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + done, err := f.engine.StartReviewRuns(ctx, map[string]reviewexec.TargetReader{f.capability.ID: f.reader}) + if err != nil { + t.Fatal(err) + } + timer := time.NewTicker(10 * time.Millisecond) + defer timer.Stop() + var opID string + for opID == "" { + err = f.store.DB().QueryRowContext(ctx, `SELECT o.id FROM review_operations o JOIN review_selections s ON s.operation_id=o.id + JOIN review_automatic_selections a ON a.selection_id=s.id + WHERE o.project_id=? AND o.pull_number=2 AND o.channel='hosted' AND o.state='queued'`, f.project).Scan(&opID) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + t.Fatal(err) + } + if opID != "" { + break + } + select { + case err := <-done: + t.Fatal("automatic selector stopped", err) + case <-ctx.Done(): + t.Fatal("automatic scheduler did not author a linked operation") + case <-timer.C: + } + } + cancel() + if err := <-done; err != nil { + t.Fatal(err) + } + attempt, err := f.engine.StartAttempt(t.Context(), f.project, opID) + if err != nil || attempt.ID == "" { + t.Fatal("automatic attempt was not claimed", err) + } + current, err := f.engine.ExecutionContext(t.Context(), f.project, opID) + if err != nil { + t.Fatal(err) + } + return current.Operation, attempt, current.Configuration, scope +} + func TestHostedCooldownRetentionOutageRecoversOriginalAttemptOffline(t *testing.T) { - for _, damage := range []string{"none", "clock-boundary", "missing-capture", "malformed-capture", "workspace", "operational-workspace", "operational-query", "project-pause", "project-pause-source-changed", "observation"} { + for _, damage := range []string{"none", "clock-boundary", "missing-capture", "malformed-capture", "workspace", "operational-workspace", "operational-query", "project-pause", "pull-pause", "automatic-disable", "project-pause-source-changed", "observation"} { t.Run(damage, func(t *testing.T) { f, _ := newHostedCooldownRetryFixture(t) - operation, attempt, config := f.startHosted(t) + var operation reviewexec.Operation + var attempt reviewexec.Attempt + var config reviewexec.Configuration + var managed core.Scope + if damage == "automatic-disable" { + operation, attempt, config, managed = startOrdinaryAutomaticHostedCooldown(t, f) + } else { + operation, attempt, config = f.startHosted(t) + } if damage == "clock-boundary" { f.hosted.provider.(*cooldownRetryProvider).postedAt = func() time.Time { query, err := f.engine.ReadHostedAllowanceQuery(t.Context(), f.project, attempt.ID) @@ -514,6 +587,27 @@ func TestHostedCooldownRetentionOutageRecoversOriginalAttemptOffline(t *testing. t.Fatal(err) } } + if damage == "pull-pause" { + zero, paused := int64(0), true + if _, err := f.engine.ConfigurePullScheduling(t.Context(), f.scope(t, f.writer, false), "recovery-pull-pause", operation.PullNumber, + reviewexec.PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused, Reason: "Ordinary pause during retention"}); err != nil { + t.Fatal(err) + } + if _, err := f.engine.ExecutionContext(t.Context(), operation.ProjectID, operation.ID); err == nil { + t.Fatal("ordinary preparation unexpectedly admitted a paused pull") + } + } + if damage == "automatic-disable" { + one, disabled := int64(1), false + if _, err := f.engine.ConfigureScheduling(t.Context(), managed, "recover-auto-disable", + reviewexec.SchedulingRequest{ExpectedRevision: &one, AutomaticHosted: &disabled}); err != nil { + t.Fatal(err) + } + var refusal *core.Error + if _, err := f.engine.ExecutionContext(t.Context(), operation.ProjectID, operation.ID); !errors.As(err, &refusal) || refusal.Code != "automation_authorization_changed" { + t.Fatal("ordinary preparation no longer refused disabled automatic eligibility", err) + } + } before := []int{f.provider.queries, f.provider.reviews, f.provider.histories, f.reader.repositoryCalls} for pass := 0; pass < 2; pass++ { ctx, cancel := context.WithCancel(t.Context()) @@ -530,10 +624,26 @@ func TestHostedCooldownRetentionOutageRecoversOriginalAttemptOffline(t *testing. if err != nil || got.ID != operation.ID { t.Fatal("request identity changed", got, err) } - if damage == "none" || damage == "clock-boundary" || damage == "project-pause" { + if damage == "none" || damage == "clock-boundary" || damage == "project-pause" || damage == "pull-pause" || damage == "automatic-disable" { if got.State != "queued" || got.Wait == nil || got.Wait.BaselineAttemptID != attempt.ID || got.Wait.RetryNotBefore == "" { t.Fatal("original cooldown not recovered", got) } + if damage == "pull-pause" || damage == "automatic-disable" { + var body []byte + err := f.store.DB().QueryRow(`SELECT body_json FROM review_hosted_preflight WHERE project_id=? AND attempt_id=?`, operation.ProjectID, attempt.ID).Scan(&body) + var stored struct { + Input reviewexec.HostedAllowanceInput `json:"input"` + } + if err != nil || json.Unmarshal(body, &stored) != nil || stored.Input.Observation.State != "cooldown_observed" || + got.Wait.RetryNotBefore != stored.Input.Observation.RetryNotBefore.Format(time.RFC3339Nano) || + cliCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 || + cliCount(t, f.store, `SELECT count(*) FROM review_execution_evidence`) != 0 { + t.Fatal("negative custody invented authority or changed timer", err) + } + if _, err := f.engine.ExecutionContext(t.Context(), operation.ProjectID, operation.ID); err == nil { + t.Fatal("recovering the timer admitted ordinary preparation") + } + } } else if got.State != "cancelled" || cliCount(t, f.store, `SELECT count(*) FROM review_hosted_preflight`) != 0 { t.Fatal("unproven recovery retained cooldown", got) } diff --git a/internal/reviewruntime/hosted_preflight.go b/internal/reviewruntime/hosted_preflight.go index a61b73585..e7d6d26ae 100644 --- a/internal/reviewruntime/hosted_preflight.go +++ b/internal/reviewruntime/hosted_preflight.go @@ -15,14 +15,14 @@ import ( // source rather than trusting a caller's parsed availability. It records no // review completion, provider action, attempt transition or execution permit. func RetainHostedAllowance(ctx context.Context, captures *HostedCaptureStore, engine *reviewexec.Engine, attempt reviewexec.Attempt, anchor reviewexec.Anchor, changedFiles int64, reference CaptureReference) error { - return retainHostedAllowance(ctx, captures, engine, attempt, anchor, changedFiles, reference, false) + return retainHostedAllowance(ctx, captures, engine, attempt, anchor, changedFiles, reference, false, false) } func RetainHostedCooldown(ctx context.Context, captures *HostedCaptureStore, engine *reviewexec.Engine, attempt reviewexec.Attempt, anchor reviewexec.Anchor, changedFiles int64, reference CaptureReference) error { - return retainHostedAllowance(ctx, captures, engine, attempt, anchor, changedFiles, reference, true) + return retainHostedAllowance(ctx, captures, engine, attempt, anchor, changedFiles, reference, true, false) } -func retainHostedAllowance(ctx context.Context, captures *HostedCaptureStore, engine *reviewexec.Engine, attempt reviewexec.Attempt, anchor reviewexec.Anchor, changedFiles int64, reference CaptureReference, cooldown bool) error { +func retainHostedAllowance(ctx context.Context, captures *HostedCaptureStore, engine *reviewexec.Engine, attempt reviewexec.Attempt, anchor reviewexec.Anchor, changedFiles int64, reference CaptureReference, cooldown, recovery bool) error { if ctx == nil || captures == nil || engine == nil || !validHostedReference(reference) { return core.Fail("validation_failed", "Use the preparing hosted attempt and its private query capture.", 400) } @@ -76,6 +76,9 @@ func retainHostedAllowance(ctx context.Context, captures *HostedCaptureStore, en } input := reviewexec.HostedAllowanceInput{QueryID: query.ID, Anchor: anchor, ObservedAt: record.Snapshot.ObservedAt.Format(time.RFC3339Nano), ChangedFiles: changedFiles, CaptureID: reference.ID, CaptureSHA256: reference.SHA256, CaptureBytes: reference.Bytes, Observation: observation} + if cooldown && recovery { + return engine.RetainRecoveredHostedCooldown(ctx, attempt.ProjectID, attempt.ID, attempt.Revision, input) + } if cooldown { return engine.RecordHostedCooldown(ctx, attempt.ProjectID, attempt.ID, attempt.Revision, input) } @@ -178,7 +181,7 @@ func (d *HostedDriver) RecoverPreparation(ctx context.Context, operation reviewe } return nil } - err = RetainHostedCooldown(ctx, d.captures, d.engine, attempt, anchor, int64(len(files)), reference) + err = retainHostedAllowance(ctx, d.captures, d.engine, attempt, anchor, int64(len(files)), reference, true, true) if retryableHostedRetention(err) || ctx.Err() != nil { return err }