node-app-replica 7.7.27

Change-only replication for Node app backends: a per-collection ledger (epoch, version, tombstones) that answers a device's pull with nothing new, the changes, or a full copy
Documentation
# node-app-replica

Change-only replication of app data for Rust app backends (Phase 3 of the one-stack design:
`docs/superpowers/specs/2026-11-19-one-stack-phase-3-replication.md`, sections 4 and 5).

An app declares each collection once and tells the helper what changed. The helper keeps a small
ledger in the app's own database (keys, digests, versions, tombstones — never the rows) and answers
the node's pull with one of three replies: **nothing new**, **the changes** since the caller's
version, or a **full copy**. The app writes no versioning code.

The crate depends on `serde`, `serde_json` and `sha2`, plus `rusqlite` 0.31 behind the `sqlite`
feature. It does **not** depend on `node-app-sdk-rust`, so an app pinned to any SDK version can use it.

```toml
[dependencies]
node-app-replica = { version = "7.7", features = ["sqlite"] }
```

`rusqlite` is never built with `bundled`: an in-process app must link the host's `libsqlite3`
(ADR-141).

## Declare a collection

```rust
use node_app_replica::Collection;

/// `<app>.<collection>.pull`; table prefix; the schema numbers (the `N` of `.vN`) served.
pub static PEOPLE: Collection = Collection::new("friends.people.pull", "friends_", &[1]);
```

Create the ledger's tables where the app creates its own, on every start (idempotent):

```rust
PEOPLE.ensure(&conn)?; // friends_replica_collections, friends_replica_rows, friends_replica_meta
```

The table prefix is empty or `[A-Za-z_][A-Za-z0-9_]{0,47}` (it starts SQL identifiers, so not a digit).
`friends_replica_meta` holds the ledger's layout number; `ensure` upgrades a ledger written by an
older helper in place and refuses one written by a newer helper.

## Tell it what changed

Either hand over the whole current list (the helper finds what changed: one digest per row), or
record changes at the write sites. Both can be mixed.

```rust
use node_app_replica::Row;
use serde_json::json;

let rows: Vec<Row> = list_people(&conn)?
    .into_iter()
    .map(|p| Row::new(p.did, json!({ "name": p.name })).with_ord(p.position))
    .collect();
PEOPLE.reconcile(&conn, &rows)?;        // Some(new head) when it moved

PEOPLE.touch(&conn, &Row::new(did, json!({ "name": name })))?; // one row written
PEOPLE.remove(&conn, &did)?;                                     // one row deleted
PEOPLE.mark_dirty(&conn)?;                                       // "something may have changed"
```

A row is a key (1–256 bytes, no control characters), any JSON value (≤ 65,536 bytes encoded and at
most 127 containers deep: the node's serde_json stops at 128, so a deeper value would break every full
copy of the collection), an `ord` (its place in the list, |ord| ≤ 2^53 − 1, default 0) and a `part` (a
group, ≤ 128 bytes, default `""`). A row outside these limits is refused, and a `reconcile` with one bad
row records nothing. `wire::value_within_depth` is the depth check, counted as the device's storage
counts it; `tests/fixtures/value-depth.json` holds the cases both helpers test.

On SQLite every ledger write is one `BEGIN IMMEDIATE` transaction, so two connections to one file
never hand out the same version; give the connection a busy timeout. Inside a transaction the app
already holds, the ledger uses a savepoint and commits or rolls back with the app's own write.
`head()` and a pull answered "nothing new" are one `SELECT` and take no write lock. A `touch` or
`remove` costs a few indexed statements: pruning reads partial indexes on the tombstones, never the
live rows (0.16 ms at 100,000 rows on x86).

`mark_dirty` makes the next pull that reaches the app reconcile first. The node answers a device that
holds the head it remembers without calling the app, so a dirty mark alone does not reach devices:
reconcile and announce on a periodic tick (Friends uses its 5-minute discovery tick) as the safety net
for writers the app does not hear about. A `reconcile` the app runs in the background and that fails
records nothing; like a failed announce it is the app's to retry, because the node does not call the
app while devices hold the head it remembers.

A reconcile reads every row the app hands over: one digest per row plus one read of the ledger,
about 1.0 µs per row on x86 (100 ms at 100,000 rows), plus the app's own `load(None)`. A pull after
`mark_dirty` pays that inside the node's 5-second budget (measured: 240 ms at 100,000 rows on x86,
60 ms of it the benchmark's own `load`; a Raspberry Pi is several times slower). Up to about 20,000
rows nothing more is needed. Above that, record writes with `touch`/`remove` and run whole-list
`reconcile` on the app's own tick, not through `mark_dirty`, so no device check waits for it.

## Serve the pull capability

Add the capability to `provides` and `capabilities.provides` in `manifest.json`, and to
`provided_capabilities` with `PEOPLE.description()`. Then dispatch:

```rust
"friends.people.pull" => {
    let reply = PEOPLE.pull(&conn, &request.payload, |conn, keys| load_people(conn, keys))?;
    // ...return `reply` as the capability's payload
}
```

`load(conn, None)` returns every current row; `load(conn, Some(keys))` returns the rows of those keys
(a key with no row is left out). It runs inside the ledger's transaction, on the same connection, and
must not call the collection again. Errors come back with a stable prefix
(`replica_schema_unsupported:`, `replica_request_invalid:`, `replica_row_invalid:`,
`replica_load_failed:`, `replica_store_failed:`, `replica_config_invalid:`). `PEOPLE.answer(...)`
returns the typed `PullReply`, and whether the pull moved the head (then announce).

A pull reflects every write the app has acknowledged: a dirty ledger is reconciled first, and a row
whose loaded value no longer matches the ledger (a write the app did not report), or a key the app no
longer has, is recorded before the answer is built.

## Announce

After a write that moved the head (including a pull whose `head_moved` is true), and once per
collection at start, before the app's first write:

```rust
use node_app_replica::{Announcer, AnnounceOutcome};
use node_app_sdk_rust::{invoke_capability, CapabilityRequest};

struct HostBus;
impl Announcer for HostBus {
    fn invoke(&self, capability: &str, payload: serde_json::Value) -> Result<serde_json::Value, String> {
        let response = invoke_capability(&CapabilityRequest {
            capability: capability.into(),
            payload,
            ..Default::default()
        })
        .map_err(|e| e.to_string())?;
        if response.success { Ok(response.payload) } else { Err(response.payload.to_string()) }
    }
}

match PEOPLE.announce(&conn, &HostBus) {
    AnnounceOutcome::Accepted(_) | AnnounceOutcome::Rotated(_) => retry.clear(),
    AnnounceOutcome::Failed { error, first } => {
        if first { host_warn(&error); } // once per failure run
        retry.schedule(); // the app's own timer: announce again later
    }
    AnnounceOutcome::RotationDeferred(_) => retry.schedule(),
}
```

