Skip to main content

Scaling

Agent Vigilo starts with one PostgreSQL database and a routing model that can grow beyond it. The default deployment stores control data and execution data in the same placement. As evaluation volume grows, execution-owned rows can move to additional PostgreSQL placements without changing coordinator or worker code.

The design principle is simple: control metadata decides where work should live; each execution database enforces whether a routed write is still valid. A follows the stored to resolve an . A process-local isolates unavailable aliases without becoming routing authority.

Case Storage keeps immutable case segments and run plans in object storage. PostgreSQL routing governs coordination and execution evidence; workers resolve case data through recorded blob references.

Routing At A Glance​

  • The system has 128 possible logical , but a run uses only those assigned to its chunks.
  • Each used run shard has one shard-placement row and, after creation, one .
  • One dispatch operation claims one cursor, selects a bounded from that run shard, and inserts one run.chunk.ready outbox event record per selected chunk.
  • run.started is inserted at most once per run in the control database; it is not inserted once per shard.
  • Many run shards can route to the same database alias. A coordinator pass can therefore report counts for several aliases while each routed operation still targets one database at a time.

The run shard itself is not leased by normal dispatch. The coordinator claims the shard's dispatch cursor while it prepares one window. Rebalance is a separate workflow that claims one persisted rebalance item for a targeted run shard before invoking the single-shard move operation.

Default Posture​

Most teams can start with one database:

DATABASE_URL=postgres://...
VIGILO_CONTROL_DATABASE_ALIAS=primary
VIGILO_DEFAULT_SHARD_DATABASE_ALIAS=primary

vigilo setup applies migrations and seeds:

alias = primary
database_url_env = DATABASE_URL
role = control_and_shard
status = active

All used run shards route to primary until another shard-capable placement is added and selected for new or moved run shards.

The development Compose topologies provide single-node Ceph Object Gateway storage for case segments, indexes, and manifests. Object references record their storage owner independently of database shard routing. See the local stack guide for endpoints and development credentials.

Control And Execution Databases​

Agent Vigilo separates database responsibility from database location.

  • The control database owns evaluator registry rows, global run metadata, placement catalog rows, recoverable , dataset catalogs, dispatch cursors, coordinator leases, and global run lifecycle updates.
  • An execution database owns high-volume run work: chunks, , executions, attempts, aggregates, evaluator results, , and chunk-ready outbox event records.
  • name PostgreSQL targets such as primary or shard_001.
  • Shard placements map one run_id + run_shard pair to a database placement.

There is one active control-capable placement. Additional placements can have role shard and store execution data. Environment variables hold connection secrets; the placement catalog in PostgreSQL is the routing authority.

Placement status and role are checked in the control database when routes and placement pools are resolved. A provisioning placement is registered but cannot receive or serve ownership until activation verifies its target. An active placement accepts new shard ownership. A draining placement rejects new ownership but remains serviceable for shards it already owns, including dispatch, workers, recovery, reads, outbox publication, and movement away from the placement. A disabled placement is not serviceable.

Connection secrets remain process configuration. A newly added alias is discovered and cached on first use when its referenced environment variable was already provisioned in the process. Changing database_url_env, changing its URL value, or rotating credentials still requires a process restart; control metadata does not distribute or reload secrets.

Placement pool configuration resolves the requested alias lazily. An unset secret for one placement therefore fails that placement without preventing a healthy alias from initializing. Coordinator and worker runtime operations also pass through a process-local per-alias circuit breaker. Open circuits defer durable work or delay worker messages for the unavailable alias while other aliases continue. Breaker state is neither shared between processes nor persisted, and explicit administrative commands bypass it.

Logical Shards​

The system uses 128 stable logical shards:

run_shard = 0..127

Run chunks receive a run_shard during run creation. Execution-owned rows keep that same key:

run_chunks(run_id, run_shard, id)
executions(run_id, run_shard, id)
execution_attempts(run_id, run_shard, id)
execution_aggregates(run_id, run_shard, execution_id)
evaluator_results(run_id, run_shard, id)
evaluator_diagnostics(run_id, run_shard, id)
run_snapshots(run_id, run_shard)
run_shard_summaries(run_id, run_shard)

High-volume execution tables are list partitioned by run_shard. The key is stable for the lifetime of a chunk and its child rows. Adding database capacity does not recalculate run_shard; it changes stored placement rows.

