Skip to content

crates storage

bondiano edited this page Nov 12, 2026 · 1 revision

Durable storage

Active contributors: Vassiliy, bondiano

Purpose

sych-storage keeps mutable lifecycle state and pointers in SQLite or PostgreSQL, while immutable versioned documents live in a local content-addressed artifact directory. It implements the model cost ledger and the server’s durable jobs, publication outbox, finding history and API read models. The public facade is crates/sych-storage/src/lib.rs; runtime orchestration belongs to Server and CLI.

Storage boundary

Abstraction Role Source
StoreConfig, Database Select database backend and artifact root crates/sych-storage/src/lib.rs
Storage Shared business operations over a one-connection SQLx Any pool crates/sych-storage/src/connection.rs
Partition Tenant plus access scope for run/artifact identity crates/sych-storage/src/lib.rs
RunHandle Run ID, partition, generation and optional server fence crates/sych-storage/src/lib.rs
Fence, Claim Worker job ownership, lease epoch and claimed inputs crates/sych-storage/src/jobs.rs
ArtifactStore Immutable bytes, partitioned keys and verified reads crates/sych-storage/src/artifacts.rs
RunLedger Cost ledger plus accepted-answer checkpoint writes for one run crates/sych-storage/src/checkpoints.rs
Visibility Tenant and readable repository set for dashboard queries crates/sych-storage/src/views.rs

The database stores identities, state, counters, history and document pointers rather than decomposing the entire ReviewResult into relational objects. See migrations/sqlite/0001_runs_and_artifacts.sql and Data models.

Explicit migrations and writer transactions

Storage::migrate in crates/sych-storage/src/connection.rs is the schema-changing entry point. Storage::open refuses missing migrations and unknown newer versions; it never creates a missing SQLite database or migrates on open. The application exposes migration through sych db migrate.

The embedded migration histories are separate:

  • migrations/sqlite/: 17 migrations, from migrations/sqlite/0001_runs_and_artifacts.sql through migrations/sqlite/0017_run_modes.sql.
  • migrations/postgres/: 8 migrations, from migrations/postgres/0001_storage.sql through migrations/postgres/0008_run_modes.sql.

Both current schemas contain 25 application tables, enumerated by TABLES in crates/sych-storage/src/import/schema.rs. Do not infer the current table count from an older guide or the first migration.

All business writes use the shared Storage::write transaction in crates/sych-storage/src/connection.rs:

Backend Connection settings Writer coordination
SQLite WAL, synchronous=FULL, foreign keys on, 30-second busy timeout BEGIN IMMEDIATE obtains the writer reservation before business reads
PostgreSQL One-connection pool BEGIN ISOLATION LEVEL READ COMMITTED, local 30-second lock timeout, then pg_advisory_xact_lock(1937335144)

PostgreSQL acquires its lock in a separate statement so later business reads have a fresh READ COMMITTED snapshot after any wait. The lock serializes cooperating writers across independent pools/processes, not only within one Storage instance. PostgreSQL support preserves one-writer semantics; it is not a multi-writer scaling design. External Git, tool, model and SCM work is outside these short database transactions (docs/STORAGE.md).

Database formatting and connection-error handling avoid displaying PostgreSQL credentials (crates/sych-storage/src/lib.rs, crates/sych-storage/src/connection.rs).

Artifact writes, reads and partition checks

put_artifact in crates/sych-storage/src/lib.rs follows this order:

  1. Serialize canonical JSON and hash the bytes.
  2. Upsert artifact metadata, extend retention to the later deadline and pin the digest under the run’s role. A server pin must satisfy its current fence.
  3. Commit metadata, then write the artifact bytes.

The row precedes the bytes deliberately: a crash may leave visible metadata with unavailable bytes, rather than untracked application state. Finalization separately requires the saved result bytes to be readable and hash-correct.

ArtifactStore::key in crates/sych-storage/src/artifacts.rs produces <partition-prefix>/<digest-prefix>/<digest>. The partition prefix is the first 32 hex characters of SHA-256 over tenant_id, a NUL separator and access_scope; the digest prefix is the first two hex characters of the content hash. Identical bytes share an address within the partition, not an authorization grant across tenants or scopes.

ArtifactStore::put compares an existing file with the supplied bytes. New bytes go through a unique temporary file, file sync, rename and directory sync. get verifies SHA-256 every time; a missing file is ArtifactUnavailable, and a mismatching file is Corrupt. read_document then uses core’s version-aware decode, never regeneration (crates/sych-storage/src/lib.rs).

