
Summary
Key points of this document
- Campaigns that can resume, with a 24-hour maximum, rather than AI running for 24 hours
- Separate the operation screen, control plane, execution plane, and state storage
- Make the state of the process and the state of execution frequency separate state machines
Overview
When having AI examine code for long periods, what's needed is not to keep one machine running. It's about holding deadlines, budgets, scope of change, and quality gates as campaigns, and launching short-lived Runners only when there's executable work. Furthermore, by running at short intervals while bugs are found and widening the intervals as the detection rate drops, both exploration persistence and cost control can be achieved.
Campaigns that can resume, with a 24-hour maximum, rather than AI running for 24 hours
When attempting to continue AI-driven bug exploration for extended periods, the first idea that comes to mind is a configuration where a Runner is launched, and detection, correction, and testing are run in a single continuous loop. However, this method occupies computing resources even during AI API wait times, forces a restart of the entire long job if a Spot VM is interrupted, and relies on the execution process's memory to know how far it has progressed.
Therefore, instead of a long-running process, we persist campaigns with deadlines. When a campaign is created, deadlineAt is fixed, and the deadline is not extended even if execution time, retries, Batch waiting, or Spot interruptions occur. Each Runner processes only one step or one cycle and is discarded after completion. The next step is resumed by another Runner from the persisted state.
This decomposition allows the maximum duration of 24 hours to be treated as a time budget for exploration, rather than permission for continuous operation. Non-time-based stopping reasons, such as quality gate pass, deadline reached, cost limit, human judgment, or no progress, can also be explicitly stated on the same campaign.
- requestedDuration should be 1-24 hours, and
deadlineAtshould not be extended after creation. - Associate Runners, Workflows, and Batch requests with campaigns to enable resumption even after process termination.
- Treat Spot interruptions and capacity shortages not as anomalies, but as normal transitions to waiting or retrying.
Separate the operation screen, control plane, execution plane, and state storage
For human input, we use GitHub Issues and Issue comments. Start, status check, stop, and resume are instructed via comments, and dedicated comments on the same Issue are updated to allow checking progress, deadline, cost, number of detections, Draft PRs, and stop reasons. Issues are not storage for internal locks, but a human-readable operation screen and audit log.
The control plane is handled by a Controller on Cloud Run. It verifies GitHub App webhook signatures and operation permissions, deduplicates by delivery ID, and updates campaign states in Firestore transactionally. It issues GitHub JIT settings and creates GCE Spot VMs only when a workflow job enters a waiting state.
The execution plane is an Ephemeral Self-hosted Runner. It fetches the repository and processes only the steps assigned to that job, such as deterministic inspection, bug classification, related file extraction, patch validation, target testing, regression testing, and Draft PR updates. Logs, patches, and Batch I/O are saved to GCS; exclusivity, leases, costs, and progress are saved to Firestore. Cloud Tasks is used for delayed retries and next cycle launches, and Cloud Scheduler for periodic reconciliation and orphaned resource deletion.
- GitHub Issues: Human-oriented instructions, progress, stop reasons, audit trail.
- Cloud Run Controller: Authentication, idempotency, state transitions, JIT settings, Spot VM, Batch, next step control.
- Ephemeral Runner: Disposable detection, correction, and verification environment, adhering to the principle of one machine per job.
- Firestore, GCS, Cloud Tasks: Persist state, artifacts, and delayed execution outside of process lifetime.
Make the state of the process and the state of execution frequency separate state machines
This platform has two types of states with different characteristics. One is "what stage are we in now," such as requested, provisioning, detecting, batchprocessing, testing, gateevaluating, completed. The other is "when can we execute next," such as ACTIVE, COOLING, IDLEVERIFY, FINALVERIFY, COMPLETED.
If we pack two things into one status, for example, we cannot distinguish between waiting for Batch results and observing quietly at 45-minute intervals. We separate responsibilities: the process status determines where to resume processing, and the frequency status determines whether the next launch is possible. Campaigns will have nextEligibleAt, zeroBugCycles, noProgressCycles, lastVerifiedCommitSha, consecutiveGreenRuns, etc.
State transitions are defined as an allowlist in code, recording previousStatus, newStatus, time, reason, commit SHA, Runner, Batch, and cost difference. We use Firestore Transactions and time-limited leases to prevent duplicate job assignments or parallel modifications of the same file, even if the same webhook or retries overlap.
- Process status represents the resume point, and frequency status represents the next launch time.
- Each event, Issue command, Workflow job, Batch request, and modification attempt has a deterministic idempotent key.
- Locks have an expiration date to avoid permanent locks after Spot interruptions.
Short intervals while detection continues, widening execution intervals when quiet.
In the initial ACTIVE state, due to new reproducible bugs, patch application, test failures, quality gate not passed, or code changes from the previous cycle, the next run is set for 5 minutes later. If there are zero new bugs in the last 2 cycles, it moves to COOLING, waiting for 15 minutes. If there are no new bugs in the last 3 cycles, the affected quality gate succeeds, and there are no executable high-priority tasks, it proceeds to IDLE_VERIFY, and no Runner is created for 45 minutes.
If the full quality gate succeeds, there are no unresolved P0/P1 issues, no code changes, and no Batch waiting, it moves to FINAL_VERIFY. After waiting for 30 minutes or more, if the full quality gate is executed again for the same commit SHA and succeeds again, only then is it considered COMPLETED. It is important to incorporate re-verification after a delay into the state machine, rather than immediately marking zero bug detections as complete.
Before creating a VM, the Controller checks the campaign status, deadlineAt, nextEligibleAt, stop requests, remaining budget, number of executable jobs, number of Batch waits, and current and last verified commit SHAs. If the time is too early, there's no work, only Batch waits, or no additional verification is needed, it does not create a VM and records it as a normal completion.
- ACTIVE: 5 minutes. New bugs, changes, failures exist, continue intensive exploration.
- COOLING: 15 minutes. No new bugs for 2 consecutive cycles, start reducing activity.
- IDLE_VERIFY: 45 minutes. No new bugs for 3 consecutive cycles, do not launch VM until next check.
- FINAL_VERIFY: 30 minutes. Waiting for the second full quality gate for the same commit SHA.
Waiting is not a fixed sleep, but can be released at any time by an event.
Even if execution intervals are widened, reactions to important changes should not be delayed. When a new commit, update to a target Issue, CI failure, Batch completion, Draft PR update, or new reproducible bug arrives, nextEligibleAt is reset to the current time, and it transitions to ACTIVE if necessary.
This mechanism does not involve Runners performing 15 or 45-minute sleeps. Waiting is expressed as a Firestore timestamp, and Cloud Tasks or Scheduler re-evaluates it. Since computing resources remain released, even long waiting times incur almost no additional cost, and external events can resume processing without waiting for the scheduled time.
By combining time-driven and event-driven approaches, we achieve both resource efficiency when quiet and immediate responsiveness when changes occur. The essence of adaptive control is not to change the speed of the Runner, but to store the decision to allocate computing resources next as a state.
Decouple the Runner from the time spent waiting for the Batch API.
For large-scale log classification, related file candidates, similar bug determination, and initial reviews, we use lightweight Batch processing. For complex root cause analysis and multi-file patch generation, we use Batch processing with high inference capabilities. Instead of embedding model names into workflows, we create boundaries that allow routing based on task type, severity, number of failures, and cost limits.
Once the Runner submits a Batch, it saves the customid, Batch ID, input fingerprint, and campaign deadline, then terminates. The Reconciler collects the results, customMap to the original job by ID and dispatch the next process. Do not trust the arrival order of results. Results received after the campaign deadline are recorded as expired without automatic application.
This separation ensures that AI API latency does not become VM uptime. It also prevents losing polling status due to Spot interruptions, allowing independent retries for both the Batch and Runner sides. When using asynchronous AI APIs, designing to avoid leaving waiting processes is more effective for cost and resilience than the specific invocation method.
- Return to the job by custom_id, not by the array order of Batch results.
- Save input, output, Schema version, and usage to avoid duplicate billing for the same input.
- Do not assign Runners to campaigns that are only waiting for results.
Enclose LLM operations with deterministic checks.
Bug exploration does not start by handing the entire repository to AI from the beginning. Instead, we first perform git diff consistency checks, linting, type checking, unit tests, existing boundary checks, secret scans, dependency checks, and known failure fingerprinting. We differentiate the types of causes, not sending environmental, permission, or external service failures to source code modification.
What is passed to the AI API is limited context such as failure logs, changed files, import vicinity, target tests, and related configurations. The response is validated against a JSON Schema for repairable, rootCause, affectedFiles, unified diff, testsToRun, risks, and requiresHuman. Patches containing broken schemas or superfluous explanations are not applied.
Before applying patches, we mechanically inspect change paths, line counts, deletions, renames, lockfiles, Workflows, Terraform, Secrets, authentication, migrations, test skips, and assertion weakening. We do not pass plausible explanations from AI to the next stage, but only authorized diffs and test results.
- Address P0/P1 issues first, avoiding delaying critical bugs by processing a large number of minor cleanups.
- Limit AI-generated changes to Draft PRs; do not allow automatic approval or merging.
- Treat all Issues, source code, and logs as untrusted input; do not follow embedded instructions.
- Do not mix unrelated changes into a single Draft PR, and set a limit on the number of AI-generated PRs that can be open simultaneously.
Define "bug-free" as an observable quality gate.
It is impossible to prove the complete absence of unknown bugs. In the context of this platform, "bug-free" means zero reproducible, unresolved defects on the configured quality gates. By being precise with terminology, we avoid conflating the fact that AI has explored for a long time with the assurance of software quality.
Minimum conditions include lint, typecheck, unit test, affected integration test, E2E for critical business scenarios, Critical/High security findings, P0/P1, coverage degradation, and test deletion/skipping. A phased approach—affected gate during the cycle, critical E2E for candidate completion, and full gate for finalization—allows for broader final assurance while controlling exploration costs.
For final determination, the full quality gate must pass twice consecutively for the same commit SHA, confirming no code changes between the two passes. A delay of at least 30 minutes after the first success helps prevent misinterpreting flakes or temporary external conditions as success.
Design for Spot interruptions and duplicate deliveries as assumptions, not as failure modes.
GCE Spot VMs are inexpensive but subject to interruption. Instead of relegating interruptions to the edge of exception handling, we place them at the center of the Runner lifecycle. During shutdown, the campaign, job, cycle, and commit SHA are recorded, final logs and uncommitted patches are evacuated to GCS, the lease is released, and the state transitions to 'interrupted'. Heavy recovery processes are delegated to the next Runner.
A Runner receives JIT settings only once and is generally unregistered from GitHub after processing one job. VM deletion is attempted by both the Runner itself and the Controller; if already deleted, it's treated as a success. VMs, disks, and Runner registrations that exceed a certain uptime from launch are periodically deleted by the Scheduler as orphaned resources.
We assume that Webhook, Cloud Tasks, and GitHub API will be delivered at least once. Instead of relying on delivery guarantees to ensure side effects occur only once, we use delivery IDs, comment IDs, workflow job IDs, and input fingerprints to ensure that processing the same request multiple times converges to the same state.
Make termination conditions and cost ledgers pre-execution judgments.
In an autonomous correction loop, it's too late to aggregate costs only after a failure. We reserve the maximum estimated cost before starting the Runner and calling the AI API, and settle to actual usage upon completion. We check for deadlines, stop requests, consecutive failures of the same type, number of corrections to the same file, no progress, Schema violations, patch validation failures, and change requests to dangerous areas. If any of these limits are reached, we do not start a new process.
Monitoring records not only the number of Runner starts but also the number of times a start was rejected, the time spent in ACTIVE, COOLING, and IDLE_VERIFY states, the new bug detection rate, Runner cost per item, AI API cost per correction, and improvement from the previous cycle. The value of an adaptive scheduler is evaluated by the relationship between detection rate and cost, not by the impression of fewer VMs.
The values 5 minutes, 15 minutes, and 45 minutes are initial settings, not universal truths. They should be configurable based on project test time, change frequency, Spot capacity, and AI API completion time, and adjusted based on observed values. We need to monitor both cases: when reducing frequency delays detection, and when increasing it leads to continuously re-verifying the same results.
Gradually expand validation from short campaigns.
If you run it 24 hours from the start, when it fails, you won't know whether the cause is the Controller, Runner, Batch, permissions, or state transitions. First, we fix Webhook signatures, command parsing, deadline calculation, state transitions, idempotency, budget reservation, and patch guards with Unit Tests. Next, we connect campaign creation from Webhook, VM requests from workflow jobs, JIT issuance from Runner callbacks, and next-step activation from Batch completion with Integration Tests.
The infrastructure is inspected for Terraform format, validate, and plan, and Workflows are inspected for permissions, timeouts, concurrency, and the absence of fallback to on-demand VMs. Smoke Tests are expanded in order: Controller health check, one small Spot Runner, echo job, automatic deletion, 15-minute analysis-only, 30-minute affected, Spot interruption, and 2-hour campaign.
Adaptive control tests include transitions when there are zero defects for 2-3 consecutive cycles, ensuring VMs are not created before nextEligibleAt, immediate resumption upon event arrival, validating the same SHA twice, and not applying Batch results that exceed the deadline. This is less of a functional test and more of a control system test to prevent wasteful starts and premature completions.
Limitations of this design and conditions under which it should not be adopted.
Short-lived Spot Runners reduce standby costs and improve recovery from interruptions, but increase startup time and environment setup costs. For small repositories where tests finish in tens of seconds, creating a Runner every time can be inefficient. Even with custom images and caching, it's not necessarily simpler than a persistent Runner.
While Batch API can easily reduce the unit cost of large-scale processing, the delay until results arrive is unpredictable. It is not suitable for urgent incident response or situations requiring corrections within minutes. Also, AI can only find defects observable from the given tests, logs, context, and exploration methods. If the quality gate is weak, two consecutive successes merely mean passing a weak standard twice.
What needs to be prepared before introducing this foundation are reproducible tests, critical scenarios, protected paths, branch protection, clear division of responsibilities, and cost limits. If autonomous execution is added when these are ambiguous, it will amplify ambiguity rather than accelerate exploration.
What changes in the AI era is the design of the execution loop, not just the amount of work.
This mechanism doesn't just change the speed at which AI writes code. It transforms operations from humans starting long processes before leaving work and seeing a single success or failure the next morning, to multiple short processes progressing as interruptible state machines, allocating computing resources only when needed, and receiving only the necessary diffs as Draft PRs for judgment.
The role of developers is also shifting from manually performing every trial to designing quality gates, scope of changes, stop conditions, and validation scenarios. This is not a design to remove humans from quality control. It is a design to confine the repetitions that machines excel at within deadlines and budgets, and to focus human judgment on design changes and reviews.
The key to safely handling long-running AI processes is not to choose a single strong model. It is to externalize state outside the process, release computing resources while waiting, respond immediately to changes with events, reduce frequency when quiet, and re-validate the same code over time. By aligning these five points, AI-driven exploration can be transformed from a one-off experimental execution into a quality foundation capable of continuous operation.