Within a run shard, the executions(run_id, run_shard, chunk_id) index supports chunk receipt totals and cleanup of unfinished attempts. These lookups include terminal executions, so the index covers every execution status.

Routing Lifecycle​

Run creation publishes a verified immutable plan before admitting execution:

  • The control database stores a creating run, dataset/plan references, exact file ownership, and at most 128 shard summaries of planned work.
  • The assignment policy freezes initial execution placements in the plan.
  • Bounded metadata pages seed execution-local chunks and compact snapshots. They contain storage references, settlement hashes, gate policy and expected gate counts. Cases and per-case membership remain in object storage.
  • Local commits precede contiguous control acknowledgements. Retries verify immutable identity and replay safely after lost acknowledgements.
  • Admission independently verifies exact local chunk coverage. One fenced transaction publishes shard routes and dispatch cursors and sets pending.
  • Coordinators resume only ready plans with execution requested. Prepared-only runs stay held. Cancellation closes partial local admission before a stale creator can restore work. See Run Preparation.
  • The default policy is explicit and conservative: VIGILO_SHARD_ASSIGNMENT_POLICY=single-default assigns all new run shards to VIGILO_DEFAULT_SHARD_DATABASE_ALIAS.
  • VIGILO_SHARD_ASSIGNMENT_POLICY=spread-active spreads one run's used shards across active shard-capable placements.

Coordinator dispatch is route-constrained:

  • The control database claims one open run_id + run_shard dispatch cursor with FOR UPDATE SKIP LOCKED and retains that transaction through the routed write. Running dispatches share the run lifecycle lock; the initial pending-to-running transition is exclusive.
  • The scoped snapshot statement reads the shard and database placement records. The router validates their purpose, lifecycle and matching alias, then routes the write without another control-database lookup.
  • The execution database upserts run_snapshots, marks pending chunks dispatched, and inserts run.chunk.ready outbox event records.
  • On a colocated placement, the chunk writes and cursor update commit together on one connection. On a separate execution placement, the execution transaction commits before control releases the cursor or marks it drained.
  • If an execution placement operation fails, the cursor remains open and that database alias is excluded from the rest of the current dispatch pass. Healthy aliases continue within the same cycle.

Workers stay chunk-local:

  • Each in a worker message carries run_id, run_shard, chunk_id, database_alias, and a .
  • The worker resolves the hinted database pool locally and validates the execution database's in the chunk-claim transaction. A valid hint requires no control-database route read. Rejected hints invalidate the route cache and perform one authoritative refresh.
  • After claiming, the worker loads the local run snapshot, retrieves and verifies assigned case segments from object storage, persists attempts/results/aggregates, and commits a terminal chunk receipt in that execution placement.
  • Evaluator registry metadata remains a control-database read.
  • Database operations have bounded client and PostgreSQL deadlines. An availability failure or lock conflict delays only the affected message and does not consume its worker-failure retry budget. A claimed message waits past its lease before redelivery; claim and attempt tokens fence stale work.
  • Agent calls, evaluator execution, and broker settlement stay outside the database deadline. Broker failure remains process-visible so work is never acknowledged without a durable retry or completed database state.