Reads join pointers using tenant, scope and digest; saved-run entry points select the run by tenant. Successor checkpoint loading additionally requires the exact Partition (crates/sych-storage/src/checkpoints.rs). Dashboard lists use Visibility and shared predicates in crates/sych-storage/src/sql.rs.

Storage is not the HTTP authorization layer: internal methods that accept a change/finding/job ID rely on callers to have authorized that object. For example, administration delivery reads require the caller’s allowed connection IDs (crates/sych-storage/src/admin.rs). Follow Security and the server handlers when adding a public endpoint.

Run lifecycle and authoritative completion

Local begin_run increments the change generation and inserts RUNNING / PLAN in one transaction. complete_run requires a result for that run, its review_result pin, readable hash-verified result bytes and an active run; it commits the pointer, usage, coverage, UNKNOWN count and COMPLETED together. fail_run and cancel_run can end a running local run but cannot turn a terminal run into a completed one (crates/sych-storage/src/lib.rs).

Server runs add durable scheduling and fencing:

graph LR
    Intent["Admitted intent"] --> Generate["Generation + QUEUED run/job"]
    Generate --> Claim["Claim + lease epoch"]
    Claim --> Prepare["Prepare source/policy, EVIDENCE"]
    Prepare --> Wait["WAITING_EVIDENCE if needed"]
    Prepare --> Freeze["Freeze inputs: ANALYZE"]
    Wait --> Freeze
    Freeze --> Bytes["Store result bytes"]
    Bytes --> Commit["Atomic completion + DONE + outbox"]
    Commit --> Publish["Separate publisher/reconciler"]
Loading

crates/sych-storage/src/scheduler.rs creates the next review generation, supersedes older active work and revokes its job lease in one transaction. crates/sych-storage/src/jobs.rs claims due work with a new epoch, heartbeats/reaps leases, records prepared source/policy and freezes inputs. New external inputs after freezing require a successor, not mutation of the frozen analysis.

For a fenced server run, complete_run and the fenced! predicate require:

  • RUNNING with frozen inputs at stage = ANALYZE;
  • the same claimed job, owner and epoch, with an unexpired lease;
  • the current desired review generation;
  • the stored result artifact for that run and matching durable bytes.

The same transaction finishes the job and creates configured summary/check publication intent. A stale worker cannot pin artifacts or commit its result. A crash after completion leaves a finished job and durable outbox work, not a second analysis (crates/sych-storage/src/lib.rs, crates/sych-storage/src/sql.rs, crates/sych-storage/tests/finalize.rs).

PLAYGROUND runs are an explicit exception to review-generation currency: they share a generation without superseding reviews, publish nothing and are born with lineage already applied. Review-only read models and analytics exclude them. See crates/sych-storage/src/scheduler.rs, crates/sych-storage/src/outbox.rs and migrations/postgres/0008_run_modes.sql.

Cost reservation, settlement and unknown charge

Storage implements core’s Ledger; budget policy remains in crates/sych-core/src/model/budget.rs, while durable accounting is in crates/sych-storage/src/ledger.rs. Money is integer micro-USD.

Before dispatch, reserve_attempt/reserve_scoped calculate committed usage and run core admission under the writer transaction, then insert RESERVED. Run limits are separated by purpose and optional session scope; tenant day/week/month pools remain shared. Released attempts still count toward the lifetime attempt limit. Weekly accounting starts Monday UTC and can span a month boundary. A configured provider subscription fee is allocated once per tenant/provider/month.

Stored state Accounting meaning
RESERVED Hold bounded money/tokens before a request
RELEASED Request did not leave Sych; release the financial hold
UNKNOWN Request may have been dispatched without known charge; retain the reservation
SETTLED Record observed usage, charge/reference amount and provider/model identifiers

UNKNOWN_CHARGE is the core accounting condition; the SQL state is UNKNOWN. Settlement is idempotent, and a later known charge may reconcile UNKNOWN to SETTLED. Missing usage stays nullable, not fabricated as zero. hold_unsettled moves a cancelled run’s leftover reservations to UNKNOWN because dropped requests may already have been sent (crates/sych-storage/src/ledger.rs, migrations/sqlite/0002_model_ledger.sql).

A provider charge above its reservation is recorded truthfully and flagged as a billing mismatch. Subscription-quota mismatch blocks further matching provider/month admission; the store does not hide an overcharge to preserve an apparent cap. Analytics return known cost and unknown-attempt counts separately (crates/sych-storage/src/ledger.rs, crates/sych-storage/src/spend.rs, crates/sych-storage/src/totals.rs). See Models.

