# Batch engine

> How the engine reads repositories, looks up updates, builds the report and writes branches.

`patchula-engine::Engine` takes a token, the shared SQLite cache, a concurrency cap and a transport. The CLI builds one network pool; tests inject cassette replay. A lookup takes named repositories or discovers every one the token can reach, through `user/repos` or, for App tokens, the installation repositories endpoint.

## Reading a repository

Repositories run concurrently behind one GitHub governor. On a cold scan, the default branch, commit and tree come from one GraphQL snapshot, and only the selected manager files and the config modules they need are fetched as blobs, in GraphQL batches (see [the GitHub client](https://count-patchula.sweepy.dev/internals/github-client/#conditional-reads)). The tree is listed completely, however large (see [the GitHub client](https://count-patchula.sweepy.dev/internals/github-client/#trees)). A selected file whose blob cannot be fetched or whose contents are not text is an error for that repository — a registry-settings file excepted, which stays unreadable so its packages fail their lookups rather than using a public registry. A file only managers whose file names another format shares select (`pkl`: `.pkl` is also Python’s pickle extension) is left out unread and unreported when it is not text or is over 1 MiB. A symlink is never read through: the entry stays in the extraction as unreadable rather than absent, and a symlinked settings file fails its packages’ lookups the same way. The one exception is a Cargo configuration linked to a file inside the repository: its link is resolved against the tree, through at most eight links, and the file it ends at is read in its place, without a blob for the snapshot. A link that is absolute, climbs out of the repository or ends at anything but a text file leaves it unreadable. The lockfile checkout follows the same links through its clone, so Cargo gets the registries extraction saw. Files the include chain names in later rounds that cannot be read are unreadable too. In a local checkout, files below a symlinked directory are omitted from the tree entirely. A repository without `patchula.pkl` at its root is skipped. A local `--config` applies to every selected repository and is evaluated before network access.

Configs evaluate in isolation over the supplied files. Local `amends` and `import` targets are fetched, and the bundled `PatchulaConfig.pkl` is used when the repository does not vendor it. Remote and absolute imports, and imports that escape the repository, are rejected, and only literal import targets are supported. `config check` and local overrides use the same evaluator.

An unchanged commit and config fingerprint reuses the previous extraction with no tree or blob calls, Pkl evaluation or scanning; the fingerprint’s namespace carries this build’s version, so a release that changes extraction semantics never reuses the previous release’s entries. A new commit reads the tree and the selected files again, but those are cached by blob SHA, and config evaluation and extraction are keyed by the content of the files they read as well: a push that changes no file the scan reads costs one tree request and no Pkl evaluation or scanning. Only the newest of each is asked for again, so a repository keeps one saved config, evaluated config, file extraction and extraction, each holding the commit or content hash it answers for, and a scan under another one replaces it (see [the cache](https://count-patchula.sweepy.dev/internals/cache/#releases-and-state)). The path inventory and unsupported-file list always come from the current tree. A run that will write takes the default branch, its head commit and tree, and the repository’s visibility from its inventory (below), so a configured repository’s run with nothing to change sends the inventory and, on the server, the public record’s conditional visibility read. The scan still reads the head itself when the inventory failed, and for a repository whose last run found no config, which reads no inventory unless the scan finds a config. Any other scan (`lookup`, `--dry-run`, a local directory aside) reads the head itself: warm scans revalidate the repository metadata and the hinted branch in parallel, and always check the current default branch. Catalog, digest and ref requests are deduplicated across the batch. Forge tag catalogs (GitHub tags and releases, forge tags) run in a fan-out of their own beside the registry reads: each is a tag listing followed by serial date pages, the longest chain of a cold lookup, so it starts with the stage instead of behind hundreds of registry reads, and a batch with many of them never holds the registry reads back. Persisted lookup hints let warm source reads — current refs, the mutable tags of GitHub tag catalogs the next run may reuse, and the image tags the last run resolved — overlap revalidation, so the first warm run after a cold one already prefetches them. Hints only schedule work: the validated extraction and policy decide the report, a manual retry reads a hinted answer again, and a prefetched image digest the run no longer wants is dropped. The OSV advisory batch needs only the extraction, so it goes out as soon as the scan ends and the plan names its queries, beside a prefetch that may still be in flight; the catalog and current-ref reads wait for the prefetch, whose answers they reuse. The second pass, which promotes a vulnerable lockfile package and re-reads a vulnerable dependency’s catalog, still runs after the advisories, and reads that catalog live. On the server, a run also builds each complete repository’s inputs from the record its hint is saved from, for the [watch and input rows](https://count-patchula.sweepy.dev/internals/cache/#watch-and-input-rows), and a queued batch’s run serves a catalog from its stored view, whatever the key’s wait, when the [poller](https://count-patchula.sweepy.dev/internals/scheduler/#runs-read-the-store) confirmed the view’s watch row, under the scope it was read from, within its bound, and the view covers the versions the run needs; otherwise it reads through as the CLI does. A writing run reads the catalog of each version it is about to write live first, where the lookup served it from a stored view; when one has changed since, it writes and settles nothing derived from it (closing obsolete PRs comes before the read), and the repository ends `stale` and runs again, reading those catalogs live ([the live read before a write](https://count-patchula.sweepy.dev/internals/scheduler/#the-live-read-before-a-write)). A run that will write reads its control and write inventory first, and the scan extracts at the head that read answered, so the two cannot disagree: the walk anchors its per-page checks on its own first page. It walks under the branch prefix a config override declares, else the one the last receipts were saved under, else the bundled default. A scanned config naming another prefix reads the inventory again, anchored at the scanned head, so a head that moved in between ends the repository `stale`. An inventory that fails is not fatal to the scan: the scan reads the head itself, and a configured repository then reads the inventory again after it. A head that moves after the inventory is caught by the write’s own leases (the base read before publishing, `beforeOid` on every ref update). Sampling the inventory first means non-head state — dashboard edits, merge settings, branch protection, a receipted branch deleted mid-run — can be observed a whole extraction before the writes; it self-corrects next run, and the dashboard write re-reads its issue immediately before patching so an edit landed during the run is never written over.

A complete run stores a `quiet-run` state row per repository and credential scope: the head commit and branch, a hash of the report row (tooling, lookup and release-age evaluation timestamps, catalog evidence, stats and clock fields excluded), `next_due` — the earliest instant time alone can change the answer: a held-back release’s eligibility, a schedule window, a lockfile defer, an hourly PR quota freeing — and what the probe compares: what the run’s inventory saw of the Count’s branches, pull requests and issues, the login it read as, and, when the run wrote, its receipts. A run that finds no `patchula.pkl` stores the head commit, the branch and that it found no config: its answer reads nothing else. A run that does not complete, or completes without one of those pieces, removes the row, and a run about to show a [rebasing banner](https://count-patchula.sweepy.dev/guide/pull-requests/#the-rebasing-banner) removes it before the first one goes up, so a run that stops partway through leaves nothing for the sweep to skip over. The server’s quiet sweep check runs only for batches the sweep alone claimed: candidates are rebuilt from the cached config and extraction without a head check, the hinted digests are prefetched — the only requests a quiet repository makes while the poller keeps its catalogs and OSV listings fresh — and the report is re-evaluated off the same catalogs. Before the rebuild, the batch is probed in one GraphQL query for what each repository’s last run left on GitHub (see [lost webhooks](https://count-patchula.sweepy.dev/internals/scheduler/#lost-webhooks)); a repository whose answer differs runs in full. A repository stays in the quiet set when its rebuilt report hashes the same and its `next_due` has not passed; any missing state, failed reconstruction, passed due or hash mismatch runs it in full — the check fails open toward running, never skipping. A repository whose row says it has no config is quiet without a rebuild while the probe finds no `patchula.pkl` at its head. A full run of such a repository reads no inventory, and its scan reads the head itself, unless a config override applies to it (`--config` for every repository, or its file under `--config-dir`), which always reads one; a scan that finds a config after all reads the inventory once the scan ends.

## Report and exit codes

The report carries the branch and commit, warnings, sources, kinds and locations, per-update policy, request and cache counters, and phase timings. `extraction` includes repository metadata latency even on a warm hit, `lookup` includes source prefetch and catalog work, `policy` is CPU selection and report assembly, and `digest` is any remaining ref wave. `lookup` overlaps `extraction`, so phase times must not be summed.

An unavailable upstream is a warning; API, config and extraction failures are errors. Every warning carries a scope, chosen by its producer: `Repository` when nothing narrower can be named, `File`, `Source`, `Package`, or `Run` for the run’s own writes and caches. There is no default and no conversion from a bare string. The CLI writes the report to stdout, as text or with `--json` as JSON, and `-v` adds the counters and phase timings on stderr. It exits 1 for a batch failure or any per-repository error, and 2 for invalid config or options; `lookup` exits 4 when a lookup failed, while `run` reports failed lookups and exits 0. A `run` where a repository changed underneath it — a race the update layer reports as `Error::Raced` — exits 5 instead, after an error has had its say. The [CLI reference](https://count-patchula.sweepy.dev/reference/cli/) lists every exit code.

## Tests and measurements

Recorded tests replay a public two-repository batch (jdx/usage and jdx/mr-boxington) and the npm, Cargo, Go and GitHub sources. The benchmarks replay those recordings, so they say nothing about a live batch.

```sh
mise run benchmarks:lookup
mise run benchmarks:lookup-release
GH_TOKEN=$(mise exec -- gh auth token) mise run fixtures:record-lookup
mise run fixtures:check
# A live batch: run twice against the same private cache.
mise run lookup:release --config examples/renovate-migration.pkl \
  --cache /tmp/patchula-runner --concurrency 8 --json \
  owner/repo > /tmp/patchula-runner-report.json
# Median phases of five warm `lookup -v` runs against live GitHub.
mise run benchmarks:live --cache /tmp/patchula-runner owner/repo
```

> **Caution**
>
> Cache rows include repository identities and manifest contents. Keep private run caches and reports outside this repository.

## Branch write path

`Engine::run` shares discovery, configuration, lookup and policy with `lookup`. The `extract` state keeps the full path inventory, the lockfile packages checked for advisories with the direct dependencies each lockfile’s graph reaches them from (read during extraction, since the lockfile’s text is not kept), and each read file’s Git blob SHA and mode. It keeps a file’s text only where a later reader reads it: each file an extracted dependency is declared in (edits and the write’s content check), `actions.lock` with the workflows and action files the composite-action walk reads, CI workflows and pipelines, and files declaring Flux or Argo CD resources (the tooling evidence). The rest, such as a large manifest with no dependency in it, keep only the SHA and mode, which the write still checks. A reader that asks for a text that was not kept finds the file unread and holds the plan or leaves the evidence unknown, as for a file the run never fetched.

**Edits.** The updater derives branches and scalar edits from proposals and extracted locations, with explicit renderers for forms such as npm aliases, action refs and comments, and Go directive prefixes. A reference that inherits its version from a root entry (Cargo `workspace = true`, a `catalog:` specifier, a versionless NuGet reference under central package management) is never edited: planning puts it on its root entry’s branch, with the entry’s update, and the entry’s edit moves it. Edits apply in descending byte order after overlap and UTF-8 boundary checks, so all surrounding text is preserved. A location that cannot be edited safely, such as a generated Flux bundle or an expanded Docker `ARG`, is reported as skipped.

**Commits.** Before creating objects, the writer re-reads the default head and tree and checks each extracted blob SHA and content hash; a moved base or stale blob refuses publication. One replacement commit has the default commit as its only parent. No author, committer or signature is supplied, and GitHub must return `verification.verified = true` before a ref is published (see [bot signing](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification#signature-verification-for-bots)).

**Existing branches.** Every commit on the branch that is not on the base must be authored by the authenticated actor, committed by the bot or GitHub, verified, and carry the Count’s version and identity trailers. Otherwise the branch is left alone. The writer proves this by reading the branch ref, its tip commit, a compare from the base the tip records, and the tip’s tree when the plan may already be on it — unless the run’s inventory decoded every ref and found the branch at exactly the commit and tree a [write receipt](https://count-patchula.sweepy.dev/internals/cache/#write-receipts) for the same identity recorded, and the tip’s trailers name the plan’s identity. Then the receipt stands in for the reads: it records the tip’s tree at the plan’s paths, so whether the plan is already there is decided without the tree, and the ref update is leased on that commit. The receipt’s tree matters only when the plan may already be on the branch: on the same base, or on a moved base under `rebase = "conflicts"` with the same plan fingerprint. There, a receipt that does not cover every plan path takes the full check; a moved base otherwise, or a changed fingerprint, is a rewrite without it. A branch whose pull requests or labels the inventory could not fully read takes the full check too. See [branch ownership](https://count-patchula.sweepy.dev/internals/threat-model/#branch-ownership). Changes replace the branch commit in place; unchanged contents write nothing. `rebase = "behind"` recreates the branch when the base moves. `"conflicts"` keeps an identical plan on its old base until a touched file or proposal changes.

**Refs.** Refs are published with the GraphQL [`updateRefs` mutation](https://docs.github.com/en/graphql/reference/git#updaterefs) and a `beforeOid` lease on each branch. Unlike REST’s unconditional force update, this atomically refuses a concurrent human push. The default branch is not leased: the writer checks the base head when it reads it, and a branch left behind by a base that moves afterwards is handled by `prs.rebase` on the next run. Cleanup first proves that a branch is the Count’s, with the compare and signature checks below. Only once it has such a branch to delete does it read the repository metadata, and before each deletion it reads the default head again; once that has moved, it deletes nothing more. A failed ownership probe fails cleanup before any deletion. The ref update never names the default branch, because a no-op update of it is rejected by rulesets that require pull requests. The mutation is atomic, so a refused update moves none of its refs. GitHub answers a stale `beforeOid` with only its generic GraphQL error, so on that error (or none) the writer reads each named branch again. When at least one moved, that move explains the refusal: a branch whose new head is not provably his is protected, exactly as the full check would leave it; one still his that moved or was deleted ends stale, and so do the branches that only waited on the refused update. When none moved, or a re-read fails, or GitHub gave a specific reason (a ruleset, a permission), every branch the update named fails with GitHub’s GraphQL error messages. Writes never enter the read cache, and transport or server failures are not retried: the next run reconciles the ref.

**Races.** Every step’s outcome is one of three severities: an error, a stale, or a warning. The update layer types its races as `Error::Raced` — each names a state change observed mid-run, safe to rerun because the write stopped before mutating against the stale view or its mutations are idempotent on retry: the publish lease’s base-head and metadata reads, the write inventory, the obsolete-PR refresh and closure leases, the cleanup metadata read, the post-publish head read with its bounded replication retries, and the dashboard issue’s re-check before its write. A race leaves its branch or pull request action `stale`; the first stale action lifts to the repository’s `stale` status after errors and protections have had their say, since an error always outranks a race. A stale repository records no schedule turn, so the rerun still sees the window the raced run covered; on the server it is requeued, never retried with a backoff. Control and inventory reads use the same mapping.

**Certainty.** Closing an obsolete PR, deleting a branch and merging a PR each take a `Certain` proof, and `Evidence::certain` is the only way to get one. The write path folds the report’s scoped warnings, lookup failures and image comparisons that could not be read (an SBOM or OSV.dev failed, which makes that image’s package uncertain) into one `Evidence` after lookup and before any write; closure, cleanup and auto-merge, on both the full and the receipts path, decide on that one snapshot, so warnings the write path adds later (lockfile tools, caches) change none of them. Each decision names what it `Depends` on: `Everything`, `Extraction` (lockfile maintenance), or a set of targets (file, source, package) and files. An open PR’s targets come from its own `patchula-targets` or batch marker, so they are known when this run no longer finds the package; an unreadable marker is `Everything`. A plan depends on its targets and every file it publishes: the plan’s file actions, which hold the edited manifests, every path a lockfile run changed or removed, and, for a plan a write receipt restored, the receipt’s files. A grouped plan adds every declaration its group rule takes in this run’s extraction, and depends on the whole extraction as well: a grouped PR also waits while any file the Count reads failed to read or parse, since a missing member can’t be ruled out. Its targets set `whole_extraction`, which any `File` or `Source` warning makes uncertain. The group PR’s body carries a `patchula-grouped` marker beside its targets, so closing it as obsolete waits the same way. A batch item records whether its source PR carried that marker, and the batch PR depends on the union of its items: their targets, and `whole_extraction` when any item is grouped. Closing, branch cleanup and auto-merge all read that union, from the items marker for an open or restored batch PR and from the plan’s items for one this run builds. A group PR written before the marker existed has none and is treated as ungrouped until its body is rewritten. A target is uncertain under a `Repository` warning, a `Source` warning for its source, a `Package` warning or lookup failure for its source and package, or a `File` warning in its file’s directory or an ancestor of it; `Extraction` only under `Repository` and `File`; targets with `whole_extraction` also under any `File` or `Source` warning; `Everything` under any scope but `Run`. Both enums are matched without a wildcard, so a new scope or dependency kind does not compile until someone decides what it blocks.

**Lockfiles.** Lockfiles are regenerated with the real tools through mise, in disposable trees backed by a persistent partial clone; see [lockfiles](https://count-patchula.sweepy.dev/guide/lockfiles/). The tool must succeed before any commit, and a failure is reported for that branch without publishing manifest-only work. `--allow-lockfile-pending` permits manifest-only test branches for binary Bun locks.

**Warm writes.** Warm runs check [write receipts](https://count-patchula.sweepy.dev/internals/cache/#write-receipts) against a fresh GraphQL inventory of heads and PRs, and an exact match skips history, tree and PR reads and tool runs. A plan the lifecycle held for `prs.concurrent` has a held receipt: it settles held again while its plan is unchanged, no PR is open on its branch, nothing lets it skip the limit, and the open PRs of his on branches a plan wants already reach the limit. A full write reads only the pull requests each decision needs: the open PRs; the PRs created in the last hour when `prs.perHour` is set, the REST listing of every pull request walked newest first until a page ends older than the hour; and the closed PRs of exactly the branches a planned update could publish on, batched into GraphQL `pullRequests` reads paged per branch. A branch whose closed PRs cannot be read leaves its plan protected rather than recreating a PR its owner closed.

The open PRs, and cleanup’s branch list, come from the run’s inventory when it stands in for the REST listings: every ref decoded, every ref’s open PRs and their labels read in full (no `unsettled` ref), and a walk that covers every branch of his. A walk of every branch does. The walk narrows to `prs.branch` only after a walk of every branch found nothing of his outside the prefix — no open PR of his on another branch, and no other branch but the default whose tip is a signed commit of his with the Count’s trailer — and only while it still returns every write receipt’s branch and every closed receipt’s branch that walk saw. A narrowed walk that misses one clears that verdict, so the next run walks every branch again. An obsolete PR left on an old prefix after `prs.branch` changes therefore keeps every run walking every branch until it is closed and its branch deleted. The receipts path settles only from an inventory that stands in, by the same test. Otherwise the full write lists the open PRs (`pulls?state=open`, paged newest first) and the branches over REST. Either way, the fresh read of a PR just before its PATCH stays, so an edit made after the inventory is never written over, and so do the leases on every closure and deletion. A deletion whose lease the branch’s head no longer satisfies — someone pushed to it after the inventory read — re-reads that head and leaves the branch when it is gone or no longer provably his; one still his moved under the run, which ends stale.

PR lifecycle, labels and auto-merge are in [branches and PRs](https://count-patchula.sweepy.dev/guide/pull-requests/) and [auto-merge](https://count-patchula.sweepy.dev/guide/auto-merge/).

**Open PRs for the public record.** `Engine::run_settled_at` also returns, per repository, the Count’s open PRs as the run left them (`patchula_update::open`): a run settled from receipts gives the inventory’s PRs with the settlement’s changes (auto-merge it turned on); a write-path run gives the lifecycle’s PRs, which its listing or the inventory supplied and every write’s answer replaced, with mergeability taken from the inventory for a PR whose head no write moved; a run whose lookup didn’t complete writes nothing and gives the inventory’s, but only when the inventory stands in for the REST listings by the same test as above (`Inventory::covers`). A repository without a config reads no inventory, so the server lists and reads its PRs. PRs the run closed or merged, and PRs whose head branch it deleted, are dropped. The inventory query carries `isDraft`, `createdAt`, `updatedAt`, `mergeable` and `mergeStateStatus` for this; no write decision reads them. An inventory that doesn’t stand in, an unreadable lifecycle listing, or a step that failed leaves no view, and the server lists and reads the PRs instead.