Finalization fans in:

  • Each execution placement maintains run_shard_summaries.
  • Settlement keeps query plans specific to the current shard, including PostgreSQL's internal foreign-key checks, so unrelated partitions do not consume shared relation-lock capacity. This transaction-local policy resets on commit or rollback and adds no database query. It trades additional planning work for bounded shard-local locking; no server-wide planning setting is required.
  • Coordinators consume bounded immutable receipt pages, publish provisional progress, and seal summaries only after a canonical fold validates exact planned membership. Every configured gate retains its planned denominator, including eligible cases without executions. See settlement and partial results.
  • Aggregation selects shards with indexed pending receipts or a canonical fold ready to advance. Idle shards do not open aggregation transactions. Successful checkpoints rotate productive shards; busy or invalid candidates also rotate to keep the bounded ready-work pass fair. Shards with remaining ready work are revisited in fair rounds within each database's page and scheduling-time budgets. A progress page uses one extra pending identity in its existing query to avoid revisiting a shard that has consumed all currently available receipts and still awaits other chunks. Independent shard pages and execution database passes run with bounded concurrency; each page retains its own ownership claim, movement fence, and atomic checkpoint. Pages are limited by both receipt count and serialized bytes, so large gate payloads can fill a page before its row limit. See the aggregation controls for defaults and the distinction between scheduling budgets and database deadlines.
  • Aggregation budgets are separate from finalization candidate limits. Concurrent work is bounded per coordinator, so adding coordinators also increases potential database demand. Readiness discovery can still inspect idle unsealed summaries; a bounded candidate result does not guarantee constant discovery work. Capacity depends on database headroom and sustained receipt arrival and drainage rates.
  • The coordinator inspects a bounded number of candidates per cycle and reads routed summaries for each run in one batch per execution database. Finalization inspects published progress and seals; receipt aggregation advances only in its dedicated cycle stage. A blocked candidate is moved behind unchecked candidates, allowing a later ready run to finalize in the same cycle. --max-finalize-per-cycle / VIGILO_COORDINATOR_MAX_FINALIZE_PER_CYCLE bounds candidate inspections, not guaranteed successful finalizations; the default is 64.
  • The control database claims the run without waiting behind active dispatch lifecycle locks. The final write rechecks expiry after locking the run row. A coordinator whose lease expired while waiting leaves the outcome for a later claim.
  • The coordinator verifies every shard scorecard has the same policy hash and gate set, merges exact counters, evaluates run gates, and atomically stores run_scorecards, runs.gate_status, and the completion event.
  • A failed placement read defers that run without discarding summaries already read from healthy placements. The run cannot finalize until every routed summary is available, sealed, and valid.

Cancellation fans out:

  • The control database marks the run cancelled and marks its dispatch cursors drained first.
  • The workflow resolves the run's execution placements and cancels local chunks, executions, and attempts in each placement with bounded fanout. Each group holds shared movement admission, validates local settlement authority, and commits chunk receipts in the cancellation transaction; coordinator pages publish the summaries.
  • run.cancelled remains a control-database outbox event record.

Status, watch, results, and export reads fan in lightweight summaries:

  • The control run row remains the authoritative lifecycle record.
  • While a run is creating, reads report placement counts, attempts, and the latest creation error from the control database without contacting unseeded execution databases.
  • Live progress is read from routed run_shard_summaries when available, in one batch per execution database. Shards on the same database share that read; route validation and missing-shard checks still apply to each shard.
  • Results and export merge summaries in shard order, keeping floating-point scores independent of the grouping of shards into database batches.
  • Payloads include data.live_progress and progress-source metadata so callers can distinguish control-only state from execution-shard progress.

Outbox records are local to the database where the state changed. Control event records publish from the control database. Execution event records publish from the execution database that owns the changed rows. Lease recovery and outbox publication iterate placements independently; a failed alias is logged and skipped while healthy aliases finish the pass.

Within a placement, expired chunk recovery reads up to 32 extra candidates per retry class so it can skip contended shards and chunks within the window. The configured recovery batch still limits writes in each class. Standalone deferred discovery checks local ownership before limiting due work, so retained rows on closed placements do not use polling slots.

Control Database Scale​

The control database is singular and authoritative. Its CPU, memory, storage, and connection limits bound control-plane capacity; execution rows spread across shard-capable placements. Coordinator hot paths emit structured log fields that can be treated as metrics: dispatch cursor backlog, finalization candidate backlog, per-placement outbox backlog, oldest finalization candidate lag, route resolution timing, pool acquisition timing, and stage timings for recovery, dispatch, finalization, and outbox publication. Each completed cycle also reports unique skipped placements, failed placement operations, and retryable versus terminal placement errors. Contained failure logs include the database alias, operation, error kind, and retryability.

The hot outbox publisher scan is indexed by availability time. Evaluator registry reads use the control database; immutable case payloads and run configuration are read from object storage. Connection settings are fixed for each process lifetime.

Operating Placements​

Add a shard-capable placement by migrating its target, deploying the secret env var to every Vigilo process, registering it, and then activating it:

export VIGILO_SHARD_001_DATABASE_URL=postgres://...
DATABASE_URL="$VIGILO_SHARD_001_DATABASE_URL" vigilo setup --skip-evaluators
vigilo database register shard_001 --database-url-env VIGILO_SHARD_001_DATABASE_URL
vigilo database activate shard_001