An announce never fails the app's work, but it is what tells devices: the node answers a device that
holds the head it remembers with "nothing new" without calling the app, so until an announce lands no
device sees the change (not even on its next check). **The crate does not retry**: `announce` is one
synchronous call and the crate runs no timers or threads, so retrying a `Failed` or `RotationDeferred`
announce is the app's duty — with bounded backoff on its own scheduler (the TypeScript helper's
`Replica` retries after 2 s, doubling to 60 s, until it succeeds), and at the latest on the periodic
tick below. When the node answers `{"rotate":true}` (it has handed out a higher version of this epoch:
the app's database went back in time), the helper starts a new epoch at once and announces again.

The start announce is how a database restored while the app was stopped is found: the node has
handed out versions the restored ledger reached again with other data. A write before that announce
could take such a version. While the app runs, the helper needs no announce for this: it remembers
the highest version it handed out (or the node took, or the node said it had) per epoch, and a
ledger that reads lower in the same epoch rotates before anything else happens.

## Epochs, tombstones, reset

- A version is a per-collection integer; each changed row takes the next one. An epoch
  (`[a-z0-9]{8}`) names one unbroken run of versions.
- The epoch rotates when the ledger is created, and on evidence that the database went back in time:
  a pull from a device ahead of the head in the same epoch, an announce answered with `rotate`, or
  a ledger that reads below what this process handed out in that epoch. Evidence rotates at once.
  Held back, the ledger would go on answering in an epoch whose higher versions are already on
  devices with other data, and a device whose version names exactly the restored head (one that
  just finished a paged copy holds rows newer than the copy's version) would be told "nothing new".
- `reset()` (the app replaced its data) and the pruning guard ask for a rotation. These are limited
  to one a minute per collection, so a burst of them costs the devices one full copy, not one each.
  A rotation the limit holds back is **owed**: it is stored with the collection's record, happens
  before the next version is assigned (a write never takes a version of the old epoch) or at the
  first ledger operation after the minute, and is never dropped.
- Rotation renumbers the live rows 1…n in key order and drops every tombstone; every device takes
  one full copy.
- A delete is a tombstone at its version. Tombstones are kept 30 days and at most 5,000 per
  collection; pruning raises the collection's `floor` to the highest version pruned, and a device
  asking from below the floor gets a full copy.

## Replies

| Case | Reply |
|---|---|
| Nothing new | `{"e":"k3f9a2c1","v":41}` |
| Changes | `{"e":"k3f9a2c1","v":43,"u":[["<key>",<value>,<ord>,"<part>"],…],"x":["<key>",…]}` plus `"m":1` when more remain |
| Full copy | `{"e":"p0q9r8s7","v":7,"f":1,"u":[…]}` plus `"n":"<last key>"` when more pages remain, and `"h":<head>` on a later page read after the head moved; rows in key order |

A row entry drops a trailing `part` of `""` and then a trailing `ord` of 0; object keys inside values
are written sorted. A changes reply always carries both `u` and `x`.

Two properties every reply keeps, so that a device's `(epoch, version)` always names exactly the
list it holds (which is what lets the node detect a restored database):

1. **A cut change list ends on an exact version.** Changes are read in version order, but a row that
   changed twice keeps only its latest version, so a cut after an arbitrary change would leave the
   device without that row's earlier value while claiming the later version. A cut is made before the
   first superseded version; when the very first change after the caller's version was superseded,
   the caller gets a full copy instead.
2. **A paged full copy is "as of" page one's version `V` and always finishes.** Later pages (`"a"` =
   the previous page's `"n"`) carry the rows after the resume key as they are now and keep `V`, so a
   copy takes as many pages as the list has, however busy it is. Once the last page is in, the caller
   asks for the changes since `V`: they bring every row changed after `V` (whatever page it was on)
   and every delete after `V`. Only when deletes after `V` were forgotten (`V` below the floor) does a
   resumed request start a new copy at the head (its version is above `V`, so the caller sees a new
   page one). Until that follow-up, the device holds rows up to the head the pages were read at, so a
   later page whose head is above `V` carries `"h"`: the node raises its mark for the epoch to it
   (below) and does not pass it on.

## Wire types and golden fixtures

`node_app_replica::wire` has the contract's shapes with byte-exact encoders: `PullRequest`,
`PullReply`, `SyncRequest`/`SyncEntry`/`SyncReply`/`SyncAnswer` (`core.replica.sync`), `Announce`/
`AnnounceReply` (`core.replica.announce`) and `HeadsData` (`replica.heads`). Decoding ignores keys it
does not know (the router stamps `caller` and `caller_ingress` into every payload).

`tests/fixtures/*.json` holds the exact bytes of each exchange, one line each, and is shared with the
TypeScript helper and the client kernel. The Friends "nothing new" check is 141 bytes out
(`sync-request-two.json`) and at most 142 back (`sync-reply-nothing-new-two.json`). 142 is an upper
bound: the fixture's envelope timestamp has 9 fraction digits (`…56.789012345Z`); a timestamp written
with fewer makes the reply shorter.

### Device-selected history windows

A provider serving a selectable recent-history capability can deserialize its input as
`WindowedPullRequest`. Its `request` holds the ordinary paging fields and its
`window_days` holds the requested positive day count. An absent day count selects 30 days.
Use `WindowedAnnounce` with the same day count when publishing the head of a custom window.

A batch can be decoded as `WindowedSyncRequest`. Its entries accept the ordinary four-slot
form, the five-slot paging form and the six-slot custom form. Calling
`WindowedSyncEntry::pull_request` forwards the count and cursor to the provider. The SDK
validates day counts up to the largest JavaScript safe integer. Legacy Rust structures keep
their existing fields and encodings. A legacy `SyncEntry` or `PullRequest` rejects a custom
window at deserialization. [ADR-395](../../docs/adr/395-configurable-device-history.md)

## For the node and the device

The helper's guarantees hold when the other two sides do the following (checked by the property test
in `tests/convergence.rs`, which models them):

- **Node, resumed entries**: an entry with a resume key (fifth element) is always passed to the app,
  never answered `0` from the head cache, and its reply's head is not recorded as the collection's head
  (a later page carries page one's version).
- **Node, marks**: remember, per capability, the highest version handed out in **each** epoch seen —
  `PullReply::handed_out()`: the reply's `v`, or its `"h"` when higher; truncated replies and pages
  included, not only complete ones; announces it accepted too — and answer an announce with `rotate`
  when its epoch's mark is above its version. Comparing with the current head only misses a database
  restored twice to the same backup, a device that took a truncated reply, and one that took a page.
- **Node, persistence**: the marks survive a node restart. A raised mark is written to the node's
  database before the reply that raised it is sent; marks are kept as long as the app is installed
  and deleted with it. Remembered heads may be written behind (a lost head only costs one app call);
  lost marks let a restored app reuse versions a device holds.
- **Device, full-copy pages**: a full copy answering a resumed request continues the copy only when
  its `(e, v)` equal page one's; otherwise it is a new page one. After the last page it asks at once
  for the changes since the copy's version.

## Storage seam

The ledger's logic sees only `LedgerStore` / `LedgerTx`. The crate ships two stores:
`rusqlite::Connection` (feature `sqlite`) and `MemoryLedger` (process memory: a new process starts a
new epoch, so every device takes one full copy after each start — for an app with no database of its
own; a write copies the ledger, a read does not). An app on another database implements
`LedgerStore` for it; `LedgerStore::read_record` has a default that goes through `write`, and a
store with a cheaper read overrides it.