diff --git a/docs/README.md b/docs/README.md index 6632d7bf..212d9efa 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,7 +41,7 @@ The [Hosted source foundation](delivery.md#hosted-source-foundation) records the - [Hosted capacity settlement](hosted-settlement.md): guarded administrator recovery after verified external termination, preserving evidence and preventing automatic reposts. - [Per-PR review rounds](review-round-controls.md): explicit native grants, close, taper, cumulative accounting and bound-client contracts. - [Retained review operations](review-operations.md): provider-free discovery, compact status and original Hosted observer diagnostics. -- [Review scheduling](review-scheduling.md): per-PR pauses, accepted review work and retained-state recovery. +- [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/review-scheduling.md b/docs/review-scheduling.md index 0482ea3e..a00d8bfc 100644 --- a/docs/review-scheduling.md +++ b/docs/review-scheduling.md @@ -1,33 +1,91 @@ # Review scheduling +## Source-slice boundary + +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 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 + +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 CLI intent crossing a scheduling revision additionally needs the same explicit, writer-owned CLI basis in every revision. An unrelated-channel edit can preserve that basis; a missing basis or an authorizer change followed by a change back cannot prove CLI continuity. 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. 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`, `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 for CLI and for legacy Hosted history. A completed, unselected Hosted retry can survive an unrelated-channel edit only when paired durable settings events prove the same scheduling-authorizer binding, uninterrupted Hosted enablement and the same Hosted lane basis. This is not a history of credential activation or grants; current authorization is checked independently. Changing the authorizer, withdrawing or rearming Hosted, or missing proof requires a new authorization under ordinary scheduling rules. Already-linked work keeps its established checks. 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 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. + ## Pause a PR -A project writer can pause new reviews for a PR before its first review intent or while it has queued work. The pause covers undispatched Hosted and CLI work. It preserves accepted operation identities and their cooldown deadlines, and collection of an already issued review can continue. An optional reason explains the pause. Resuming clears that reason. +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. When the owned CLI driver observes a pause at its final local check before starting the review process, it can retain the original request using an attempt-bound no-start receipt. It releases the exact unused reservation and keeps the prior attempt as history. Resume takes the ordinary admission path with a new attempt; an issued action or uncertain outcome never uses this automatic path. -Draft eligibility, [round settings](review-round-controls.md), earned taper, channel closure and operation controls remain separate. To resume an individually paused operation, use its [operation control](retained-review-quota-controls.md). +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 -Use `GET` and `POST /api/v1/projects/{project_id}/reviews/pulls/{number}/scheduling` to read or update the pause. A write supplies `expected_revision`, `paused` and an optional `reason`, with the normal explicit idempotency key. An unconfigured PR reads as revision zero and unpaused. Keep the original request and key when a mutation result is uncertain. +These scheduling commands and tools require the dependent client slice. The backend slice exposes the scheduling HTTP API. -Project scheduling is read-only. `GET /api/v1/projects/{project_id}/reviews/scheduling` shows the retained revision, settings, authorizing worker and pauses for currently queued PRs. It reports unavailable authorization and provider holds without exposing credentials. The per-PR read can find controls outside the queue. +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. -## Accepted work +```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, 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 pending operation without a retained selection link is eligible as a direct request only when the exact public enqueue receipt matches its original project, principal, worker, configuration revision, channel, pull request, and head. The same rule applies when counting a direct request as a queue fence. If neither a valid selection link nor a direct receipt establishes origin, the controller does not admit the operation as direct. This requirement does not change settled history or recovery of already-admitted work. -Explicit selection uses the existing durable queue. Automatic origin in retained state requires matching attribution, an authorized original worker and complete relevant scheduling history. Queued or selecting work retains its original authorizer. An already selected operation can retain that original authorizer through a manager change when both authorizers remain valid and the intervening history proves continuous enablement of its channel. Missing or conflicting attribution and ambiguous legacy selections hold for operator investigation. Legacy explicit origin can be proven by an exact retained mutation receipt, a caller-supplied PR pin or complete history from before automatic scheduling for that channel. +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. 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. -Current queued diagnostics identify an earlier accepted Hosted request before the later request's independent cooldown. The bounded local read uses compatible active queue and quota bindings. A paused, cancelled or invalid earlier request releases that turn. CLI shared-account quota diagnostics retain the original deadline while the accepted account and current configuration still agree. +## Validation -Version 5 of `X-FC-Operation-Wait` extends version 3 with optional `queue_ahead_pull_number` in the round-progress read. Older response versions omit it. It reports the accepted predecessor without changing allowance or deadlines. +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. -## Backup and restore +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. -Backups retain scheduling settings, PR pauses, acceptance events and automatic attribution. Inspection checks their consistency. Older bundles may omit the optional domain. Version-one Hosted-only settings migrate with automatic CLI off. Restore lands in an inactive destination with provider execution held. Historical authorizers remain evidence after revocation or retirement. +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. -A legacy bundle can omit a PR control when its unique latest canonical event proves an unpaused resume. Restore retains that event's actor, revision and time in the destination control and preserves the journal. A missing paused control or ambiguous history blocks restore. +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. -A linked selection with proven custody retains its original child identifier and observed revision in a diagnostic record. Quarantine preserves the child, authorizer, retained evidence and any existing provider action. A held child cannot obtain new admission or reserve a queued turn. Ambiguous provenance holds for investigation. +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. The active selection custody migration is forward-only. Before upgrading, retain a verified rollback backup whose `review_selection` schema is version 1. For binary rollback, restore that bundle to a separate inactive destination and use the [backup recovery procedure](backups.md). Backups containing `review_selection` schema version 2 require compatible readers and retain custody records pending an explicit retention policy. The selection schema version is independent of the bundle manifest version. diff --git a/internal/backup/review_selection_test.go b/internal/backup/review_selection_test.go index fb81a258..1df82219 100644 --- a/internal/backup/review_selection_test.go +++ b/internal/backup/review_selection_test.go @@ -391,6 +391,59 @@ func TestSelectionQuarantineInventoryRefusesV1NameCollision(t *testing.T) { 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) + } + 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) { f, _ := selectionInventoryFixture(t, "queued") bundle := restoreBundle(t, f) diff --git a/internal/backup/scheduling_test.go b/internal/backup/scheduling_test.go index 4269f00c..79adbdf3 100644 --- a/internal/backup/scheduling_test.go +++ b/internal/backup/scheduling_test.go @@ -3,70 +3,137 @@ 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" ) -func TestSchedulingBackupRetainsCanonicalProjectRow(t *testing.T) { +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) - // Model previously accepted settings in the native schema. The foundation - // has no project write path and this fixture does not synthesize a selection. - if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - var credential string - if err := tx.QueryRowContext(ctx, `SELECT id FROM credentials WHERE principal_id=? AND is_admin=1`, f.principal).Scan(&credential); err != nil { - return err - } - at := time.Now().UTC().Format(time.RFC3339Nano) - if _, err := tx.ExecContext(ctx, `INSERT INTO review_scheduling - (project_id,revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at) - VALUES(?,1,1,0,?,?,?,?)`, f.project, f.principal, f.worker, credential, at); err != nil { - return err - } - _, err := tx.ExecContext(ctx, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) - VALUES(?,'review.scheduling_updated',?,1,?,'{"automatic_hosted":true,"automatic_cli":false,"hosted_basis_revision":1,"cli_basis_revision":1}',?)`, f.project, f.project, f.principal, at) - if err != nil { - return err + 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) } - _, err = tx.ExecContext(ctx, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) - VALUES(?,'review.scheduling_authority_bound',?,1,?,'{"generation":1}',?)`, f.project, f.project, f.principal, at) - return err - }); err != nil { + 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) } - const controls = `SELECT * FROM review_scheduling` - const journal = `SELECT * FROM events WHERE event_type IN ('review.scheduling_updated','review.scheduling_authority_bound') ORDER BY sequence` - wantControls, wantJournal := restoreRows(t, f.store.DB(), controls), restoreRows(t, f.store.DB(), journal) + 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`) + } + rows["authority_journal"] = restoreRows(t, db, `SELECT * FROM events WHERE event_type IN + ('review.scheduling_updated','review.scheduling_authority_bound') ORDER BY sequence`) + 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-project-scheduling") + destination := filepath.Join(t.TempDir(), "inactive-scheduling") if _, err := Restore(t.Context(), bundle.Path, destination); err != nil { t.Fatal(err) } - store, err := core.Open(t.Context(), destination) + restored, err := core.Open(t.Context(), destination) if err != nil { t.Fatal(err) } - defer store.Close() - status, err := ReadRecoveryStatus(t.Context(), store) + 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("restored settings unlocked provider work", status, err) + t.Fatal("restore enabled provider work", status, err) } - for _, db := range []*sql.DB{store.DB(), f.store.DB()} { - if !reflect.DeepEqual(wantControls, restoreRows(t, db, controls)) || !reflect.DeepEqual(wantJournal, restoreRows(t, db, journal)) { - t.Fatal("backup/restore changed prior scheduling authority") - } + backupCode(t, StartupGuard(t.Context(), restored), "restore_inactive") + tx, err := restored.DB().BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) } - if !reflect.DeepEqual(immutable, restoreTree(t, bundle.Path)) { - t.Fatal("restore changed the validated bundle") + 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 TestSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T) { @@ -150,24 +217,213 @@ func testSchedulingRestorePreservesHistoricalPullResumeRevision(t *testing.T, ve if !reflect.DeepEqual(sourceControls, restoreRows(t, f.store.DB(), controls)) || !reflect.DeepEqual(immutable, restoreTree(t, bundle.Path)) { t.Fatal("restore mutated source controls or validated bundle") } - // The same valid retained resume supplies the live CAS basis before - // an offline restore materializes its projection. - recovered, err := e.ReadPullScheduling(t.Context(), scope, 4) - if err != nil || recovered.Revision != 2 || recovered.Paused { - t.Fatal("legacy resume did not provide its live CAS revision", recovered, err) + current, err := e.ReadPullScheduling(t.Context(), scope, 4) + if err != nil || current.Revision != 2 || current.Paused { + t.Fatal("legacy resume lost its CAS revision", current, err) } if _, err := e.ConfigurePullScheduling(t.Context(), scope, "stale-legacy-pause", 4, reviewexec.PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused, Reason: "Fixture pause"}); err == nil { t.Fatal("legacy resume incorrectly allowed a revision-zero overwrite") } two := int64(2) - if _, err := e.ConfigurePullScheduling(t.Context(), scope, "next-legacy-pause", 4, - reviewexec.PullSchedulingRequest{ExpectedRevision: &two, Paused: &paused, Reason: "Fixture pause"}); err != nil { - t.Fatal("legacy CAS could not materialize a legitimate pause", err) + if _, err := e.ConfigurePullScheduling(t.Context(), scope, "live-pause-after-resume", 4, + reviewexec.PullSchedulingRequest{ExpectedRevision: &two, Paused: &paused, Reason: "Fixture pause again"}); err != nil { + t.Fatal(err) + } + current, err = e.ReadPullScheduling(t.Context(), scope, 4) + if err != nil || current.Revision != 3 || !current.Paused { + t.Fatal("live update did not extend retained journal", current, err) + } + tx, err := f.store.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("legitimate next revision failed snapshot verification", err) + } +} + +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() + 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 { + 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'`}, + {"deleted-active-domain", `DROP TABLE review_automatic_selections; DROP TABLE review_pull_scheduling; DROP TABLE review_scheduling; 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`}, + {"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)`}, + {"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. + predecessor := newRestoreFixture(t) + selectionInventoryEngine(t, predecessor.store) + // No scheduling control or automatic selection has ever been accepted. + old := schedulingBundleCopy(t, restoreBundle(t, predecessor).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) } - control, err := e.ReadPullScheduling(t.Context(), scope, 4) - if err != nil || control.Revision != 3 || !control.Paused { - t.Fatal("legacy CAS did not create its next pause", control, err) + 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/reviewexec/attempts.go b/internal/reviewexec/attempts.go index f30015bf..63406b4f 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) @@ -164,8 +168,13 @@ 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 { + 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/front_evaluator.go b/internal/reviewexec/front_evaluator.go index 8154d73f..3face436 100644 --- a/internal/reviewexec/front_evaluator.go +++ b/internal/reviewexec/front_evaluator.go @@ -181,15 +181,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 } diff --git a/internal/reviewexec/front_frame.go b/internal/reviewexec/front_frame.go index f972b678..66390dd0 100644 --- a/internal/reviewexec/front_frame.go +++ b/internal/reviewexec/front_frame.go @@ -9,6 +9,7 @@ import ( "slices" "time" + "github.com/benhook1013/FireController/internal/reviewprovider" "github.com/benhook1013/FireController/internal/strictjson" ) @@ -35,6 +36,13 @@ type frontFrame struct { 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 diff --git a/internal/reviewexec/hosted_control_batch_regression_test.go b/internal/reviewexec/hosted_control_batch_regression_test.go index 87031157..05a524ca 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) @@ -150,7 +160,7 @@ func TestContinuityValidatesCurrentBasisAndNativeProjectActor(t *testing.T) { } current := schedulingRecord{Scheduling: Scheduling{ProjectID: "test-project", Revision: 2, AutomaticHosted: true}, actor: "test-actor"} ok, err := automaticChannelContinuous(t.Context(), tx, Run{ProjectID: "test-project", Channel: "hosted", State: "selected", OperationID: "review_operation_legacy"}, 1, "test-actor", current) - if ok != tc.valid || tc.valid != (err == nil) { + if ok != tc.valid || err != nil { t.Fatalf("continuity: got %v %v; expected valid=%v", ok, err, tc.valid) } if tc.name == "legacy-hosted" { diff --git a/internal/reviewexec/hosted_preflight.go b/internal/reviewexec/hosted_preflight.go index ad899d9d..fd96d876 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 { @@ -132,7 +158,11 @@ func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID s if err != nil { return err } - operation, err = historicalHostedAllowanceOperation(ctx, tx, operation, attempt, retained.Input.Observation.State == "available_observed") + if retained.Input.Observation.State == "available_observed" { + operation, err = historicalHostedRetainedReadOperation(ctx, tx, operation, attempt) + } else { + operation, err = historicalCooldownOperation(ctx, tx, operation, attempt) + } if err != nil { return err } @@ -175,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 } @@ -212,15 +242,16 @@ func (e *Engine) recordHostedAllowance(ctx context.Context, project, attemptID s }) } -// Historical positive allowance is an exact read or replay, never live authority. -func historicalHostedAllowanceOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt, positive bool) (Operation, error) { - if positive && o.Channel == "hosted" && o.AttemptID != a.ID { - historical, unused, err := historicalUnusedPreparationOperation(ctx, q, o, a, true) +// Historical recovery reads may attribute the old allowance to its original +// paused attempt. This operation shape must not be used as action authority. +func historicalHostedRetainedReadOperation(ctx context.Context, q EvidenceQuery, o Operation, a Attempt) (Operation, error) { + if o.Channel == "hosted" && o.AttemptID != a.ID { + original, unused, err := historicalUnusedPreparationOperation(ctx, q, o, a, true) if err != nil { return Operation{}, err } - if unused && historical.Reason == "pull_scheduling_paused" { - return historical, nil + if unused && original.Reason == "pull_scheduling_paused" { + return original, nil } } return historicalCooldownOperation(ctx, q, o, a) @@ -247,7 +278,11 @@ func readHostedAllowance(ctx context.Context, tx *sql.Tx, project, attemptID str if err != nil { return record, attempt, operation, err } - operation, err = historicalHostedAllowanceOperation(ctx, tx, operation, attempt, retainedRead && record.Input.Observation.State == "available_observed") + if retainedRead && record.Input.Observation.State == "available_observed" { + operation, err = historicalHostedRetainedReadOperation(ctx, tx, operation, attempt) + } else { + operation, err = historicalCooldownOperation(ctx, tx, operation, attempt) + } if err != nil { return record, attempt, operation, err } diff --git a/internal/reviewexec/hosted_preflight_test.go b/internal/reviewexec/hosted_preflight_test.go index d16e89cc..3df62c60 100644 --- a/internal/reviewexec/hosted_preflight_test.go +++ b/internal/reviewexec/hosted_preflight_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/benhook1013/FireController/internal/core" "github.com/benhook1013/FireController/internal/reviewprovider" ) @@ -50,6 +51,37 @@ func hostedAllowanceRead(t *testing.T, f *attemptFixture, a Attempt) (hostedAllo return record, body } +func TestHostedAllowanceReadsOriginalAfterOrdinaryPauseAndResume(t *testing.T) { + f, old, query, input := hostedAllowanceFixture(t) + if err := f.e.RecordHostedAllowance(t.Context(), attemptProject, old.ID, old.Revision, input); err != nil { + t.Fatal(err) + } + scope := f.scope(t, attemptProject, f.writer, false) + setPaused := func(revision int64, paused bool) { + t.Helper() + if _, err := f.e.ConfigurePullScheduling(t.Context(), scope, core.NewID("pause"), 2, PullSchedulingRequest{ExpectedRevision: &revision, Paused: &paused, Reason: "Fix in progress"}); err != nil { + t.Fatal(err) + } + } + setPaused(0, true) + if _, err := f.e.Advance(t.Context(), attemptProject, old.ID, old.Revision, "held", "pull_scheduling_paused", ""); err != nil { + t.Fatal(err) + } + setPaused(1, false) + next := f.start(t, attemptProject, Receipt{ID: old.OperationID}) + if next.ID == old.ID { + t.Fatal("ordinary resume did not acquire a separate attempt") + } + retainedQuery, err := f.e.ReadHostedAllowanceQuery(t.Context(), attemptProject, old.ID) + if err != nil || !reflect.DeepEqual(retainedQuery, query) { + t.Fatalf("retained query changed after resume: %v", err) + } + retainedInput, err := f.e.ReadHostedAllowance(t.Context(), attemptProject, old.ID) + if err != nil || !reflect.DeepEqual(retainedInput, input) { + t.Fatalf("retained allowance changed after resume: %v", err) + } +} + func TestHostedAllowanceRecordOriginalBindingReplayAndNoAdmission(t *testing.T) { f, a, q, in := hostedAllowanceFixture(t) before, receipts := attemptState(t, f, a), attemptCount(t, f.store, `SELECT count(*) FROM receipts`) diff --git a/internal/reviewexec/hosted_priority.go b/internal/reviewexec/hosted_priority.go index 5a7474d0..5b05c174 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,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, true) +} + +type queuePriorityPreflight struct { + cause error + predecessors []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, 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 @@ -75,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 { @@ -89,12 +105,37 @@ ORDER BY q.key,o.created_at,o.id`, string(queue), position, o.ProjectID, o.Chann conflict.project == earlier.ProjectID && conflict.operation == earlier.ID { continue } - 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 + } + 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(), repositoryID, c, revision, earlier, o) { + continue + } + 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_query.go b/internal/reviewexec/hosted_query.go index 0112f6fd..9c07bcc9 100644 --- a/internal/reviewexec/hosted_query.go +++ b/internal/reviewexec/hosted_query.go @@ -188,6 +188,10 @@ func (e *Engine) ReadHostedAllowanceQuery(ctx context.Context, project, attemptI if err != nil { return err } + o, err = historicalHostedRetainedReadOperation(ctx, tx, o, a) + if err != nil { + return err + } result, err = readHostedQuery(ctx, tx, a, o) return err }) diff --git a/internal/reviewexec/independent_claim_witness.go b/internal/reviewexec/independent_claim_witness.go new file mode 100644 index 00000000..01b28332 --- /dev/null +++ b/internal/reviewexec/independent_claim_witness.go @@ -0,0 +1,172 @@ +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 exact typed per-pull refusals, +// and the serialized claim rechecks each identity before any exemption. +type independentClaimWitness struct { + predecessors []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, 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}) + 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{predecessors: slices.Clone(predecessors), 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(successor, w.successor) && + slices.ContainsFunc(w.predecessors, func(observed Operation) bool { return sameIndependentClaimOperation(predecessor, observed) }) +} + +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 + 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 || len(p.predecessors) == 0 { + return nil + } + reader := driver.IndependentQueueTargetReader() + if reader == nil { + return nil + } + // 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 || 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() + + probeCtx, cancel := context.WithTimeout(ctx, independentProbeTimeout) + defer cancel() + 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 +} + +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 00000000..5c850343 --- /dev/null +++ b/internal/reviewexec/independent_claim_witness_test.go @@ -0,0 +1,360 @@ +package reviewexec + +import ( + "context" + "errors" + "fmt" + "reflect" + "slices" + "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, []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) + } + 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") + } + 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" + checkRefusal(dependent, "non-default base") + incomplete := reader + incomplete.pull.IsDraft = nil + 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) { + 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{predecessors: []Operation{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{predecessors: []Operation{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") + } +} + +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/local_refusal_boundaries_test.go b/internal/reviewexec/local_refusal_boundaries_test.go index 3ca2cada..2f351888 100644 --- a/internal/reviewexec/local_refusal_boundaries_test.go +++ b/internal/reviewexec/local_refusal_boundaries_test.go @@ -4,12 +4,50 @@ 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) @@ -46,3 +84,25 @@ func TestAutomaticAdoptionCountRetainsLocalRepositoryRefusal(t *testing.T) { 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 new file mode 100644 index 00000000..6c34ef7b --- /dev/null +++ b/internal/reviewexec/next_ordinary_test.go @@ -0,0 +1,38 @@ +package reviewexec + +import ( + "context" + "database/sql" + "testing" +) + +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/policy_admission.go b/internal/reviewexec/policy_admission.go index 725f01a9..b7991667 100644 --- a/internal/reviewexec/policy_admission.go +++ b/internal/reviewexec/policy_admission.go @@ -52,6 +52,15 @@ func (e *Engine) currentExecutionContext(ctx context.Context, tx *sql.Tx, operat // A cooldown is retained negative evidence, not admission. Project or pull // pause may delay its retry without discarding it; other authority checks still apply. func (e *Engine) executionContext(ctx context.Context, tx *sql.Tx, operation Operation, retainCooldown bool) (ExecutionContext, error) { + 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 { var pause *core.Error @@ -60,7 +69,16 @@ func (e *Engine) executionContext(ctx context.Context, tx *sql.Tx, operation Ope } } 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 @@ -117,6 +135,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/preferred_cli_wait_integrity_test.go b/internal/reviewexec/preferred_cli_wait_integrity_test.go index d7001065..6a702a57 100644 --- a/internal/reviewexec/preferred_cli_wait_integrity_test.go +++ b/internal/reviewexec/preferred_cli_wait_integrity_test.go @@ -2,11 +2,88 @@ 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) diff --git a/internal/reviewexec/preparation_recovery.go b/internal/reviewexec/preparation_recovery.go index 5f25a46b..56adeb57 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/reviewexec/run_selection.go b/internal/reviewexec/run_selection.go index 11d5353a..9561142b 100644 --- a/internal/reviewexec/run_selection.go +++ b/internal/reviewexec/run_selection.go @@ -661,9 +661,13 @@ 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 - (o.project_id<>s.project_id OR o.actor_id<>s.actor_id OR o.worker_id<>s.worker_id 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 (s.expected_pull_number<>0 AND o.pull_number<>s.expected_pull_number)) @@ -674,7 +678,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_capacity_test.go b/internal/reviewexec/run_selection_capacity_test.go index fbde2490..493bf0da 100644 --- a/internal/reviewexec/run_selection_capacity_test.go +++ b/internal/reviewexec/run_selection_capacity_test.go @@ -164,3 +164,36 @@ 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) + 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) + } + 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 7152b6b6..1e330476 100644 --- a/internal/reviewexec/run_selection_worker.go +++ b/internal/reviewexec/run_selection_worker.go @@ -3,16 +3,16 @@ package reviewexec import ( "context" "database/sql" + "encoding/json" "errors" + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/reviewprovider" + "github.com/benhook1013/FireController/internal/reviews" "math" "reflect" "slices" "sync" "time" - - "github.com/benhook1013/FireController/internal/core" - "github.com/benhook1013/FireController/internal/reviewprovider" - "github.com/benhook1013/FireController/internal/reviews" ) // runSourceBudget bounds cumulative source acquisition, excluding local SQL @@ -556,7 +556,12 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR if workerCtx.Err() != nil { return } - worked, err := e.runNextInDrain(workerCtx, owned, &cursor) + generated, err := e.coordinateAutomaticHosted(workerCtx, owned) + var worked bool + if err == nil { + worked, err = e.runNextInDrain(workerCtx, owned, &cursor) + } + worked = worked || generated if err != nil { if workerCtx.Err() != nil { return @@ -590,10 +595,12 @@ func (e *Engine) StartReviewRuns(ctx context.Context, readers map[string]TargetR } type runCandidateCursor struct { - createdAt any - id any - throughSequence int64 - hasHorizon bool + priority int64 + accountAt, accountID any + createdAt any + id any + throughSequence int64 + hasHorizon bool } func (e *Engine) runNext(ctx context.Context, readers map[string]TargetReader) (bool, error) { @@ -623,6 +630,21 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target var changed string 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 { @@ -642,15 +664,31 @@ 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, `SELECT s.project_id,s.id,`+selectionClaimRevision+`,s.created_at FROM review_selections 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.created_at,s.id)>(?,?)) AND NOT EXISTS (SELECT 1 FROM events later WHERE later.project_id=s.project_id AND later.resource_id=s.id AND later.event_type='review.selection_requested' AND later.revision=1 AND later.sequence>?) AND (s.operation_id IS NULL OR (typeof(s.project_id)='text' AND typeof(s.id)='text')) AND (SELECT count(*) FROM review_operations WHERE state IN ('queued','preparing','posting','active','uncertain'))(?,?,?,?,?)) + ORDER BY s.account_at,s.account_id,s.run_priority,s.created_at,s.id LIMIT 1`, preferredCLIRepository, string(accountJSON), cursor.throughSequence, 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 } @@ -660,7 +698,8 @@ func (e *Engine) runNextCandidate(ctx context.Context, readers map[string]Target if err != nil || nativeID == nil { return false, err } - cursor.createdAt, cursor.id = nativeCreatedAt, nativeID + 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) @@ -901,7 +940,7 @@ func (e *Engine) finishRunChoice(ctx context.Context, r Run, repo int64, metadat if settle && !(pull == 0 && choice.sourceReason != "") { complete := choice.automaticQueueLimit == nil || (choice.sourcePrefixComplete && len(choice.prefix) == len(boundPrefix)) - resultErr = e.settleAutomaticBasis(ctx, tx, r, pull, complete) + resultErr = e.settleAutomaticBasis(ctx, tx, r, pull, complete, pull == 0 && reason == "repository_changed") } } if automaticProjectRefused(resultErr) { diff --git a/internal/reviewexec/scheduling.go b/internal/reviewexec/scheduling.go index eefd7b4d..400e772d 100644 --- a/internal/reviewexec/scheduling.go +++ b/internal/reviewexec/scheduling.go @@ -1,6 +1,7 @@ package reviewexec import ( + "bytes" "context" "database/sql" "encoding/json" @@ -25,6 +26,33 @@ type Scheduling struct { UpdatedAt string `json:"updated_at,omitempty"` Reason string `json:"reason,omitempty"` } +type SchedulingRequest struct { + ExpectedRevision *int64 `json:"expected_revision"` + AutomaticCLI *bool `json:"automatic_cli,omitempty"` + AutomaticHosted *bool `json:"automatic_hosted"` +} + +// Omission preserves the CLI setting; explicit null is not a boolean choice. +func (r *SchedulingRequest) UnmarshalJSON(data []byte) error { + type plain SchedulingRequest + var value plain + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&value); err != nil { + return err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + for name, raw := range fields { + if strings.EqualFold(name, "automatic_cli") && bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + return invalid() + } + } + *r = SchedulingRequest(value) + return nil +} type PullScheduling struct { ProjectID string `json:"project_id"` @@ -220,6 +248,85 @@ func (e *Engine) ReadScheduling(ctx context.Context, scope core.Scope) (Scheduli 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 + } + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, scope.WorkerID); err != nil { + return nil, err + } + credential := "" + if *input.AutomaticHosted || automaticCLI { + 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 + generation := old.Revision + 1 + if !authorizerChanged && old.Revision > 0 { + prior, err := schedulingAuthorityContinuity(ctx, tx, scope.ProjectID, old.actor, old.Revision, old.Revision, false) + if err != nil { + return nil, err + } + if prior != 0 { + generation = prior + } + } + 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 + } + if err = core.AppendEvent(ctx, tx, scope, schedulingAuthorityBoundEvent, scope.ProjectID, old.Revision+1, schedulingAuthorityPayload{Generation: generation}); 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 +} // A pull-specific retained control refusal is distinct from project // scheduling, a query error, or another member of the queue. 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 00000000..380e9a33 --- /dev/null +++ b/internal/reviewexec/scheduling_adjudication_basis_compatibility_test.go @@ -0,0 +1,68 @@ +package reviewexec + +import ( + "bytes" + "crypto/sha256" + "database/sql" + "encoding/hex" + "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 + }{ + {"e4", "p", "cli", `{"capture":{"review":{"Findings":[{"Title":"Valid finding"}]}}}`, 2}, + {"e1", "p", "cli", `{"capture":{"review":{"Findings":[]}}}`, 2}, + {"e3", "p", "hosted", `{"capture":{"review":{"Findings":null}}}`, 2}, + {"e2", "p", "hosted", `{"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) + } + } + // Freeze the original query label, NUL separator, and ordered JSON rows. + // CLI includes e1, e2, e4; Hosted includes e2, e3, e4. + for _, tc := range []struct{ channel, digest string }{ + {"cli", "4dc8d8a0206132b93a7fc669f6bfa0046ce6e1891faf238a0626313e21415d99"}, + {"hosted", "1b1e87c3e6f25b7e538a6e0197be5baf4d1a945228126d45ef4d2141664a5eb2"}, + } { + var actual bytes.Buffer + label := automaticAdjudicationBasisLabel(tc.channel) + if err := automaticBasisAppender(t.Context(), tx, &actual, tc.channel, 1)(label, false, "p", 2); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(actual.Bytes()) + if got := hex.EncodeToString(sum[:]); got != tc.digest { + t.Fatalf("%s changed valid digest input: got %s, want %s; input %q", tc.channel, got, tc.digest, actual.Bytes()) + } + } +} diff --git a/internal/reviewexec/scheduling_admission0030_test.go b/internal/reviewexec/scheduling_admission0030_test.go index cc781210..83de7785 100644 --- a/internal/reviewexec/scheduling_admission0030_test.go +++ b/internal/reviewexec/scheduling_admission0030_test.go @@ -8,15 +8,35 @@ import ( func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { for _, channel := range []string{"hosted", "cli"} { - for _, change := range []string{"explicit-pause", "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 - id := f.enqueue(t, attemptProject, "late-explicit-pause", channel, 2, 1).ID + 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") - const reason = "pull_scheduling_paused" + reason := "automation_authorization_changed" + if change == "explicit-pause" || change == "automatic-pause" { + reason = "pull_scheduling_paused" + } + if change == "malformed-state" || change == "malformed-scheduling" { + reason = "automatic_scheduling_unavailable" + } 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 { @@ -24,8 +44,26 @@ func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { } preparedAttempt = a switch change { - case "explicit-pause": + 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'`) + 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) } @@ -64,7 +102,7 @@ func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { 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" { + 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) { @@ -80,6 +118,11 @@ func TestSchedulingAdmissionRechecksControlsAfterPreparation(t *testing.T) { 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) + } } }) } diff --git a/internal/reviewexec/scheduling_allowance_history_test.go b/internal/reviewexec/scheduling_allowance_history_test.go new file mode 100644 index 00000000..c57f153a --- /dev/null +++ b/internal/reviewexec/scheduling_allowance_history_test.go @@ -0,0 +1,32 @@ +package reviewexec + +import "testing" + +func TestSchedulingDetachedCLIAllowanceRemainsValidHistory(t *testing.T) { + for _, reason := range []string{"pull_scheduling_paused", "automation_authorization_changed", "automatic_scheduling_unavailable"} { + t.Run(reason, func(t *testing.T) { + f := attemptProjectionFixture(t, true) + a := f.start(t, attemptProject, f.enqueue(t, attemptProject, "scheduling-allowance", "cli", 2, 1)) + in := CLIAllowanceObservation{Anchor: attemptAnchor(attemptProject, 2), ObservedAt: stamp(), Remaining: 3, Limit: 5, FullCapacityInMS: 12000, RollingWindowMS: 3600000, ChangedFiles: 2} + if err := f.e.RecordCLIAllowance(t.Context(), attemptProject, a.ID, a.Revision, in); err != nil { + t.Fatal(err) + } + held, err := f.e.Advance(t.Context(), attemptProject, a.ID, a.Revision, "held", reason, "") + if err != nil { + t.Fatal(err) + } + o, err := readOperationBase(t.Context(), f.store.DB(), attemptProject, a.OperationID) + if err != nil { + t.Fatal(err) + } + if o.AttemptID != "" { + t.Fatal("attempt not detached", o) + } + if _, err := readCLIAllowanceRecord(t.Context(), f.store.DB(), o, held); err != nil { + t.Fatal("valid detached allowance rejected", err) + } + assertCLIWaitSnapshot(t, f) + assertCLIWaitNoCredit(t, f) + }) + } +} diff --git a/internal/reviewexec/scheduling_ancestor_memo_test.go b/internal/reviewexec/scheduling_ancestor_memo_test.go index 02d58f01..6e496186 100644 --- a/internal/reviewexec/scheduling_ancestor_memo_test.go +++ b/internal/reviewexec/scheduling_ancestor_memo_test.go @@ -18,18 +18,16 @@ func TestAutomaticDependenciesReuseSharedAncestorWithinSnapshot(t *testing.T) { frame.prefix = append(frame.prefix, frontPull{Number: pull, ParentPullNumber: parent}) } if err := f.store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { - memo := make(map[int64][]any) - index := frontPullIndex(frame) + memo := newAutomaticDependencyRead(ctx, tx, attemptProject, "hosted", frame, true) + load := memo.load reads := 0 + memo.load = func(p frontPull) ([]any, error) { reads++; return load(p) } for pull := int64(10); pull < 60; pull++ { - direct, err := automaticDependenciesWithFrame(ctx, tx, attemptProject, pull, "hosted", frame, true, nil, nil) + direct, err := newAutomaticDependencyRead(ctx, tx, attemptProject, "hosted", frame, true).forPull(pull) if err != nil { return err } - cached, err := automaticDependenciesWithAncestorRead(pull, frame, true, index, memo, func(p frontPull) ([]any, error) { - reads++ - return readAutomaticAncestorFacts(ctx, tx, attemptProject, "hosted", frame.repository, p) - }) + cached, err := memo.forPull(pull) if err != nil { return err } @@ -40,8 +38,8 @@ func TestAutomaticDependenciesReuseSharedAncestorWithinSnapshot(t *testing.T) { if reads != 2 { return fmt.Errorf("evaluated %d ancestors, want exactly two across all siblings", reads) } - if len(memo) != 2 { - return fmt.Errorf("memo has %d entries, want exactly two shared ancestors", len(memo)) + if len(memo.facts) != 2 { + return fmt.Errorf("memo has %d entries, want exactly two shared ancestors", len(memo.facts)) } return nil }); err != nil { diff --git a/internal/reviewexec/scheduling_authority_retry_test.go b/internal/reviewexec/scheduling_authority_retry_test.go new file mode 100644 index 00000000..98012495 --- /dev/null +++ b/internal/reviewexec/scheduling_authority_retry_test.go @@ -0,0 +1,68 @@ +package reviewexec + +import ( + "testing" + "time" +) + +func TestAutomaticHostedSourceRetryPreservesBindingAcrossUnrelatedEdit(t *testing.T) { + f, original := sourceRetryFixture(t) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + revision, enabled := int64(1), true + if _, err := f.e.ConfigureScheduling(t.Context(), scope, "retry-enable-unrelated-cli", SchedulingRequest{ExpectedRevision: &revision, AutomaticHosted: &enabled, AutomaticCLI: &enabled}); err != nil { + t.Fatal(err) + } + if retrySourceDirect(t, f, original, time.Now()) { + t.Fatal("settings edit shortened the original retry backoff") + } + ageSourceRetry(t, f, original.ID) + schedulingGenerate(t, f, true) + queued := schedulingLatest(t, f) + if queued.ID != original.ID || queued.State != "queued" || queued.Revision != 4 || queued.ActorID != original.ActorID || queued.WorkerID != original.WorkerID { + t.Fatal(queued) + } + selectionNext(t, f, &refreshTestReader{}) + selected := schedulingLatest(t, f) + if selected.ID != original.ID || selected.State != "selected" || selected.OperationID == "" { + t.Fatal(selected) + } + 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("changed settings created replacement intent or started provider work") + } +} + +func TestSchedulingWriterKeepsAuthorityGenerationSeparateFromLaneRearm(t *testing.T) { + f := schedulingFixtureWithQueue(t, []int64{2}) + schedulingEnable(t, f, 0, true) + scope := selectionScope(t, f, attemptProject, f.writer, "write") + revision, on := int64(1), true + if _, err := f.e.ConfigureScheduling(t.Context(), scope, "authority-generation-unrelated-lane", SchedulingRequest{ExpectedRevision: &revision, AutomaticHosted: &on, AutomaticCLI: &on}); err != nil { + t.Fatal(err) + } + schedulingEnable(t, f, 2, true) + admissionSQL(t, f, `INSERT INTO workers VALUES(?,'replacement-worker','Replacement manager')`, attemptProject) + continuityConfigure(t, f, 3, true, true) + schedulingEnable(t, f, 4, true) + want := []struct{ generation, basis int64 }{{1, 1}, {1, 1}, {1, 3}, {4, 4}, {5, 5}} + rows, err := f.store.DB().Query(`SELECT json_extract(w.payload_json,'$.generation'),json_extract(s.payload_json,'$.hosted_basis_revision') + FROM events w JOIN events s ON s.project_id=w.project_id AND s.resource_id=w.resource_id AND s.revision=w.revision AND s.actor_id=w.actor_id AND s.sequence= len(want) || generation != want[i].generation || basis != want[i].basis { + t.Fatalf("revision %d generation=%d hosted basis=%d", i+1, generation, basis) + } + i++ + } + if rows.Err() != nil || i != len(want) { + t.Fatal(i, rows.Err()) + } +} diff --git a/internal/reviewexec/scheduling_authorization_continuity.go b/internal/reviewexec/scheduling_authorization_continuity.go index eb08298e..f72e011d 100644 --- a/internal/reviewexec/scheduling_authorization_continuity.go +++ b/internal/reviewexec/scheduling_authorization_continuity.go @@ -33,6 +33,12 @@ func automaticChannelContinuous(ctx context.Context, tx *sql.Tx, r Run, revision return false, nil } if _, _, err := schedulingBasisRevisions(ctx, tx, current); err != nil { + if automaticProjectRefused(err) { + // Invalid retained evidence cannot prove continuity. Keep the + // existing authorization denial for this cross-revision check; + // propagate actual query or transaction failures. + return false, nil + } return false, err } selectedChild := r.State == "selected" && r.OperationID != "" diff --git a/internal/reviewexec/scheduling_authorization_continuity_test.go b/internal/reviewexec/scheduling_authorization_continuity_test.go new file mode 100644 index 00000000..e7e5c624 --- /dev/null +++ b/internal/reviewexec/scheduling_authorization_continuity_test.go @@ -0,0 +1,327 @@ +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", "duplicate-channel", "case-alias-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 { + 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 "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 "case-alias-channel": + continuityConfigure(t, f, 2, true, true) + 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": + 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) + wait := snapshotTable(t, f, "review_operation_waits") + admissionSQL(t, f, `INSERT INTO workers VALUES(?,'replacement-worker','Replacement manager')`, attemptProject) + continuityConfigure(t, f, 1, true, true) + if wait != snapshotTable(t, f, "review_operation_waits") { + t.Fatal("authorizer update changed the retained wait") + } + 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) + // Reasserting an enabled CLI channel deliberately rearms its + // pending intent; unrelated edits and already-linked work + // keep their established continuity contracts. + denied := change == "off-on" || change == "missing-history" || + (change == "same-settings" && channel == "cli" && state != "selected") + 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) + } + } + }) + } + } + } +} + +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 976ecc69..b1caa7af 100644 --- a/internal/reviewexec/scheduling_automatic.go +++ b/internal/reviewexec/scheduling_automatic.go @@ -12,6 +12,7 @@ import ( "slices" "strconv" "strings" + "time" "github.com/benhook1013/FireController/internal/core" ) @@ -37,11 +38,6 @@ func automaticProjectRefused(err error) bool { func automaticDenied() error { return core.Fail("automation_authorization_changed", "Automatic review scheduling is disabled or its original authorizer is no longer authorized.", 403) } - -func automaticChannelEnabled(s schedulingRecord, channel string) bool { - return channel == "hosted" && s.AutomaticHosted || channel == "cli" && s.AutomaticCLI -} - func (e *Engine) requireAutomaticRun(ctx context.Context, tx *sql.Tx, r Run) error { attribution, err := automaticSelectionBinding(ctx, tx, r) if err != nil || attribution.revision == 0 { @@ -73,8 +69,9 @@ func (e *Engine) requireAutomaticRun(ctx context.Context, tx *sql.Tx, r Run) err return automaticDenied() } } else { - // Same-revision work still requires the exact canonical event - // behind its enabled control; a retained projection alone is not proof. + // 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 } @@ -147,13 +144,10 @@ func automaticPullBasis(ctx context.Context, tx *sql.Tx, project string, pull in } type automaticBasisRead struct { - prefix []byte - revision int64 - workspace bool - frame frontFrame - hasFrame bool - parentFacts map[int64][]any - frontByNumber map[int64]frontPull + prefix []byte + revision int64 + workspace bool + dependencies automaticDependencyRead } // The channel semantic revision is independent of unrelated control edits. @@ -180,10 +174,11 @@ func readAutomaticBasis(ctx context.Context, tx *sql.Tx, project, channel string 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) + frame, found, err := readFrontFrame(ctx, tx, project, channel) if err != nil { return out, err } + out.dependencies = newAutomaticDependencyRead(ctx, tx, project, channel, frame, found) var prefix bytes.Buffer appendRows := automaticBasisAppender(ctx, tx, &prefix, channel, out.revision) for _, query := range []string{ @@ -196,10 +191,6 @@ func readAutomaticBasis(ctx context.Context, tx *sql.Tx, project, channel string } } out.prefix = prefix.Bytes() - if out.hasFrame { - out.parentFacts = make(map[int64][]any) - out.frontByNumber = frontPullIndex(out.frame) - } return out, nil } @@ -349,7 +340,7 @@ func automaticPullBasisWithRead(ctx context.Context, tx *sql.Tx, project string, return "", err } } - dependencies, err := automaticDependenciesWithFrame(ctx, tx, project, pull, channel, shared.frame, shared.hasFrame, shared.frontByNumber, shared.parentFacts) + dependencies, err := shared.dependencies.forPull(pull) if err != nil { return "", err } @@ -373,32 +364,38 @@ func automaticDependenciesChannel(ctx context.Context, tx *sql.Tx, project strin if err != nil { return nil, err } - return automaticDependenciesWithFrame(ctx, tx, project, pull, channel, frame, found, nil, nil) -} - -func frontPullIndex(frame frontFrame) map[int64]frontPull { - byNumber := make(map[int64]frontPull, len(frame.prefix)) - for _, p := range frame.prefix { - byNumber[p.Number] = p - } - return byNumber + return newAutomaticDependencyRead(ctx, tx, project, channel, frame, found).forPull(pull) } -func automaticDependenciesWithFrame(ctx context.Context, tx *sql.Tx, project string, pull int64, channel string, frame frontFrame, found bool, byNumber map[int64]frontPull, parentFacts map[int64][]any) ([]any, error) { - return automaticDependenciesWithAncestorRead(pull, frame, found, byNumber, parentFacts, func(p frontPull) ([]any, error) { - return readAutomaticAncestorFacts(ctx, tx, project, channel, frame.repository, p) - }) +// A dependency read owns one planning snapshot and one project's channel. +// Keep traversal guards per descendant, but read each ancestor's immutable +// transaction facts once. A writer replan always constructs a fresh read. +type automaticDependencyRead struct { + byNumber map[int64]frontPull + facts map[int64][]any + load func(frontPull) ([]any, error) } -func automaticDependenciesWithAncestorRead(pull int64, frame frontFrame, found bool, byNumber map[int64]frontPull, parentFacts map[int64][]any, read func(frontPull) ([]any, error)) ([]any, error) { - out := []any{} +func newAutomaticDependencyRead(ctx context.Context, tx *sql.Tx, project, channel string, frame frontFrame, found bool) automaticDependencyRead { if !found { - return out, nil + return automaticDependencyRead{} } - if byNumber == nil { - byNumber = frontPullIndex(frame) + read := automaticDependencyRead{ + byNumber: make(map[int64]frontPull, len(frame.prefix)), + facts: make(map[int64][]any), + load: func(p frontPull) ([]any, error) { + return loadAutomaticDependencyFacts(ctx, tx, project, channel, frame.repository, p) + }, } - current, found := byNumber[pull] + for _, p := range frame.prefix { + read.byNumber[p.Number] = p + } + return read +} + +func (r automaticDependencyRead) forPull(pull int64) ([]any, error) { + out := []any{} + current, found := r.byNumber[pull] if !found { return out, nil } @@ -408,24 +405,19 @@ func automaticDependenciesWithAncestorRead(pull int64, frame frontFrame, found b return nil, errors.Join(errAutomaticParentCycle, schedulingUnavailable()) } seen[parent] = true - p, exists := byNumber[parent] + p, exists := r.byNumber[parent] if !exists { out = append(out, []any{parent, "source_prefix_incomplete"}) break } - // One planning snapshot owns this memo and immutable frame. Never - // cache an error or skip the current pull's own chain/cycle checks. - if facts, present := parentFacts[parent]; present { - out = append(out, facts) - parent = p.ParentPullNumber - continue - } - facts, err := read(p) - if err != nil { - return nil, err - } - if parentFacts != nil { - parentFacts[parent] = facts + facts, loaded := r.facts[parent] + if !loaded { + var err error + facts, err = r.load(p) + if err != nil { + return nil, err + } + r.facts[parent] = facts } out = append(out, facts) parent = p.ParentPullNumber @@ -433,7 +425,7 @@ func automaticDependenciesWithAncestorRead(pull int64, frame frontFrame, found b return out, nil } -func readAutomaticAncestorFacts(ctx context.Context, tx *sql.Tx, project, channel string, repository int64, p frontPull) ([]any, error) { +func loadAutomaticDependencyFacts(ctx context.Context, tx *sql.Tx, project, channel string, repository int64, p frontPull) ([]any, error) { parent := p.Number progress, err := channelProgress(ctx, tx, project, repository, parent, channel) if err != nil { @@ -563,6 +555,31 @@ func automaticPlanningBasisForPrefix(ctx context.Context, tx *sql.Tx, project st return basis, 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. @@ -781,12 +798,12 @@ 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, complete bool) error { +func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pull int64, complete, acceptedOnly bool) error { attribution, err := automaticSelectionBinding(ctx, tx, r) if err != nil || attribution.revision == 0 { return err } - if !complete && pull == 0 { + if !complete && !acceptedOnly && pull == 0 { return nil } pullBasis := "" @@ -796,7 +813,7 @@ func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pu return err } } - if !complete { + if !complete && !acceptedOnly { _, err = tx.ExecContext(ctx, `UPDATE review_automatic_selections SET pull_number=?,pull_basis_sha256=? WHERE selection_id=? AND project_id=?`, pull, pullBasis, r.ID, r.ProjectID) return err } @@ -808,6 +825,257 @@ func (e *Engine) settleAutomaticBasis(ctx context.Context, tx *sql.Tx, r Run, pu 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) + 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 } + +// 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) { + 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() + } + 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 { + account string + 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, configurationRevision, 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 + } + 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 + } + 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 + } + 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{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 { + 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 +} + +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 + candidate, err = e.planAutomaticProject(ctx, tx, project, channel, readers) + return err + }) + if ctx.Err() != nil { + return false, ctx.Err() + } + if err != nil || candidate == nil || expectedAccount != "" && candidate.account != expectedAccount { + 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) { + 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) + if err != nil || current == nil { + return err + } + 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 { + 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 := 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 { + 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 00000000..edd662f8 --- /dev/null +++ b/internal/reviewexec/scheduling_cli.go @@ -0,0 +1,124 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "github.com/benhook1013/FireController/internal/core" +) + +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) 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 + var err error + preferred, err = automaticCLIProjects(ctx, tx, true, e.automaticCLICursor, half) + if err != nil { + return err + } + 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 err + }); err != nil { + return false, err + } + // Visit the bounded project set even after creating a preferred selection. + // Account-level preference is enforced again at claim; independent accounts + // must not starve simply because preferred work is always available. + generated := false + selectedAccounts := map[string]bool{} + for i, project := range append(preferred, other...) { + if i < len(preferred) { + e.automaticCLICursor = project + } else { + e.automaticCLIOtherCursor = project + } + 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] { + continue + } + worked, err := e.generateAutomaticProjectForAccount(ctx, project, "cli", readers, account) + if automaticProjectRefused(err) { + continue + } + if err != nil { + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "overloaded" && ctx.Err() == nil { + // No intent was accepted. Other projects on the same + // account can still make progress during this bounded pass. + continue + } + return generated, err + } + if worked { + generated = true + selectedAccounts[account] = true + } + } + return generated, nil +} diff --git a/internal/reviewexec/scheduling_cli_account_window_test.go b/internal/reviewexec/scheduling_cli_account_window_test.go new file mode 100644 index 00000000..dd83194b --- /dev/null +++ b/internal/reviewexec/scheduling_cli_account_window_test.go @@ -0,0 +1,30 @@ +package reviewexec + +import ( + "fmt" + "testing" +) + +func TestPreferredCLIAccountWindowIgnoresOtherAccounts(t *testing.T) { + f := schedulingFixture(t) + f.configure(t, otherAttemptProject, "test-capability", 0, false) + low := f.enqueue(t, attemptProject, "competing", "cli", 2, 1) + high := f.enqueue(t, otherAttemptProject, "preferred", "cli", 2, 1) + admissionSQL(t, f, `UPDATE projects SET repository=? WHERE id=?`, preferredCLIRepository, otherAttemptProject) + + for i := range 101/requestProjectCapacity + 1 { + project := fmt.Sprintf("other-account-priority-%d", i) + selectionCapacityProject(t, f, project, int64(900+i)) + admissionSQL(t, f, `UPDATE review_execution_config SET body_json=json_set(body_json, '$.capability_id', 'other-account') WHERE project_id=?`, project) + selectionCapacityFill(t, f, project) + admissionSQL(t, f, `UPDATE projects SET repository=? WHERE id=?`, preferredCLIRepository, project) + admissionSQL(t, f, `UPDATE review_operations SET channel='cli',capability_fingerprint=?,created_at='2000-01-01T00:00:00Z' WHERE project_id=?`, f.e.capabilities["other-account"].Fingerprint, project) + } + if !schedulingCLI0030Priority(t, f, attemptProject, low.ID) { + t.Fatal("older candidates on another account consumed the priority window") + } + admissionSQL(t, f, `UPDATE review_operations SET reason='cli_draft_wait' WHERE id=?`, high.ID) + if schedulingCLI0030Priority(t, f, attemptProject, low.ID) { + t.Fatal("other-account candidates or an ineligible shared-account candidate reserved priority") + } +} diff --git a/internal/reviewexec/scheduling_cli_fairness_test.go b/internal/reviewexec/scheduling_cli_fairness_test.go new file mode 100644 index 00000000..69e897c6 --- /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 new file mode 100644 index 00000000..fe693a89 --- /dev/null +++ b/internal/reviewexec/scheduling_cli_priority.go @@ -0,0 +1,253 @@ +package reviewexec + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "slices" + "strings" +) + +const preferredCLIRepository = "benhook1013/firemud" + +type pendingCandidateID struct{ project, operation string } + +// Only candidates on the installed account may consume the bounded priority +// window. Each candidate still needs its exact current binding checked below. +func (e *Engine) preferredCLIAccountFingerprints(capability Capability) string { + fingerprints := []string{} + for _, installed := range e.capabilities { + if installed.Provider == capability.Provider && installed.Account == capability.Account && installed.Fingerprint != "" { + fingerprints = append(fingerprints, installed.Fingerprint) + } + } + slices.Sort(fingerprints) + encoded, _ := json.Marshal(slices.Compact(fingerprints)) // []string cannot fail JSON encoding. + return string(encoded) +} + +// 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<>? AND o.capability_fingerprint IN (SELECT value FROM json_each(?)) ORDER BY o.created_at,o.id LIMIT 101`, preferredCLIRepository, o.ProjectID, e.preferredCLIAccountFingerprints(capability)) + if err != nil { + return false, err + } + var ids []pendingCandidateID + for rows.Next() { + var rawProject, rawOperation any + if err = rows.Scan(&rawProject, &rawOperation); err != nil { + break + } + project, projectOK := rawProject.(string) + operation, operationOK := rawOperation.(string) + if projectOK && operationOK { + ids = append(ids, pendingCandidateID{project, operation}) + } + } + 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 isStoredUnavailable(err, storedOperationIdentity) || isRetainedOperationDecodeError(err) || isWaitUnavailable(err) || automaticProjectRefused(err) || isStoredUnavailable(err, storedConfigurationHistory) { + continue candidates + } + return false, err + } + if earlier.Wait != nil && earlier.Wait.Paused { + continue + } + priorConfig, revision, 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 + } + // 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 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) || isStoredUnavailable(err, storedRoundHistory) { + continue candidates + } + return false, err + } + if valid { + // 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 { + continue candidates + } + dependency, err := e.earlierQueuedReviewIntentWithWitness(ctx, tx, earlier, priorConfig, revision, nil, nil, false) + if err != nil { + if automaticProjectRefused(err) || isRetainedOperationDecodeError(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 + } + } + } + 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 s.capability_fingerprint IN (SELECT value FROM json_each(?)) + AND (SELECT count(*) FROM review_operations WHERE state IN ('queued','preparing','posting','active','uncertain')) 6 { + return false + } + switch r.Reason { + case "source_budget_exhausted", "source_fetch_timeout", "source_provider_unavailable", "routed_findings_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 + var retainedRevision any + err := tx.QueryRowContext(ctx, `SELECT s.id,a.scheduling_revision 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=? OR (s.channel='hosted' AND typeof(a.scheduling_revision)='integer' AND a.scheduling_revision BETWEEN 1 AND ?-1)) AND (a.basis_sha256=? OR a.settled_basis_sha256=?) ORDER BY s.created_at DESC,s.id LIMIT 1`, project, channel, schedulingRevision, schedulingRevision, basis, basis).Scan(&id, &retainedRevision) + 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 + } + configuration, _, reason, err := e.runBinding(ctx, tx, r) + if err != nil || reason != "" { + return nil, err + } + accepted, validRevision := retainedRevision.(int64) + if !validRevision || accepted < 1 { + return nil, schedulingUnavailable() + } + if accepted != schedulingRevision { + generation, err := schedulingAuthorityContinuity(ctx, tx, project, r.ActorID, accepted, schedulingRevision, true) + if err != nil || generation == 0 { + return nil, err + } + } + if r.Reason == "routed_findings_unavailable" { + // A repaired projection can have the same source digest as before + // invalidation. Reconsider the same intent, but do not spend its + // bounded source retries while a configured pull's route facts are + // dirty. Check the whole bounded queue: an eligible pull may depend + // on an ancestor outside its current waiting cutoff. + var dirty bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS( + SELECT 1 FROM json_each(?) q JOIN review_route_policy_invalidations i + ON i.project_id=? AND i.target_pull_number=q.value)`, encoded(configuration.Queue), project).Scan(&dirty) + if err != nil || dirty { + 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. // Both recovery paths respect newer intent. Completed source holds require the @@ -52,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 @@ -70,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. @@ -120,10 +300,9 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er // Match the closed canonical acceptance shapes without parsing untrusted // payloads. Channel and worker are restricted to JSON-safe native IDs, // so SQLite json_object emits the same bytes as selectionRequestedEvent. - // Compare parsed times, not RFC3339 text with variable fractional precision. - // For rows with no acceptance event, millisecond ties conservatively fence. // Event sequence is the durable acceptance order even if the wall clock - // moves backwards. Missing acceptance evidence is not permission to retry. + // moves backwards. Legacy eventless rows stay readable, but their + // timestamps cannot prove same-channel precedence for automatic recovery. acceptance, err := readSelectionRequestedEvent(ctx, tx, r) if err != nil { return false, err @@ -131,19 +310,13 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er if acceptance.sequence == 0 { return true, nil } - acceptedAt, err := time.Parse(time.RFC3339Nano, r.CreatedAt) - if err != nil || acceptedAt.IsZero() { - return true, nil - } - comparedAt := acceptedAt.UTC().Format(time.RFC3339Nano) accepted := acceptance.sequence var superseded bool err = tx.QueryRowContext(ctx, `SELECT EXISTS( SELECT 1 FROM review_selections s WHERE s.project_id=? AND s.channel=? AND s.id<>? - AND (typeof(s.created_at)<>'text' OR length(s.created_at)<19 OR substr(s.created_at,11,1) NOT IN ('T',' ') OR julianday(s.created_at) IS NULL OR julianday(s.created_at)>=julianday(?)) AND NOT EXISTS(SELECT 1 FROM events e WHERE e.project_id=s.project_id AND e.resource_id=s.id AND e.event_type='review.selection_requested' AND e.revision=1) ) OR EXISTS( - SELECT 1 FROM review_operations o WHERE o.project_id=? AND o.channel=? AND (typeof(o.created_at)<>'text' OR length(o.created_at)<19 OR substr(o.created_at,11,1) NOT IN ('T',' ') OR julianday(o.created_at) IS NULL OR julianday(o.created_at)>=julianday(?)) + SELECT 1 FROM review_operations o WHERE o.project_id=? AND o.channel=? 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 @@ -173,6 +346,6 @@ func automaticSourceSuperseded(ctx context.Context, tx *sql.Tx, r Run) (bool, er AND (SELECT count(*) FROM events witness WHERE witness.project_id=parent.project_id AND witness.resource_id=parent.id AND witness.event_type='review.selection_requested' AND witness.revision=1)=1 ) -)`, r.ProjectID, r.Channel, r.ID, comparedAt, r.ProjectID, r.Channel, comparedAt, r.ProjectID, accepted, r.Channel, r.ProjectID, accepted, r.Channel).Scan(&superseded) +)`, r.ProjectID, r.Channel, r.ID, r.ProjectID, r.Channel, 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 00000000..d8402c32 --- /dev/null +++ b/internal/reviewexec/scheduling_source_retry_test.go @@ -0,0 +1,532 @@ +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 TestAutomaticHostedFreshBasisAfterPullPauseAndResume(t *testing.T) { + f, original := sourceRetryFixture(t) + schedulingPause(t, f, 2, 0, true) + schedulingPause(t, f, 2, 1, false) + schedulingGenerate(t, f, true) + selectionNext(t, f, &refreshTestReader{}) + retained := selectionRead(t, f, original.ID) + fresh := schedulingLatest(t, f) + if retained.State != original.State || retained.Revision != original.Revision || retained.OperationID != "" || + fresh.ID == original.ID || fresh.State != "selected" || fresh.OperationID == "" { + t.Fatalf("fresh selection did not preserve the original source hold: old=%+v new=%+v", retained, fresh) + } + if operations := attemptCount(t, f.store, `SELECT count(*) FROM review_operations`); operations != 1 { + t.Fatalf("created %d review operations; want one", operations) + } +} + +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) + var basis string + var schedulingRevision int64 + 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": + 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+`'`) + 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, basis, schedulingRevision, 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 TestAutomaticSourceRetryFencesEventlessSuccessorAfterClockRollback(t *testing.T) { + for _, channel := range []string{"hosted", "cli"} { + for _, kind := range []string{"selection", "operation"} { + t.Run(channel+"/"+kind, func(t *testing.T) { + f, r := sourceRetryFixture(t) + ageSourceRetry(t, f, r.ID) + at := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano) + switch kind { + case "selection": + later, _ := selectionEnqueue(t, f, "eventless-later-selection", channel, nil) + 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, at, later.ID) + // Supported restore still recognizes this legacy explicit row. + if err := ValidateSelectionSnapshot(t.Context(), f.store.DB()); err != nil { + t.Fatalf("legacy selection rejected: %v", err) + } + case "operation": + later := f.enqueue(t, attemptProject, "eventless-later-operation", channel, 2, 1) + admissionSQL(t, f, `DELETE FROM events WHERE event_type='review.requested' AND resource_id=?`, later.ID) + admissionSQL(t, f, `UPDATE review_operations SET created_at=?,updated_at=? WHERE id=?`, at, at, later.ID) + } + if worked := retrySourceDirect(t, f, r, time.Now()); worked != (channel != r.Channel) { + t.Fatalf("retry=%t for %s successor against %s source", worked, channel, r.Channel) + } + }) + } + } +} + +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 + 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"}) + 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) + 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 != "" || got.Reason != want { + 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 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) + 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") + } +} + +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 TestAutomaticInitialReadHonorsInterveningIntent(t *testing.T) { + for _, withIntervening := range []bool{false, true} { + name := "no-intervening" + if withIntervening { + name = "cancelled-intervening" + } + t.Run(name, func(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) + if withIntervening { + 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 withIntervening { + if got.State != "held" || got.Reason != "selection_superseded" || got.OperationID != "" { + t.Fatalf("later cancelled intent did not fence recovery: %+v", got) + } + } else if got.State != "selected" || got.OperationID == "" { + 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 dacd93e5..b8f6d930 100644 --- a/internal/reviewexec/scheduling_test.go +++ b/internal/reviewexec/scheduling_test.go @@ -6,29 +6,39 @@ import ( "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" + "sync/atomic" "testing" + "testing/synctest" "time" - - "github.com/benhook1013/FireController/internal/core" ) func schedulingFixture(t *testing.T) *attemptFixture { return schedulingFixtureWithQueue(t, []int64{2, 4}) } - func schedulingFixtureWithQueue(t *testing.T, queue []int64) *attemptFixture { - t.Helper() f := selectionFixtureWithQueue(t, queue) + 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"}) @@ -36,6 +46,40 @@ func schedulingPause(t *testing.T, f *attemptFixture, pull, revision int64, paus 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 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) @@ -50,9 +94,9 @@ func TestSchedulingHTTPDefaultsStrictCASAndPermissions(t *testing.T) { f.handler.ServeHTTP(w, r) return w } - project := call("GET", "scheduling", f.reader, "", "") - if project.Code != 200 || strings.TrimSpace(project.Body.String()) != `{"paused_pulls":[],"project_id":"exec-project-one","revision":0,"automatic_cli":false,"automatic_hosted":false}` { - t.Fatal(project.Code, project.Body.String()) + 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()) } checkPullScheduling := func(w *httptest.ResponseRecorder, revision int64, paused bool, reason string) { t.Helper() @@ -62,51 +106,60 @@ func TestSchedulingHTTPDefaultsStrictCASAndPermissions(t *testing.T) { t.Fatal(w.Code, w.Body.String()) } } - const pull = "pulls/2/scheduling" - checkPullScheduling(call("GET", pull, f.reader, "", ""), 0, false, "") - for _, path := range []string{"scheduling", pull} { + 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") { t.Fatalf("HEAD %s must use the read path: status=%d body=%s", path, head.Code, head.Body.String()) } } - journal := snapshotTable(t, f, "events") - // Even a project manager cannot turn on generation through this foundation slice. + 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()) + } + } + 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'`) - if w := call("POST", "scheduling", f.writer, "disabled-project-post", `{"expected_revision":0,"automatic_hosted":true,"automatic_cli":true}`); w.Code != http.StatusMethodNotAllowed { + w = call("POST", "scheduling", f.writer, "enable", `{"expected_revision":0,"automatic_hosted":true}`) + if w.Code != 200 { t.Fatal(w.Code, w.Body.String()) } - if w := call("GET", "scheduling", f.reader, "", ""); w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), project.Body.Bytes()) || journal != snapshotTable(t, f, "events") { - t.Fatal("project POST changed scheduling or history", w.Code, w.Body.String()) + 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) } - admissionSQL(t, f, `UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`) - const pause = `{"expected_revision":0,"paused":true,"reason":"Fixing"}` - if w := call("POST", pull, f.reader, "reader-pause", pause); w.Code != http.StatusForbidden { + 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, "", "") + var enabledScheduling Scheduling + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &enabledScheduling) != nil || enabledScheduling.Revision != 1 || !enabledScheduling.AutomaticHosted { + t.Fatalf("Hosted scheduling not enabled: HTTP %d: %s", w.Code, w.Body.String()) + } + 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", pull, f.writer, core.NewID("key"), body); w.Code != 400 { + if w = call("POST", "pulls/2/scheduling", f.writer, core.NewID("key"), body); w.Code != 400 { t.Fatal(w.Code, w.Body.String()) } } - first := call("POST", pull, f.writer, "pause", pause) - var receipt Receipt - if first.Code != http.StatusOK || json.Unmarshal(first.Body.Bytes(), &receipt) != nil || receipt.ID != "2" || receipt.State != "pull_scheduling_updated" || receipt.Revision != 1 { - t.Fatal(first.Code, first.Body.String()) - } - checkPullScheduling(call("GET", pull, f.reader, "", ""), 1, true, "Fixing") - if w := call("POST", pull, f.writer, "stale", `{"expected_revision":0,"paused":false}`); w.Code != http.StatusConflict { + 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", pull, f.writer, "pause", pause); w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), first.Body.Bytes()) { + 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()) } - if w := call("POST", pull, f.writer, "resume", `{"expected_revision":1,"paused":false,"reason":"discarded"}`); w.Code != 200 { - t.Fatal(w.Code, w.Body.String()) + checkPullScheduling(call("GET", "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) } - checkPullScheduling(call("GET", pull, f.reader, "", ""), 2, false, "") } - func TestSchedulingPausedBothChannelsPreservesQueuedIdentityAndOperationPause(t *testing.T) { f := schedulingFixture(t) r := f.enqueue(t, attemptProject, "existing", "cli", 2, 1) @@ -145,6 +198,116 @@ func TestSchedulingPausedBothChannelsPreservesQueuedIdentityAndOperationPause(t 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, true) + 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) @@ -178,8 +341,7 @@ func TestSchedulingCooldownPauseKeepsOriginalTimerAndCollectionContinues(t *test } // A pause after issuance never prevents retaining/settling the original result. g, active, capture := hostedPublicationFixture(t, true) - pause = true - if _, err = g.e.ConfigurePullScheduling(t.Context(), g.scope(t, attemptProject, g.writer, false), "pause-issued", 2, PullSchedulingRequest{ExpectedRevision: &zero, Paused: &pause}); err != nil { + 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) @@ -193,8 +355,7 @@ func TestSchedulingCooldownPauseKeepsOriginalTimerAndCollectionContinues(t *test t.Fatal(count) } } - -func TestSchedulingFinalActionPauseRace(t *testing.T) { +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) @@ -211,8 +372,237 @@ func TestSchedulingFinalActionPauseRace(t *testing.T) { 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 := f.e.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 := f.e.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) @@ -227,8 +617,644 @@ func TestSchedulingPauseBeforeAnyIntentBulkReadAndUnenrolledIsolation(t *testing 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("manual pause created review work") + 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 || driver.prepares.Load() != 1 { + t.Fatal("admission failed to refuse before external dispatch", 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) + expected := "automation_authorization_changed" + if change == "pause" { + expected = "pull_scheduling_paused" + } + if err != nil || hosted.State != "queued" || hosted.Reason != expected || hosted.AttemptID != "" || hosted.ID != r.OperationID { + t.Fatal("refused preparation lost queued identity", 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 _, 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(tc.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) + } + 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 { + 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) + } + } +} + +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) { + 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) + } + 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") + } + 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) + } + }() + // 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") + } + 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) + first, second := <-results, <-results + accepted := 0 + for _, r := range []result{first, second} { + 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) + } + } + }) + } } } @@ -244,7 +1270,9 @@ func TestSchedulingQueuedPauseDiagnosticPrecedence(t *testing.T) { } r := f.enqueue(t, attemptProject, "queued-pause", channel, pull, 1) scope := selectionScope(t, f, attemptProject, f.writer, "write") - admissionSQL(t, f, `INSERT INTO review_operation_waits(operation_id,baseline_attempt_id,retry_not_before,paused) VALUES(?,NULL,'',0)`, r.ID) + 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) } @@ -295,7 +1323,7 @@ func TestSchedulingPausePreservesRetainedCooldown(t *testing.T) { } scope := f.scope(t, attemptProject, f.writer, false) pause := func(revision int64, paused bool) { - _, err := f.e.ConfigurePullScheduling(t.Context(), scope, core.NewID("timer-pause"), 2, PullSchedulingRequest{ExpectedRevision: &revision, Paused: &paused}) + _, 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) } @@ -428,24 +1456,47 @@ func validateSchedulingSnapshotForTest(t *testing.T, f *attemptFixture) error { }) } +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 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 { + t.Fatalf("valid schema version %s rejected: %v", tc.version, err) + } + }) + } +} + func TestValidateSchedulingSnapshotRejectsStaleProjectProjection(t *testing.T) { f := schedulingFixture(t) - scope := selectionScope(t, f, attemptProject, f.writer, "write") - at := stamp() - // Retained inputs only: model an accepted enable followed by a disable. - // The current row and both journal events must agree before simulating a - // stale projection. No selection or provider action is constructed. - admissionSQL(t, f, `INSERT INTO review_scheduling - (project_id,revision,automatic_hosted,automatic_cli,actor_id,worker_id,credential_id,updated_at) - VALUES(?,2,0,0,?,'','',?)`, attemptProject, scope.PrincipalID, at) - admissionSQL(t, f, `INSERT INTO events(project_id,event_type,resource_id,revision,actor_id,payload_json,created_at) VALUES - (?,'review.scheduling_updated',?,1,?,'{"automatic_hosted":true,"automatic_cli":false}',?), - (?,'review.scheduling_updated',?,2,?,'{"automatic_hosted":false,"automatic_cli":false}',?)`, - attemptProject, attemptProject, scope.PrincipalID, at, attemptProject, attemptProject, scope.PrincipalID, at) + 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) if err := validateSchedulingSnapshotForTest(t, f); err != nil { t.Fatalf("healthy rev-2 projection rejected: %v", err) } - admissionSQL(t, f, `UPDATE review_scheduling SET revision=1,automatic_hosted=1,worker_id='selection-worker',credential_id='exec-writer-cred' WHERE project_id=?`, attemptProject) + // 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") } @@ -453,7 +1504,13 @@ func TestValidateSchedulingSnapshotRejectsMissingPausedPullProjection(t *testing f := schedulingFixture(t) schedulingPause(t, f, 2, 0, true) schedulingPause(t, f, 4, 0, true) - schedulingPause(t, f, 4, 1, false) + 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) } @@ -466,10 +1523,16 @@ func TestValidateSchedulingSnapshotRejectsMissingPausedPullProjection(t *testing } func TestValidateSchedulingSnapshotRejectsMalformedAndFutureVersions(t *testing.T) { - for _, version := range []string{"not-a-version", "3"} { - t.Run(version, func(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'`, version) + admissionSQL(t, f, `UPDATE metadata SET value=? WHERE key='schema:review_scheduling'`, tc.version) attemptCode(t, validateSchedulingSnapshotForTest(t, f), "storage_unavailable") }) } @@ -483,6 +1546,63 @@ func TestValidateSchedulingSnapshotRequiresPresentDomainMetadata(t *testing.T) { } } +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) +} + func TestSchedulingWaitSnapshotRequiresActualDraftProof(t *testing.T) { f := schedulingFixture(t) r := f.enqueue(t, attemptProject, "scheduling-only-cli", "cli", 2, 1) @@ -500,3 +1620,91 @@ func TestSchedulingWaitSnapshotRequiresActualDraftProof(t *testing.T) { t.Fatal("scheduling-only history was accepted as draft proof") } } + +func TestAutomaticSelectionDoesNotSettleNewlyExposedQueueSuffix(t *testing.T) { + 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) + } + 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) + } + generate(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.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/selection_quarantine_custody_test.go b/internal/reviewexec/selection_quarantine_custody_test.go new file mode 100644 index 00000000..55211b7e --- /dev/null +++ b/internal/reviewexec/selection_quarantine_custody_test.go @@ -0,0 +1,179 @@ +package reviewexec + +import ( + "context" + "database/sql" + "errors" + "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") + +} + +func TestSelectionQuarantineRefusesEqualNonTextActors(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) + if r.State != "selected" || r.OperationID == "" { + t.Fatal("missing retained child") + } + 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 + } + for _, change := range []struct{ query, id string }{ + {`UPDATE review_operations SET actor_id=CAST(actor_id AS BLOB) WHERE id=?`, r.OperationID}, + {`UPDATE review_automatic_selections SET actor_id=CAST(actor_id AS BLOB) WHERE selection_id=?`, r.ID}, + {`UPDATE review_selections SET state='selecting',actor_id=CAST(actor_id AS BLOB) WHERE id=?`, r.ID}, + } { + if _, err := tx.ExecContext(ctx, change.query, change.id); err != nil { + _, resetErr := tx.ExecContext(ctx, `PRAGMA ignore_check_constraints=OFF`) + return errors.Join(err, resetErr) + } + } + 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 { + t.Fatal(err) + } + var custody int + if err := f.store.DB().QueryRow(`SELECT count(*) FROM review_selection_quarantine WHERE selection_id=?`, r.ID).Scan(&custody); err != nil || custody != 0 { + t.Fatalf("unexpected custody record: count=%d err=%v", custody, err) + } +} diff --git a/internal/reviewexec/selection_queued_prefix_test.go b/internal/reviewexec/selection_queued_prefix_test.go new file mode 100644 index 00000000..8ed959a9 --- /dev/null +++ b/internal/reviewexec/selection_queued_prefix_test.go @@ -0,0 +1,41 @@ +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 + }} + choice, err := f.e.chooseRunWithSourceBudget(t.Context(), r, 801, c, reader, time.Second) + if err != nil { + t.Fatal(err) + } + if len(choice.prefix) != 1 || choice.prefix[0].Pull.Number != 2 || choice.prefix[0].SourceReason != "pull_draft" { + t.Fatal("did not acquire the eligible draft PR 2 prefix", choice.prefix) + } + if suffix.Load() != 0 { + t.Fatal("read ineligible queued suffix", suffix.Load()) + } +} diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index d2142b40..a9756917 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -468,6 +468,14 @@ 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 { + if e.independentProbeDeferred(o) { + return Operation{}, nil + } + 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 } @@ -829,13 +837,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. @@ -861,7 +873,15 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri 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 @@ -896,6 +916,7 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri 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() @@ -968,6 +989,14 @@ func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Dri } 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, true) if err != nil { var preparedRefusal *preparedCLIAdmissionRefusal diff --git a/internal/reviewexec/types.go b/internal/reviewexec/types.go index 7876477e..74402562 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"` @@ -113,11 +115,20 @@ type Attempt struct { type Engine struct { cliExhaustionRecovery CLIExhaustionRecoverySource + automaticCursor string + automaticCLICursor string + automaticCLIOtherCursor string + automaticMu sync.Mutex + automaticNext time.Time runSourceBudget time.Duration schedulingNow func() time.Time configurationFailureMu sync.Mutex configurationFailureNext map[string]time.Time draftProbePermit atomic.Bool + 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/reviewruntime/cli_driver.go b/internal/reviewruntime/cli_driver.go index 8f824268..6586b434 100644 --- a/internal/reviewruntime/cli_driver.go +++ b/internal/reviewruntime/cli_driver.go @@ -144,6 +144,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 @@ -336,3 +339,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_cooldown_retry_test.go b/internal/reviewruntime/hosted_cooldown_retry_test.go index c0a5764d..c1226f4b 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_driver.go b/internal/reviewruntime/hosted_driver.go index c253e3fc..e00a4d82 100644 --- a/internal/reviewruntime/hosted_driver.go +++ b/internal/reviewruntime/hosted_driver.go @@ -132,6 +132,14 @@ func (d *HostedDriver) purgePrepared() { } } +// Preserve explicit scheduling refusals without promoting generic retention +// failures or unknown outcomes to resumable review work. +func hostedRetentionSchedulingRefusal(err error) bool { + var failure *core.Error + return errors.As(err, &failure) && + (failure.Code == "pull_scheduling_paused" || failure.Code == "automation_authorization_changed") +} + func (d *HostedDriver) Prepare(ctx context.Context, operation reviewexec.Operation, configuration reviewexec.Configuration, attempt reviewexec.Attempt) (preparation reviewexec.Preparation, failure error) { if ctx == nil { return preparation, reviewHold("execution_binding_changed") @@ -178,6 +186,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 } @@ -206,6 +217,9 @@ func (d *HostedDriver) Prepare(ctx context.Context, operation reviewexec.Operati if err := retryAllowanceRetention(ctx, d.wait, func() error { return RetainHostedCooldown(ctx, d.captures, d.engine, attempt, anchor, fileCount, observed.Capture) }); err != nil { + if ctx.Err() == nil && hostedRetentionSchedulingRefusal(err) { + return preparation, err + } if retryableHostedRetention(err) || ctx.Err() != nil { return preparation, &reviewexec.PreparationRecoveryError{Err: err} } @@ -226,6 +240,9 @@ func (d *HostedDriver) Prepare(ctx context.Context, operation reviewexec.Operati if ctx.Err() != nil { return preparation, ctx.Err() } + if hostedRetentionSchedulingRefusal(err) { + return preparation, err + } return preparation, reviewHold("hosted_allowance_unproven") } if _, err := retainHostedBaseline(ctx, d.provider, d.captures, d.engine, attempt, anchor, actor, d.providerActor()); err != nil { @@ -332,3 +349,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 } diff --git a/internal/reviewruntime/hosted_driver_test.go b/internal/reviewruntime/hosted_driver_test.go index 63f7bf4c..7b872f1f 100644 --- a/internal/reviewruntime/hosted_driver_test.go +++ b/internal/reviewruntime/hosted_driver_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/benhook1013/FireController/internal/core" "github.com/benhook1013/FireController/internal/reviewexec" "github.com/benhook1013/FireController/internal/reviewprovider" ) @@ -206,6 +207,103 @@ func hostedDriverJournal(t *testing.T, f *hostedDriverFixture, id string) string return state } +type pauseAfterHostedReply struct { + *driverHostedProvider + pause func(context.Context) error +} + +func (p *pauseAfterHostedReply) IssueComments(ctx context.Context, repo string, pull int64) ([]reviewprovider.IssueComment, error) { + comments, err := p.driverHostedProvider.IssueComments(ctx, repo, pull) + if err != nil { + return nil, err + } + for _, comment := range comments { + if p.pause != nil && comment.ID == 101 { + pause := p.pause + p.pause = nil + if err := pause(ctx); err != nil { + return nil, err + } + } + } + return comments, nil +} + +func TestHostedAllowanceRetentionKeepsAcceptedOperationOnPullPause(t *testing.T) { + for _, cooldown := range []bool{false, true} { + t.Run(map[bool]string{false: "available", true: "cooldown"}[cooldown], func(t *testing.T) { + f := newHostedDriverFixture(t) + if cooldown { + f.provider.reply = strings.Replace(runtimeAllowanceAvailable, "Reviews are available now.", "More reviews will be available in 3 minutes.", 1) + } + o, a, c := f.startHosted(t) + scope := f.scope(t, f.writer, false) + zero, one := int64(0), int64(1) + paused, resumed := true, false + f.hosted.provider = &pauseAfterHostedReply{driverHostedProvider: f.provider, pause: func(ctx context.Context) error { + _, err := f.engine.ConfigurePullScheduling(ctx, scope, "hosted-allowance-pause", o.PullNumber, reviewexec.PullSchedulingRequest{ExpectedRevision: &zero, Paused: &paused}) + return err + }} + _, err := f.hosted.Prepare(t.Context(), o, c, a) + var refusal *core.Error + if cooldown { + if !errors.As(err, &refusal) || refusal.Code != "review_held" { + t.Fatalf("cooldown refusal lost: %v", err) + } + details, _ := refusal.Details.(map[string]string) + if details["reason"] != "hosted_allowance_cooldown" { + t.Fatalf("wrong hold reason: %v", refusal.Details) + } + var body string + if err := f.store.DB().QueryRow(`SELECT body_json FROM review_hosted_preflight WHERE project_id=? AND attempt_id=?`, o.ProjectID, a.ID).Scan(&body); err != nil { + t.Fatal(err) + } + var stored struct { + Input reviewexec.HostedAllowanceInput `json:"input"` + } + if err := json.Unmarshal([]byte(body), &stored); err != nil { + t.Fatal(err) + } + observation := stored.Input.Observation + if observation.State != "cooldown_observed" || !observation.RetryNotBefore.After(observation.ResponseCreatedAt) { + t.Fatalf("cooldown deadline lost: %+v", observation) + } + _, err = f.engine.ExecutionContext(t.Context(), f.project, o.ID) + if !errors.As(err, &refusal) || refusal.Code != "pull_scheduling_paused" { + t.Fatalf("ordinary execution was not paused: %v", err) + } + if _, err := f.engine.ScheduleHostedCooldown(t.Context(), f.project, a.ID, a.Revision); err != nil { + t.Fatal(err) + } + waiting, err := f.engine.ReadOperation(t.Context(), scope, o.ID) + if err != nil || waiting.ID != o.ID || waiting.State != "queued" || waiting.AttemptID != "" || waiting.Wait == nil || waiting.Wait.BaselineAttemptID != a.ID || waiting.Wait.RetryNotBefore != observation.RetryNotBefore.Format(time.RFC3339Nano) { + t.Fatalf("original operation did not retain its wait: %+v, %v", waiting, err) + } + if f.provider.queries != 1 || f.provider.reviews != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_execution_reservations`) != 0 { + t.Fatal("paused operation dispatched a review or retained capacity") + } + return + } + if !errors.As(err, &refusal) || refusal.Code != "pull_scheduling_paused" { + t.Fatalf("scheduling refusal lost: %v", err) + } + if f.provider.queries != 1 || f.provider.reviews != 0 || cliCount(t, f.store, `SELECT count(*) FROM review_hosted_preflight`) != 0 { + t.Fatal("paused operation started or retained new allowance") + } + if _, err := f.engine.Advance(t.Context(), f.project, a.ID, a.Revision, "held", refusal.Code, ""); err != nil { + t.Fatal(err) + } + if _, err := f.engine.ConfigurePullScheduling(t.Context(), scope, "hosted-allowance-resume", o.PullNumber, reviewexec.PullSchedulingRequest{ExpectedRevision: &one, Paused: &resumed}); err != nil { + t.Fatal(err) + } + next, err := f.engine.StartAttempt(t.Context(), f.project, o.ID) + if err != nil || next.ID == a.ID || next.OperationID != o.ID { + t.Fatalf("ordinary resume changed request: %v", err) + } + }) + } +} + func TestHostedDriverQueryAdmitPublishThenSupervisorSettlement(t *testing.T) { f := newHostedDriverFixture(t) op, a := f.prepareHosted(t) diff --git a/internal/reviewruntime/hosted_preflight.go b/internal/reviewruntime/hosted_preflight.go index a61b7358..e7d6d26a 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 }