Registration creates a non-routable provisioning catalog row. Activation is bounded by --database-operation-timeout-seconds (default 30) and verifies that the target is reachable, writable, empty of local shard ownership, on the same successful migration set as the control database, and physically distinct from every active or draining placement. A failed check leaves the placement in provisioning; fix the target and retry the idempotent activation command. Activation validates the secret available to that command process, so deploy the same environment variable to coordinators and workers before activating.

Library operator calls​

vigilo::operations::placement::PlacementClient shares the standalone operator Client control pool. Supply a map of operator-owned PostgreSQL URLs keyed by the catalog's connection reference names. The control client supplies the DATABASE_URL binding. Deploy matching references to the runtimes that will serve the placement. The library uses its explicit map for shard references.

list_database_placements reads one control page ordered by alias, with a limit of 100 rows and an exclusive continuation alias. list_run_shards reads one run's routes in logical shard order, with up to 128 rows and the current route version and write epoch. Both calls use a single data query on control.

register_database_placement creates a provisioning shard. The same alias and reference return the current row on retry. A conflicting registration fails. For activation, first provision the target with verified setup. Pass the expected PostgreSQL cluster, database, and schema to activate_database_placement. The operator logins need access to pg_catalog.pg_control_system() for physical duplicate checks. Activation checks up to 128 active or draining peers within a 30-second deadline. A retry after activation reports the active row and whether this invocation ran a readiness probe.

Set the default for future run shards:

VIGILO_DEFAULT_SHARD_DATABASE_ALIAS=shard_001

Choose how new run shards are assigned:

VIGILO_SHARD_ASSIGNMENT_POLICY=single-default
VIGILO_SHARD_ASSIGNMENT_POLICY=spread-active

single-default is the local/small-deployment default. spread-active deterministically assigns used logical shards across active shard-capable placements and stores each assignment in shard_placements.

Placement lifecycle​

Database-placement status controls whether a physical PostgreSQL target can receive or serve shard ownership. It does not move any shard rows itself.

Database statusNew run shardAssignment or move targetExisting owned shard
provisioningRejectedRejectedBlocked
activeAllowedAllowedServed
drainingRejectedRejectedServed
disabledRejectedRejectedBlocked

Activation performs target and peer I/O before opening the control transaction. The final transition serializes activation commits in the control catalog and rechecks the registration, the verified peer set, and the absence of ownership references. Competing attempts with the same registration can observe the winning active row. A change to the peer set requires a fresh verification.

New-ownership writes take a shared row lock on the target placement through route commit. Drain and disable take an exclusive row lock on the same catalog row. This serializes a concurrent route assignment with the lifecycle change: the assignment commits before drain, or it observes draining and fails.

To evacuate a shard-only placement:

# First deploy an active default/target alias to every relevant process.
vigilo database drain shard_001
vigilo rebalance plan --from shard_001 --to shard_002 --max-items 100
vigilo rebalance apply <operation_id> --max-items 25
vigilo rebalance verify <operation_id> --max-items 25
vigilo database disable shard_001

database drain is idempotent and refuses the control-capable placement. After it succeeds, existing routes continue normally while rebalance evacuates them. database disable requires the placement to be draining and have zero owned shard routes, zero creating-run references, zero unfinished rebalance items, and zero pending outbox deliveries. It is also idempotent. Keep the placement database and its URL environment variable available until disable succeeds.

Inspect routing metadata:

vigilo database list
vigilo run shard list <run_id>
vigilo run shard show <run_id> <run_shard>

vigilo run shard show reports the database alias, placement statuses, move_target_database_alias, route_version, database_url_env, env-var availability, and whether the route is dispatchable, read_only, or blocked. An active move also reports its operation ID, phase, completed page count, and copied row and byte counts. It never prints the database URL.

Case Storage And Shard Assignment​

Control storage owns finalized dataset and run-plan references, creation progress, routing, and settlement metadata. Immutable case segments and ordered membership live in object storage. Execution databases retain owned chunks, run metadata, attempts, results, and settlement evidence.

Creation acknowledges only verified uploaded pages and activates a run only after its finalized manifest and placement coverage are complete. An ambiguous response replays the same immutable page under its recorded upload identity. Workers fetch bounded assigned batches and validate bytes, identity, and membership before execution. Moving a database shard changes execution ownership; it does not copy or rewrite the dataset's blobs. See Case Storage for publication, resource bounds, and cleanup ownership.