Checkpoints, sessions, lineage and read-model map

All the implementation modules below are private behind Storage methods and selected root re-exports in crates/sych-storage/src/lib.rs.

Capability Source files Stored behavior
Admission crates/sych-storage/src/admission.rs Webhook receipt, repository binding and debounced intent commit together; duplicate deliveries are recognized
Scheduling and jobs crates/sych-storage/src/scheduler.rs, crates/sych-storage/src/jobs.rs Change state/generations/events, successor links, jobs, leases, retries and fences
Accepted-answer reuse crates/sych-storage/src/checkpoints.rs checkpoint/<key> artifacts under the run fence; partition-bound reads; one retry for a storage failure, permanent loss on fence conflict
Publication crates/sych-storage/src/outbox.rs, crates/sych-storage/src/publish.rs, crates/sych-storage/src/recreate.rs Summary/inline/check intents, leased sends, delivery/reconciliation and audited recreation
Finding lifecycle crates/sych-storage/src/lineage.rs Apply one run’s lineage once, append history, record feedback and scoped waivers; completed reviews pending lineage can be recovered
HTTP support crates/sych-storage/src/api.rs Tenant/actor/endpoint-scoped idempotency, run/publication views, cancellation and metrics counters
Sign-in sessions crates/sych-storage/src/sessions.rs Token SHA-256, actor/kind/grants and expiry; start/end audited in the mutation transaction; expired sessions are not returned
Tours and follow-ups crates/sych-storage/src/tour_sessions.rs tour:<id> pins, latest tour, actor-private progress and exchanges; neither progress nor a question rewrites the tour/result
Dashboard lists crates/sych-storage/src/views.rs, crates/sych-storage/src/queue.rs Repository-scoped changes/findings, cursor pages, attempts, waivers, jobs and unresolved publications
Overview/quality analytics crates/sych-storage/src/totals.rs, crates/sych-storage/src/analytics.rs Counts, usage, latest feedback judgement, settled finding states and coverage/UNKNOWN reason counts
Cost/latency analytics crates/sych-storage/src/spend.rs Cost by repository/model/purpose, held budget spend and latency distributions
Administration and audit crates/sych-storage/src/admin.rs, crates/sych-storage/src/audit.rs Connection deliveries/SCM failures and append-only action audit
Rule suggestions crates/sych-storage/src/suggestions.rs Latest rule-finding judgements and audited maintainer decisions
Notification digest crates/sych-storage/src/digest.rs Claim one tenant/week/channel slot before sending; failed sends have bounded retries, unknown SENDING outcomes are not blindly resent
Saved-result lookup crates/sych-storage/src/results.rs Resolve a result ID to its tenant’s saved run

RunLedger remembers a lost checkpoint fence and refuses later reservations through that instance. Checkpoint dependencies and actual reuse decisions belong to the core model layer, not a hash-only cache hit (crates/sych-storage/src/checkpoints.rs, crates/sych-core/src/model/checkpoint.rs).

Publication is separate from completion. begin_publishing durably records the body/request digest/attempt before the network write; lost replies or expired in-flight work become UNCERTAIN, not automatic PENDING. Only reconciliation or an audited recreation decision resolves that ambiguity (crates/sych-storage/src/publish.rs, crates/sych-storage/src/recreate.rs). The full protocol is in Server.

Analytics reason counts are copied into run_reasons in the result-completion transaction, so they outlive result-artifact pruning. Counts reflect recorded judgement/coverage, not an invented review-quality score (crates/sych-storage/src/analytics.rs).

Retention and garbage collection

Artifact retention is defined by ArtifactKind in crates/sych-storage/src/lib.rs; eligibility and deletion are in crates/sych-storage/src/gc.rs.

Artifact condition Rule
Source snapshot or diff manifest of completed work 7-day retention
Other normalized artifacts, including results, evidence, checkpoints and tours 30-day retention
Active run or PENDING/PUBLISHING/UNCERTAIN publication Pinned against artifact GC
No completed or active run reference Orphan eligible after a one-hour grace period

Shared artifacts retain the later deadline. prune(now, true) lists candidates; actual deletion rechecks pins and retention under the writer lock before unlinking bytes and committing the row deletion. A pin/extension accepted after the initial listing keeps the artifact. Missing content is reported, never rebuilt.

