Skip to content

Core architecture and contribution boundaries

The current command line is built around a versioned experiment: editable project files become saved artifact versions, a review selects those versions, and a run records the trials that actually executed. This page describes the development checkout. Consult the changelog for release availability and the experiment model for terminology.

The repository also ships a retained-study/Realm implementation and older supporting modules. Shared content-identity primitives have a neutral owner. The presence of a module in the distribution, its name, or its size alone does not determine whether it can be removed.

Start from the active entry points

The installed optpilot command resolves to optpilot.cli:main in pyproject.toml. python -m optpilot reaches the same function through __main__.py. cli.build_parser() registers experiment/resource commands, starter commands, diagnostics, manifest validation, and the experiment schema printer. _retired_cli.py is not registered as this entry point.

Paths in the following table are relative to src/optpilot/.

Boundary Implementation Responsibility
Command dispatch cli.py, experiment_cli.py, resource_commands.py Parse inputs, call Core operations, format results and exit status.
First run and inspection starter.py, diagnostics.py, comparison_report.py Create the bundled starter, check local prerequisites/stores, export recorded comparisons.
Portable experiments experiment_bundle.py, _comparison_analysis.py Export and validate frozen run bundles; describe runtime observations and matched-case comparisons.
Experiment API experiment.py, _experiment_queries.py, _experiment_browse.py Admit and control runs; read detail, saved versions/files, history pages and bounded graph neighborhoods.
Authoring and review _experiment_catalog.py, _experiment_draft.py, _experiment_study.py Validate project definitions, save files and versions, derive drafts, resolve selections and schedule trials.
Execution _experiment_execution.py, _experiment_worker.py Materialize saved inputs, invoke native Python workers, validate results, checkpoint attempts and trials.
Runner integrations harbor_runner.py, _harbor_results.py, _harbor_supervisor.py, experiment_ssh.py, experiment_manual.py, external_results.py Integrate managed Harbor jobs, remote execution, operator measurements and externally recorded results.
Resource coordination experiment_resource_plan.py, experiment_resources.py Connect per-run activities with shared offers, allocations, receipts and duration records.
Persistence _experiment_store.py, _active_schemas.py, _database_migrations.py Store frozen definitions/content and run records; own active database schemas and upgrades.
Launchable interfaces _experiment_interface.py Resolve saved inputs for interface previews, trial replays and presets.
flowchart TD
    CLI[CLI and other Core callers] --> API[experiment.py]
    Files[Editable manifest and declared files] --> Review[Catalog, drafts and review]
    API --> Review
    Review --> Store[Frozen versions and reviewed selections]
    API --> Run[Admission and execution]
    Store --> Run
    Run --> Native[Native Python worker or SSH worker]
    Run --> Other[Harbor or manual work]
    Run --> Resources[Shared resource registry]
    Native --> Records[Trials, attempts and evidence]
    Other --> Records
    Import[External result import] --> Records
    Records --> Read[Graph, detail and comparison report]

Review freezes definitions and declared file content. Execution resolves its inputs from that store; editing a working file does not rewrite an earlier version. Native execution materializes those inputs in temporary directories and starts a worker using the current Python interpreter. It executes trusted project code; Python isolated mode is not an operating-system security sandbox. A source digest also does not pin every installed dependency or external service.

Keep reviewed selections distinct from observed execution. A selected candidate may never start. usedVersionIds, trial states and recorded attempts describe what happened. External imports can contain only a summary or a subset of trial receipts; a reported total is not evidence that Core executed those trials. See evidence and runner capabilities.

Schema and shared-code boundaries

The active project document is optpilot.experiment.yaml, validated against schemas/experiment.schema.json plus semantic checks in catalog/review code. schema_validation.py loads packaged schemas with importlib.resources and resolves references through a local registry. It also retains validation for the environment, method, resource and study configuration families used by other modules. JSON Schema validation and database schema migration are separate responsibilities.

