# Snapshots and changes

`records.list` and `changes.feed` use the same contracts through CLI, Python SDK,
MCP and hosted HTTP. Local CLI/SDK/MCP calls need no server. These source
capabilities are not a public release or automatic replica synchronization.

## Read a snapshot, then consume changes

```python
from op_sys import OpSys

client = OpSys()  # Or a named hosted connection.
ledger_id = client.ledgers.create(name="example")["ledger_id"]
client.records.append(ledger_id=ledger_id, payload={"message": "Hello"})

continuation = None
while True:
    page = client.records.list(ledger_id=ledger_id, continuation=continuation, limit=100)
    # Persist/process page["items"] and permitted page["context"] here.
    continuation = page["next"]
    if continuation is None:
        checkpoint = page["changes_from"]
        break

# Requires changes.read. A records-only reader receives changes_from=None.
if checkpoint is not None:
    while True:
        page = client.changes.feed(ledger_id=ledger_id, checkpoint=checkpoint)
        for change in page["items"]:
            print(change["change_id"], change["kind"])
        # Save the new checkpoint only after processing this whole page.
        checkpoint = page["checkpoint"]
        if not page["has_more"]:
            break
```

The first snapshot page fixes the accepted-history boundary and matching change
starting point in one authority transaction. Later appends occur outside that
snapshot and inside its incremental stream. Each snapshot page returns the same
observation time and definition revision, even when the authority changes between
requests. `next=null` completes this snapshot, not every future write.

`context` contains the ledger definition only with `ledger.read`, admitted
contract bodies only with `contracts.read`, and policy only with `access.read`.
Records retain their acceptance contract reference. Retrieve a retired contract
with `contracts.get` when interpreting records under an older contract. File
bytes are retrieved separately with `files.download`; attachment references are not
copies of those bytes.

## Continuation and coverage

Snapshot tokens expire 15 minutes after the first page. Change checkpoints expire
seven days after issuance and renew on each successful poll. Treat tokens as opaque:
do not parse, edit or move them between ledgers, callers or authority epochs.
Tokens are authenticated and checked against current effective permissions and
hosted credential/storage policy on every request. They grant no access themselves.
An authorized caller can change page size while continuing these two operations.

Pages contain at most 1,000 records or scanned change positions, subject to lower
credential limits and an 8 MiB response budget, with space reserved for envelope and continuation
metadata. Snapshot reads
stream rows; hosted reads decrypt batches of at most 16 records. A change page
may be empty and still have `has_more=true` because scanned facts were outside
that caller's permitted coverage. Use `next`/`has_more`, never item count, to
recognize completion.

`observation.coverage` identifies the ledger/caller/authorization scope. It is
comparable only within that scope. `source=replica` describes retained local data;
it does not claim the replica is synchronized with a reachable authority.
`freshness=current` requires the responding active authority or fails with
`authority_unavailable`. Change `complete=true` means caught up at that response's
observation, not that future changes cannot occur. There is no cross-ledger order.

`changes.feed(start="now")` explicitly starts future-only consumption without an
initial snapshot. It returns an empty page and a checkpoint. Specify exactly one
of `start` and `checkpoint`. This is useful for changes-only callers and must
not be represented as a complete initial copy.

## Changes, removal and recovery

Changes have stable `change_id` values and kinds `record`, `definition`, or
`removal`. Replaying a checkpoint redelivers the same retained logical changes;
deduplicate by change ID. Definition context and removals obey the corresponding
current read permissions. Record removals require `records.read`, file removals
require `files.read`, and ledger removals require `ledger.read`, in addition to
`changes.read`. Administrative audit details are not exposed as change payloads.

Erasure invalidates unfinished snapshots. It does not retain payload copies for
old cursors. A feed can return a removal after a completed snapshot; when an older
unprocessed record change needs already-erased data it instead returns
`resnapshot_required`. The same error covers expired, tampered, incorrectly bound
or incompatible-epoch tokens, unavailable definition context, missing change
positions and checkpoints below the retained continuity floor. Current permission
revocation may instead return `permission_denied` before token processing.

On `resnapshot_required`, discard the incomplete read's completeness claim and
start `records.list` without continuation. Build a separate complete snapshot,
then atomically replace the previously retained **same authorized coverage** and
use the new `changes_from`. Do not interpret absence from a partial snapshot or
a different coverage scope as deletion. Keep the caller's own pending work
separate. [Replica synchronization](/docs/raw/manuals/ledger-replicas.md) composes these reads with
atomic reconciliation when explicitly invoked. A changes-only caller can explicitly restart at now but
must acknowledge the gap, or obtain permission for a new snapshot.

Removal identities are retained for the ledger's lifetime in this implementation;
there is no automatic change-log pruning. Continuity-floor metadata protects
future pruning: advancing it must be atomic with removing facts. Missing facts
already cause resnapshot instead of a silent reset. Pre-upgrade change metadata
is outside newly issued checkpoints; retained accepted history is available
through a fresh snapshot. Snapshot context and tokens retain no extra payload
copies. Signing keys stay private to the authority store.

## CLI, MCP, HTTP and bounded iterators

```sh
op-sys --output json records list --ledger-id <ledger-id> --limit 100
op-sys --output json changes feed --ledger-id <ledger-id> --checkpoint <changes-from>
op-sys --output json changes feed --ledger-id <ledger-id> --start now
```

MCP uses `op_sys_records_list` and `op_sys_changes_feed` with the same named
arguments. Hosted HTTP exposes `GET /v1/ledgers/{ledger_id}/records` and
`GET /v1/ledgers/{ledger_id}/changes`; consult the generated OpenAPI for query
arguments and errors. `resnapshot_required` carries `retry=resnapshot`.

The SDK also provides `records.pages(...)` and `changes.pages(...)`. Both yield
whole pages, retain only one response at a time and default to at most 100 requests.
Set `max_pages` explicitly when needed (1–10,000). Reaching that budget does not
complete the read: inspect the last page and resume its continuation. No iterator
silently restarts a failed snapshot or persists your checkpoint for you.