Row retention is a different operation, prune_records in crates/sych-storage/src/retention.rs:

  • Consumed intents, unneeded inbox receipts and terminal jobs: 30 days.
  • Change events and settled/released model attempts: configured retention; defaults are documented in Configuration.
  • Final publication operations: 90 days.
  • Sign-in sessions: after expiry.
  • RESERVED/UNKNOWN charges and unresolved publication operations: never removed merely by age.
  • Run rows and audit events: kept.

Unresolved charges protect their accounting rows; they are not an extra artifact pin in the GC predicate. Artifact pins come from active work and unresolved publication. active_repositories also supplies the mirror-pruner’s keep set, but mirror-file deletion is application work, not ArtifactStore GC (crates/sych-storage/src/retention.rs, docs/STORAGE.md).

Importing stopped SQLite history into empty PostgreSQL

Storage::import_sqlite is an offline cutover operation, not live replication and not an automatic consequence of changing a URL. Follow docs/STORAGE.md:

  1. Stop every writer and artifact GC for the whole snapshot/import/cutover interval.
  2. Take a consistent SQLite backup and copy its matching artifact directory. If necessary, migrate a copy with the matching reviewed build; preserve the original.
  3. Configure PostgreSQL and the copied artifact directory, then explicitly migrate the empty target.
  4. Import the current-schema SQLite snapshot:
sych db migrate --config pg.yaml
sych db import-sqlite --source /protected/snapshot/sych.db --config pg.yaml

The implementation in crates/sych-storage/src/import.rs and crates/sych-storage/src/import/schema.rs opens SQLite read-only, checks integrity/foreign keys, checks exact tables/columns against an isolated trusted schema, and validates migration versions, success markers and checksums for both backends. All 25 target application tables must be empty.

One PostgreSQL writer transaction copies rows, restores finding predecessor links, resets identities, and verifies ordered row counts plus typed, length-framed SHA-256 fingerprints. Every extant artifact row must have the expected partition-derived key, in-root canonical file path, size and content hash. Already-pruned pointers remain unavailable. Import neither migrates the databases nor copies/rewrites artifact bytes.

Any validation/copy failure rolls back target rows; counts/digests are logged only after commit. The source database and files are left untouched. Keep writers stopped through verification. After PostgreSQL accepts new writes, the original SQLite snapshot is stale, not a safe rollback; recover with PostgreSQL and its matching artifact files (docs/STORAGE.md).

Key source files

File Change entry point
crates/sych-storage/src/lib.rs Public types, artifact kinds, local lifecycle and final result commit
crates/sych-storage/src/connection.rs Backend opening, migrations and writer lock
crates/sych-storage/src/sql.rs Shared active/fence/visibility predicates
crates/sych-storage/src/artifacts.rs Content addressing and file durability
crates/sych-storage/src/ledger.rs Reservation/settlement invariants
crates/sych-storage/src/import/schema.rs Import table inventory and schema validation
crates/sych-storage/src/gc.rs Artifact eligibility and race-safe deletion
crates/sych-storage/src/retention.rs Operational-row retention
crates/sych-storage/tests/finalize.rs Completion/outbox failure matrix
crates/sych-storage/tests/checkpoints.rs Fence loss and accepted-answer persistence
crates/sych-storage/tests/upgrade.rs Existing SQLite data across schema upgrades
crates/sych-storage/tests/postgres/import.rs Offline import contract cases
crates/sych-storage/tests/postgres/races.rs Cross-pool PostgreSQL races

For a persistent change, add the appropriate backend migrations, preserve shared-query semantics and update import validation/tests when the schema changes. Run cargo test --locked -p sych-storage; PostgreSQL contracts additionally require a disposable admin database and just test-postgres. Never point that suite at production. See Testing.

Scope and maintenance snapshot

Scope: crates/sych-storage/ plus migrations/ at revision 00dc7637f89a47ee6fd4713204f8331418428370. There are 75 tracked files: 48 Rust files, 25 SQL migrations and 2 package documents/manifests. Rust comprises 31 files outside tests/ and 17 integration-test/support files. 16/48 (33.3%) contain a #[test] or #[tokio::test…] attribute, including inline tests. This is a test-bearing-file ratio, not line coverage; application consumers and root fixtures are excluded.

All-history git log origin/main --format='%an' -- crates/sych-storage migrations yields 2 distinct nonbot author display names after exact-name deduplication, without alias merging or co-author trailers. The byline lists the most recent distinct names as first names/usernames, not an ownership assignment.

Clone this wiki locally