Active modules currently reuse these lower-level components:

  • _content_identity.py: BlobRef, canonical_json_bytes and request_digest supply content identities and deterministic request/version identities. Hash domains, encodings and serialized identifiers are persisted contracts.
  • parameter_values.py: parameter validation and default handling are used by catalog and interface preparation as well as other authoring paths.
  • schema_validation.py and schemas/: packaged validators and definitions are shared; changing a definition can affect more than the current CLI.

realm.refs forwards the same shared objects for retained callers. Golden-vector tests preserve their previous bytes and identities. The active static import closure no longer reaches Realm; test_active_architecture.py enforces that boundary for CLI, API and explicitly registered standalone worker entry points. This static guard is not proof that arbitrary dynamic imports cannot exist or that unreached modules are safe to delete. See API compatibility.

Retained Realm and older paths

runner.py exposes a study runner backed by realm_study_runner.py and realm.local_runtime.LocalRealmRuntime. retained_study_compiler.py and retained_study_service.py implement retained package compilation/preparation; the wider realm/ tree owns its content, authority, projection and execution records. realm/ledger.py has its own migration history and SQL files in realm/migrations/. These are separate from the active experiment databases.

Older modules such as storage.py contain a directory-based LocalEvidenceStore. They are neither the active experiment ledger nor the Realm SQLite ledger. _retired_cli.py, retained Python callers and tests still provide concrete references to older surfaces. Their existence is not a promise that every historical command remains in the installed CLI, and this guide does not declare them safe to delete.

Before deprecating a path, identify its callers with import searches, command registration, packaged resources and tests. Distinguish direct callers from shared primitives, and record which persisted formats it reads. Removal needs an explicit scope, a compatibility decision and validation of affected consumers; there is no automatic Realm-to-experiment data conversion in the current CLI.

Active storage and migration recovery

Store Location Schema owner / current version
Experiment records PROJECT/.optpilot/experiments/experiments.sqlite3, or the directory supplied by --store EXPERIMENT_SCHEMA / 6
Shared resources resources.sqlite3 in the resource registry directory RESOURCE_SCHEMA / 1
SSH target definitions ssh-targets.sqlite3 in that registry directory SSH_TARGET_SCHEMA / 1

Registry directory precedence is OPTPILOT_RESOURCE_STORE, then OPTPILOT_DATA_DIR/experiment-resources, then the per-user platform location listed in operations. The three stores have independent transactions; migration does not make a multi-database snapshot.

Schema versions 3–6 add membership projections, compact trial projections and indexes for bounded history, graph and selected-trial reads. SQL triggers update these projections in the same transaction as their source records. Frozen definitions and run/trial records remain authoritative. Portable imports restore the primary records and rebuild projections through trusted schema triggers. The query guide documents pagination, payload limits, explicit truncation and the measured large-store workload.

_active_schemas.py contains ordered Python-embedded SQL migrations. _database_migrations.open_database() checks PRAGMA user_version and owned schema structure before upgrading. Versioned stores must also match the _optpilot_migrations store names and SQL checksums. Compatible unversioned v0.2 layouts are adopted conservatively: known objects must match, optional tables are supplied centrally, and unrelated extension tables are retained. A newer or incompatible schema is rejected instead of being silently repaired.

For a nonempty store that needs an upgrade, the opener acquires the SQLite writer reservation, rechecks compatibility, checks integrity/references and creates a backup beside the database. Names follow DATABASE.sqlite3.backup-vOLDVERSION-RANDOM.sqlite3. The SQLite backup API captures committed WAL content; the backup is checked, flushed and given private creation permissions. All pending schema changes, migration history and version updates then commit in one transaction. A failed migration rolls them back. Backup failure prevents the upgrade; a failed upgrade can leave a valid backup for inspection. Already-current and newly created empty stores do not create these upgrade backups.

Recovery requires care about which records belong together:

  1. Stop clients, controllers and workers using the affected stores, including old Core builds. Older releases do not know the new version checks.
  2. Preserve the original directory, including SQLite -wal/-shm sidecars and associated job files. Do not overwrite a live database with its backup.
  3. Copy the selected completed backup to a separate recovery location using the original database filename. Retain the original backup unchanged. Preserve the corresponding project files and registry records needed by that history; an experiment database backup alone is not a complete system backup.
  4. Inspect the recovered stores with a compatible Core and read-only optpilot doctor --project RECOVERED_PROJECT --json, pointing OPTPILOT_RESOURCE_STORE at the recovered registry when applicable. Doctor checks the project's default ledger location; it does not locate arbitrary --store directories. Check known run details before permitting new work.