Moving A Run Shard​

Use shard move for a specific run_id + run_shard:

vigilo run shard move <run_id> <run_shard> --to <alias> --dry-run
vigilo run shard move <run_id> <run_shard> --to <alias>
vigilo run shard move <run_id> <run_shard> --to <alias> --verify-only

Routes are immutable while their run is creating; move and direct placement changes are rejected until creation reaches pending or failed. Rebalance plans omit creating runs for the same reason.

The move briefly fences the source to enable source-local dirty-key capture, then changes the route from active to copying. It installs the current move ID, monotonic claim generation, and opaque claim token on the prepared target before resetting or copying data. copying remains dispatchable while the target is copied in durable row-and-byte-bounded pages.

Worker claims, dispatch writes, and routed cancellation cleanup take the shared form of the and validate the local admission state and write_epoch in their execution-database transaction. The lock is cooperative: every protected writer must explicitly acquire it. PostgreSQL does not infer which rows belong to the shard.

is the control-plane CAS token for lifecycle changes. write_epoch is the data-plane ownership token carried by work. Movement keeps the epoch stable through copying and draining, closes the source at the next epoch before activating the target, then opens the target at that epoch. A crash can therefore leave a retryable no-writer gap, but never two admitted writers. The move claim generation is the target-writer fencing token. Every target reset, copy, replay, or delete transaction holds shard admission and validates the exact move ID, generation, and token before mutation. Installing a newer generation takes exclusive target admission, waits for in-flight writes, and prevents an expired coordinator from reinstalling or writing with older authority. The source transaction that changes a shard row also upserts its key into the move journal. Replay rereads current source state: existing rows are upserted in dependency order and missing rows are deleted in reverse dependency order. A version-guarded journal delete leaves a key pending when it changes during replay.

One compact page-count/cursor checkpoint per moved table lives in control storage. Capture state and dirty keys live on the source; mover authority lives on the prepared target admission. Because the fenced target page commits before its checkpoint, a lost acknowledgement replays at most one idempotent page without growing control metadata per page. A rejected target write cannot advance its control checkpoint. After backfill, a bounded catch-up cycle keeps the route in dispatchable copying when too many dirty keys remain. After the backlog is bounded, draining stops new work while admitted work settles. The exclusive source fence is held only for final replay, an empty-journal check, and route activation.

After claim admission commits, an opaque chunk claim token and renewable deadline carry worker authority. Attempt allocation and result persistence lock and validate that live token; result persistence also requires the current live worker attempt. Recovery clears an expired chunk token and retires the running attempt. This can happen during drain. Requeued chunks can be claimed after admission opens, and exhausted chunks receive a terminal receipt. Terminal worker settlement and cancellation also write receipts in the transaction that clears active work. Aggregation checkpoints, receipt-consumption identities, and sealed summaries move with their shard under the same ownership fence.

When active work exists, the route stays draining; re-run the move after that work finishes. When an online catch-up cycle reaches its work bound with too many dirty keys remaining, the route stays copying; re-run the move to continue. Interrupted copying, draining, or moving work resumes only with its persisted target. Target reset occurs once, completed pages resume from their last key, and dirty replay stays version guarded. Repeating a move after fenced activation returns a verified no-op. --force cannot bypass the active-work or write-admission fence.

Bounded library moves​

Call PlacementClient::move_run_shard with the run and shard, the active source's route version from list_run_shards, the target alias, and a caller-generated operation UUID. Keep those fields for retries. Each call accepts a budget of 1–64 nonempty batches across target reset, source backfill, journal replay, and destination control repair. A batch handles up to 1,000 rows or keys. Copy and replay pages aim for 4 MiB of row data and can carry a single larger row so the cursor advances. The two move endpoints use the operator's explicit bindings and shared placement pools.

Use the returned progress to resume with the same UUID. The caller may choose a different budget on retry. A stale initial route or a different request using the same UUID conflicts. If a call is interrupted, its claim can remain leased for up to five minutes. A call has a 30-second deadline. A completed UUID returns a read-only receipt even after a subsequent move.