There is no automatic downgrade command. Opening a restored legacy database normally with the current Core will upgrade it again. Do not edit user_version or migration checksums to bypass compatibility checks. Migration backups require available space and write access alongside the database and do not replace a broader backup policy.

Worker output and runtime observations

_worker_process.py drains native and SSH transport pipes continuously. It retains a 16,000-byte stderr tail, reports the omitted byte count and limits stdout to an 8 MiB result plus a bounded metadata/log envelope. Remote workers use the same capture path instead of writing unrestricted out/err files. Timeout and cancellation terminate the owned process tree; normal worker exit also closes descendants that could otherwise keep inherited pipes open. POSIX uses a process group. Windows creates the worker suspended, assigns it to a kill-on-close Job Object and resumes it only after successful assignment. Assignment failure prevents execution. This lifecycle management is not a sandbox against deliberately escaping trusted project code.

Before importing an evaluator or generator, the executing worker sends an optpilot.runtime-receipt.v1 protocol frame. Core checkpoints it as attempt.runtimeReceipt or generation.runtimeReceipt, including when later work fails or times out. The receipt has a content identity and cannot be replaced by a different receipt for the same attempt. Reconnecting to an SSH job records the remote worker's receipt, rather than the client's environment.

Receipts contain the supplied Core worker version and worker-file digest, observed Python implementation/version, platform, isolated/virtual-environment flags, and up to 256 installed distribution names/versions. The dependency inventory is marked incomplete when it reaches its bound or metadata cannot be read. It describes installed metadata, not an exact lockfile or proof of which code the evaluator imported. No environment-variable values, hostname, username, interpreter/package paths or package-source URLs are collected. Receipt readers validate nested field allowlists and the content identity before exporting it; the identity detects changes but is not a third-party signature.

Older records, imported results, manual work, Harbor execution and workers that fail before the first frame can have no observed Python receipt. Absence means unknown; it must not be replaced with the export machine's runtime information.

Make changes within an explicit owner

Keep command formatting in command modules, execution decisions in Core, resource accounting in its registry, and active SQL ownership in the migration modules. A feature reader should not create tables opportunistically. Append a new migration instead of editing published SQL, including its whitespace; the recorded checksum intentionally detects such edits.

Protect persisted identities, frozen file bytes, reviewed selections, existing attempt evidence and the distinction between a retry and a new run. A refactor should preserve observable behavior unless its PR explicitly describes and tests a contract change. Private module prefixes are not permission to discard persisted records or break existing internal callers without checking them.

Use focused tests from tests/core/ for the affected owner, then the checks in development. test_active_database_migrations.py includes original v0.2 fixtures, rollback, concurrent openers and WAL backup coverage; test_versioned_experiment.py exercises the current experiment path. Keep old fixtures independent of current schema generation so compatibility tests cannot pass merely by regenerating their input. Validate packaged resources from an installed wheel as well as a source checkout.

Refactor status and next boundaries

The active caller map and supported API policy are documented. Content identities have been extracted with compatibility forwarding and golden vectors. Complete read projections live in _experiment_queries.py; bounded application queries live in _experiment_browse.py. experiment.py retains the public forwarding surface and run-control operations. Worker output and runtime observations now have separate owners. These changes preserve full detail/export operations.

Continue in independently reviewable steps:

  1. Clarify runner boundaries. Give native, SSH, manual and Harbor adapters explicit inputs, outcomes and cancellation/resource responsibilities. Test waiting, partial results, retries and recovery before sharing implementation.
  2. Evaluate retained-path deprecation separately. Use the caller inventory and format fixtures to propose specific removals or compatibility adapters. Do not combine broad deletion with an active-ledger upgrade.
  3. Verify the distribution boundary. Check the wheel, source distribution, documented commands and cross-platform tests, then update architecture and release notes to describe the resulting implementation.