Online backfill seeks the next native primary-key page. The source journal indexes the captured action for each key so replay can page updates and deletes in dependency order. Library moves defer journal deletes to the exclusive source fence, where the target can apply them in child-first order. A budget stop during final replay leaves the route moving. After the control route activates, the target admission stays prepared until the move finishes any bounded repair of its copied run-control revision. Calls resume that repair from its committed cursor before opening the target at the new write epoch.

Dry-run and verify-only output uses full_fingerprint verification with source/target counts and checksums. Executed moves use checkpoint_and_replay: they report checkpoint copy counts and leave full-fingerprint fields empty so route activation does not add table scans to the exclusive freeze.

Every route alias or status change increments shard_placements.route_version. Ownership transfer or restoration also increments shard_placements.write_epoch. Route caches are invalidated on local admission rejection; correctness does not depend on cache freshness because the execution database rejects stale epochs locally.

Moved shard-owned tables:

run_chunks
run_snapshots
executions
execution_attempts
execution_aggregates
evaluator_results
evaluator_diagnostics
run_chunk_settlements
run_chunk_settlement_consumptions
run_shard_summaries

The move also copies the compact run and dataset identity prerequisites required by the target placement. Case payloads and complete dataset membership remain in object storage; the target uses the same immutable references.

run_shard_dispatch_cursors stays in the control database and is never copied between execution placements. Source cleanup is intentionally outside the move command so teams can apply their own backup and retention policy.

Bulk Rebalance​

Use rebalance operations when adding capacity or draining a placement:

vigilo rebalance plan --to shard_001 --max-items 100
vigilo rebalance plan --from primary --to shard_001 --max-items 100
vigilo rebalance apply <operation_id> --max-items 25 --lease-seconds 300
vigilo rebalance verify <operation_id> --max-items 25
vigilo rebalance cancel <operation_id>

A rebalance plan records one item per targeted run_id + run_shard in the control database. CLI apply is resumable and caps the number of items per invocation. The rebalance apply process atomically claims one item immediately before processing it, completes that item's single-shard move, and then selects another item. Multiple apply processes can work on the same plan because their item claims do not overlap. Only pending items or running items with expired leases are eligible. Completion, failure, claimed cancellation, and active-work deferral require the claim's opaque fencing token. A shard with active work returns its item to pending while its route remains draining; a later apply resumes it at the expected next route version. Each item still uses the single-shard move workflow, including route fencing, target reconciliation, bounded copy verification, and active-work guards. Plans verify the stored route_version before moving an item so stale plans fail narrowly instead of rewriting an unexpected route. An expired apply claim can resume its exact source route when it is draining at the next route version or moving two route versions later, provided its persisted target still matches the plan. Claim duration defaults to 300 seconds and can be changed with --lease-seconds or VIGILO_REBALANCE_LEASE_SECONDS. Drain-source planning includes shards owned by an active or draining source. Every target is revalidated as active when the route is activated, so a target that begins draining during a copy cannot receive the shard.

Bounded library rebalancing​

Call PlacementClient::plan_shard_rebalance with a caller-generated UUID, the target alias, and a total item limit of 1–256. Supply a source alias to drain that placement. Omit it to fill the target using observed active placement counts. Retry with the same request until the plan seals. Each call scans at most one page of 128 placements and one page of 256 route entries. The route cursor advances even when the page contains only creating runs. Selected items and the next cursor commit together on control.

Fill-target planning observes committed metadata across calls. It fills toward the observed rounded-up average and selects at most each donor's observed excess. Every item retains its source and route version for apply-time validation. Planning leaves execution placement connections idle.

Pass the sealed plan ID to apply_shard_rebalance with an item-claim limit and a shared move batch budget, both from 1 through 64. Each claim persists the same single-shard move ID across budget stops and lease recovery. The returned sequence can advance to later items when an earlier shard is still draining. Resume from the beginning to revisit deferred items after reaching the end. Stale routes fail individually, and terminal plans return their durable totals. Each call has a 30-second deadline. An interrupted apply can retain its item claim for up to six minutes while the move's own claim expires.

The CLI can apply a library plan with the same bounded mover and configured placement credentials. CLI-created plans use the CLI apply workflow. Cancelling a plan can leave an unfinished single-shard move. Use the move ID from apply to resume it independently, or abort the move through the CLI.