feat: the sender ratchet as its own row, and the receive side beside it (marmot-kmp, Phase 8)

The piece Phase 7 deferred, in both directions, because they are one question:
a group's state is a few kilobytes of ratchet tree, group context and epoch
secrets, and the app was rewriting all of it to record things that moved a
counter.

Sending an application message advances exactly one thing -- this leaf's entry
in the secret tree (RFC 9420 §9) -- so the library carries the position as its
own record, `MlsGroupStateStore.saveSenderRatchet`, in the spirit of OpenMLS
keeping `message_secrets` apart from `group_state`. Giza defaulted that to
false, which sent the manager back to a full save per message. It is now a
`MarmotSenderRatchet` row, one per room, schema 36 -> 37 with an AutoMigration.
The bytes are stored as the library wrote them -- the `MarmotPublishObligation`
precedent, not the retained-epoch one -- because a record whose whole job is to
never go backwards is safest when nothing here re-encodes it; the epoch, leaf
and generation sit beside it, read off those same bytes, so they cannot drift.

The hazard this introduces is an ordering, and it is in the app's code, not the
library's. `MlsGroupManager.restoreAll` applies the record itself. A room joined
after the engine restored is loaded from its row by `MarmotEngine.groupFor`
instead, and that has to apply the record BEFORE `adoptGroup`, because adopting
persists and persisting rewrites the row from the group being adopted. The other
way round, the next restart re-emits generations already published, under AEAD
keys and nonces already used.

Finding the test that could tell the two orders apart took two goes. The first
asserted the row after a lazy load and passed with the order inverted: a state
saved before this leaf ever sent has no ratchet entry, `exportOwnSenderRatchet`
returns null, and the adopt writes nothing. The order cannot matter until the
stored state holds a position of its own behind the record's, and a received
message is what puts one there. With one receive in the middle the inverted
order fails with expected:<2> but was:<1>.

The receive side is a full save, from `MarmotEngine.processGroupEvent`, which
`NostrDao` now reads inbound events through so a second caller cannot forget it.
And a correction to Phase 5, which said an unwritten row still lost the late
message. It does not: mls-kmp writes the skipped keys beside the positions they
belong to, so an unwritten row is an older COHERENT state, and a position that
has not passed the late generation derives it forward. quartz's engine saved the
positions and dropped the keys -- that pair is what lost messages. The cost of
an unwritten row is the re-deriving, against SecretTree's thousand-step cap. The
reason the write lands now is the send side: until this change every send wrote
the whole state, so the row could not fall far behind inside an epoch.

1167 tests across 156 classes, 0 failures; Android and JVM compile clean; the
four audits unchanged. docs/mls-skipped-keys.md loses its mitigation claim and
gains the correction; docs/marmot-kmp.md gains Phase 8.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5 committed 2026-11-19 09:55:31 +02:00
1 parent 7fb56b8f8f
commit e07bb68014
13 files changed
+5263 -93

No files matched your search

+10 -6
View File
@@ -21,7 +21,7 @@ the [retired](./retired/) notes now.
| [marmot-membership.md](./marmot-membership.md) | how members join an MLS group, and the epoch race that makes a missing member look like a successful invite |
| [member-chronicle.md](./member-chronicle.md) | handing a member added after the work was done the group's signed record — why the events are not on the wire at all, and why the room's id is enough to verify them |
| [marmot-direct-messages.md](./marmot-direct-messages.md) | a one-to-one message inside a group as a stock NIP-59 gift wrap — what its MIP-03 carve-out costs, why the sender cannot read their own, and the one query that would broadcast it |
| [mls-skipped-keys.md](./mls-skipped-keys.md) | why a group event that arrives a moment late is dropped for good, which flows trigger it, the quartz fix, and the partial mitigation in this app |
| [mls-skipped-keys.md](./mls-skipped-keys.md) | why a group event that arrives a moment late was dropped for good, which flows triggered it, the fix as it landed in mls-kmp, and the one word of the diagnosis that was wrong |
| [long-running-sync.md](./long-running-sync.md) | the chat subscriptions that stay open instead of pulling once per screen — why the request queue could not simply hold one, and how the group filter follows the room list |
| [dead-code.md](./dead-code.md) | code in the sync and relay stack that nothing calls, why each piece is still there, and which of it is a bug rather than a leftover |
| [nsec-sign-in.md](./nsec-sign-in.md) | signing in with an existing nostr key — why an nsec can never have a wallet behind it, the ten call sites that make it small, and the sign-in machine that was already built and unreachable |
@@ -31,7 +31,7 @@ the [retired](./retired/) notes now.
| [npub-profile-preview.md](./npub-profile-preview.md) | showing the person before a direct message is started from a pasted npub — why the preview is a screen keyed by public key, what "found" means when a row can be a placeholder, and the phase that makes the button honest about a key package that never comes |
| [material-design-conformance.md](./material-design-conformance.md) | what the M3 foundations actually require, measured against all 43 screens — the colour pairing that renders the app's own proposals invisible, and eight phases that put the decisions back in the theme |
| [marmot-v2.md](./marmot-v2.md) | bringing the group layer onto the Marmot current profile after the quartz 1.15.2 bump — the nine rules that reach this app, why the room's id and the routing id have to become two values, nine phases from reading both profiles to publishing before applying, and the one fork the library cannot yet settle |
| [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, and eight phases that put the swap in one commit and the evidence around it |
| [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, and how often this app persists a group once a sent message no longer rewrites it |
| [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase |
| [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu |
@@ -81,15 +81,19 @@ of nine rules and its two constraints before any phase, and its table of where t
build chose differently before any of the code -- its first row, that a room's
profile picks its pipeline, is the shape of everything that follows, and its last
is the one fork the library cannot yet settle.
The marmot-kmp note is a phased plan that has been built, phases 0 to 7, and reads
The marmot-kmp note is a phased plan that has been built, phases 0 to 8, and reads
as the Marmot v2 note's Phase 0 come round again: quartz took the engine out, so
the version the v2 work was built on is the last one that has it. Read the v2 note
first — this plan happens entirely on the current-profile side of its first row —
and read this one's two constraints before any phase: the group state already on
devices is what decides whether the move can ship at all, and Phase 4 is where it
is measured rather than argued. What it does not claim is in its status note: no
manual upgrade of a profile with real rooms has been done, and that is the last
check before a release.
is measured rather than argued. Phase 8 is the one phase that was not in the plan
as written, and is the one to read if you are changing when a group is saved: it
is where a sent message stopped rewriting the whole state, where the ordering that
decision hangs on is spelled out, and where the skipped-keys note's diagnosis is
corrected. What it does not claim is in its status note: no manual upgrade of a
profile with real rooms has been done, and that is the last check before a release,
now over a schema change as well.
The ceremony-creation note is a phased plan that has been built. It reads as
the subgroups note's Phase 10 followed through to the screens: read it after
that phase, and its table of findings before any phase. Its second half
+121 -12
View File
@@ -20,19 +20,18 @@ everything here happens on the current-profile side of that branch.
[mls-skipped-keys.md](./mls-skipped-keys.md) second — it is the gap this move closes, and
the only one it closes for free.
**Built**, phases 0 to 7, one commit each but for 5 and 6, which share one because the
fork probe produced no code. Written against the code as it stood at `8b066795`, against
marmot-kmp `2.2.1`, mls-kmp `1.3.0`, crypto-kmp `2.1.0` and quartz `2.7.3`. The phases are
kept as they were written, with what each one turned out to be recorded under it, because
the reasoning is the point and the code reads better against the argument it came from.
**Built**, phases 0 to 8, one commit each but for 5 and 6, which share one because the
fork probe produced no code. Phase 8 was the piece Phase 7 deferred and is the only one
that was not in the plan as written. Written against the code as it stood at `8b066795`,
against marmot-kmp `2.2.1`, mls-kmp `1.3.0`, crypto-kmp `2.1.0` and quartz `2.7.3`. The
phases are kept as they were written, with what each one turned out to be recorded under
it, because the reasoning is the point and the code reads better against the argument it
came from.
Three things it does not claim. **The manual upgrade has not been done** — Phase 4 proves
a real version-4 blob opens, and a profile with real rooms in it is still the last check
before a release. **The sender ratchet record and the receive-side write are deferred**,
both deliberately and for the same reason: they are one decision about how often this app
persists a group, they want a schema change, and Phase 7 says why that is its own piece of
work rather than this one's tail. **And the authored fork is still not settled** — Phase 6
probed it and the gap is the library's, unchanged.
Two things it does not claim. **The manual upgrade has not been done** — Phase 4 proves a
real version-4 blob opens, and a profile with real rooms in it is still the last check
before a release, now over a schema change as well (36 → 37). **And the authored fork is
still not settled** — Phase 6 probed it and the gap is the library's, unchanged.
| phase | what it was |
|---|---|
@@ -44,6 +43,7 @@ probed it and the gap is the library's, unchanged.
| 5 | the skipped keys: the format carries them, the app's row does not yet |
| 6 | the authored fork, probed: still open, and the fix now visible |
| 7 | the guard, so the engine cannot come back from quartz |
| 8 | the sender ratchet as its own row, and the receive-side write beside it |
## Where the engine went
@@ -619,6 +619,11 @@ no new behaviour inside the swap. It is the obvious next task, and it is the sam
the receive-side write Phase 5 pinned — worth doing as one piece of work that decides how
often this app persists a group, for both directions at once.
*That became Phase 8, as its own piece of work and its own commit, and the reason to do
both halves together turned out to be stronger than this paragraph guessed: the send-side
record is what stops the row being written, so the receive-side write is what keeps it
current afterwards. See below.*
**Durable ingest dedup: not reachable without `MarmotManager`.**
`MarmotIngestDedupStore` is taken by the client, not by `MarmotInboundProcessor`, so the
follow-up marmot-v2.md's Phase 5 asked for is only available by adopting the client — the
@@ -627,6 +632,110 @@ now runs in this repo's tests and the app's own orchestration agrees with it. Wh
is a decision about what owns the stores and the publisher in the app, not a question
about whether the library's client works.
## Phase 8 — how often this app persists a group
The piece Phase 7 deferred, as one change in both directions, because they are one
question: a group's state is a few kilobytes of ratchet tree, group context and epoch
secrets, and the app was rewriting all of it to record things that moved a counter.
**What moves, and what has to be written for it.**
| what happened | what actually changed | what the app writes now |
|---|---|---|
| an epoch change — a commit applied, a Welcome processed, a convergence rewind | nearly everything | the whole state, by the manager, as it applies it (unchanged) |
| this device **sent** an application message | this leaf's own entry in the secret tree (RFC 9420 §9) | a `MarmotSenderRatchet` row, ~100 bytes |
| this device **received** an application message | the sender's receive ratchet, and any generations it skipped past | the whole state, by `MarmotEngine.processGroupEvent` |
| a standalone proposal staged | the pending-proposal pool | the whole state, by the manager (unchanged) |
The send side is the library's own split — `MlsGroupStateStore.saveSenderRatchet`, in the
spirit of OpenMLS keeping `message_secrets` apart from `group_state`. The receive side has
no equivalent and cannot have the same one: the skipped keys are `(leafIndex, generation)`
pairs for *other* members' ratchets, they live in `MlsGroupState` and nowhere else, and
`OwnSenderRatchet` is this leaf's position only.
**The table is `MarmotSenderRatchet`: one row per room, the record opaque.** `chatRoomId`
as the primary key, and the FK to `ChatRoom` with `CASCADE` the way
`MarmotRetainedEpochSecret` has it. The bytes are stored as the library wrote them, which
is the opposite of what the retained-epoch store does — it decodes `RetainedEpochSecrets`
into five columns — and the precedent followed instead is `MarmotPublishObligation`, whose
KDoc says the bytes are "opaque here, because the gate decodes them". The reason to choose
that way round here: the retained-epoch rows already existed, written by the outbound path
for another purpose, and `RetainedEpochSecrets` is RFC-shaped. `OwnSenderRatchet` is the
library's own invention, it carries both the handshake and the application chain because
it already grew once, and a record whose entire job is to never go backwards is safest
when nothing in this app re-encodes it. `epoch`, `leafIndex` and `applicationGeneration`
are kept beside it, read off the same bytes as they are written: they cannot drift from the
blob, and "where does this device think its ratchet is" is the first question a lost
message asks.
**Schema 36 → 37, one `AutoMigration`.** A new table, so Room generates it. A room that
existed before the upgrade has no row, which reads as "has not sent since its last full
save" — true of every one of them at that moment, because the build before this one saved
the whole state on every send.
**The ordering hazard, which is the real content of this phase.** `MlsGroupManager`
applies the record itself in `restoreAll`. The app has a second way in — a room joined
*after* the engine restored is loaded from its row the first time it is asked for, which
is the common way round in a running app — and `MarmotEngine.groupFor` is that path. It
has to apply the record **before** `groupManager.adoptGroup`, because adopting persists,
and persisting rewrites the ratchet row from the group being adopted. Apply it afterwards
and the row has already been overwritten with the restored state's older position: the
group in memory looks right for the rest of the process, and the next restart re-emits
generations that have already been published, under AEAD keys and nonces that have already
been used.
`SenderRatchetPersistenceJvmTest` has it both ways round, and finding the test that could
tell them apart took two goes. The first version asserted the row after a lazy load and
passed with the order inverted — because a state saved before this leaf ever sent has no
ratchet entry at all, `exportOwnSenderRatchet` returns null for it, and the adopt writes
nothing. The order cannot matter until the stored state holds a position of its own that is
behind the record's, and what puts one there is a *receive*: it is a full save, so it
captures wherever the sender ratchet had got to, and the sends after it move the record
past that. With one received message in the middle the inverted order fails with
`expected:<2> but was:<1>`, which is the rewind, in the row, in one line.
The same file has the A/B that says the record is load-bearing at all: with the row, a
restarted engine's next message is read by the peer; with the row deleted, the same message
is refused, because the peer's ratchet for this leaf has consumed that generation and RFC
9420 §9 does not allow it twice.
**A correction to Phase 5.** That phase pinned the receive-side gap and said a restart
between two messages still lost the late one. That is not what an unwritten row costs
here, and the difference is worth stating because it is the whole reason the original bug
was a bug. quartz's engine saved the ratchet *positions* and dropped the skipped keys, so
the saved state said the ratchet had passed generation N while carrying nothing for it —
incoherent, and a message lost. mls-kmp writes both or neither, so an unwritten row is
simply an older *coherent* snapshot, and a snapshot that has not passed the late generation
derives it forward. What the gap actually cost was the deriving — every generation since
the last full save, re-derived after each restart, against `SecretTree`'s thousand-step
forward cap — plus replay protection, which `consumedGenerations` does not persist in any
case.
So the receive-side write is not a lost-message fix, and this phase does not claim it is.
Its reason is the send side: until this change every send wrote the whole state, so the row
could not fall far behind inside an epoch. Once sends write a ratchet record instead,
nothing updates the row between epoch changes, and a long-lived room could drift an
unbounded number of generations from what this device has actually read. That is what
`MarmotEngine.processGroupEvent` closes, and it is why the two halves are one change.
**One more seam.** `NostrDao` now reads inbound events through `MarmotEngine.processGroupEvent`
rather than `engine.inbound.processGroupEvent`, so the write cannot be forgotten by a
second caller; the engine's KDoc says so, and the one test that used the processor directly
was moved to the same door.
**Built.** 1167 tests across 156 classes, 0 failures; Android and JVM compile clean; the
four audits unchanged. Six new tests — five in `SenderRatchetPersistenceJvmTest`, one more
in `SkippedGenerationJvmTest`, whose third test is now inverted from what Phase 5 left and
whose KDoc carries the correction above. `IdentitySwitchJvmTest`'s profile test failed once
during this phase on a 5-second DataStore timeout and did not reproduce in four later runs,
including the full gate; it passes in isolation on this commit and on the one before it,
and its own KDoc says it depends on a DataStore cache that is per-process and per-test-order.
What this phase does **not** do: encryption at rest. The record holds two 32-byte chain
secrets, so it is exactly as sensitive as the state beside it, and it carries the same
`TODO(security)` the rest of the store does. Phase 8 moves those bytes into one more table
and does not change what guards them.
## Out of scope
`marmot-quic` and agent text streams. MIP-04 encrypted media and the Blossom image
+39 -20
View File
@@ -7,12 +7,15 @@ This is a conformance gap in quartz's MLS implementation, not in this app. What
this app can do about it from outside the library is partial, and is described
at the end.
**Half of it is closed.** The engine left quartz for mls-kmp
([marmot-kmp.md](./marmot-kmp.md)), and mls-kmp's state format carries the skipped
keys -- steps 1 to 3 of "The fix, in quartz" below, landed in the library the app now
depends on. What is left is not the same gap, and the last section says what it is.
Everything between here and there is the account as it stood, and is kept because it
is still why any of it matters.
**This is closed.** The engine left quartz for mls-kmp
([marmot-kmp.md](./marmot-kmp.md)), and mls-kmp's state format carries the skipped keys
beside the ratchet positions they belong to -- steps 1 to 3 of "The fix, in quartz" below,
landed in the library the app now depends on. Step 4, the replay guard, is still not
persisted by anyone, and that is the one thing here that is still open. The last section
says what landed where, and corrects one thing this note has wrong about why the bug bit.
Everything between here and there is the account as it stood, and is kept because it is
still why any of it matters -- and because the diagnosis, not just the fix, is what makes
the next state format reviewable.
## Symptom
@@ -240,21 +243,37 @@ So the test this note asked for -- "save and restore a group between the two mes
of an out-of-order pair, and assert the older one still decrypts" -- now passes, and it
is `SkippedGenerationJvmTest`.
**What is still broken, for a different reason.** `MlsGroupManager.decrypt` persists
only when the message was a commit that advanced the epoch. An application message is
decrypted and nothing is written, so the secret reaches the live group's state and never
reaches `ChatRoom.mlsGroupState` -- and a process that dies between the two messages
still loses the late one. The mitigation section above therefore still stands, word for
word, including its three bullets; only its first sentence has a new cause. It is no
longer "the cache is never written" but "the state is not saved after a receive", which
is a decision about write amplification rather than an oversight: persisting per inbound
message re-encodes the ratchet tree, the group context and every epoch secret, per
message, growing with the group. `MlsGroupStateStore.saveSenderRatchet` is the shape of
the answer on the send side, and the receive side wants the same treatment.
**And the row keeps up with it.** `MlsGroupManager.decrypt` persists only when the
message was a commit that advanced the epoch, so an application message reached the live
group's state and nothing else. `MarmotEngine.processGroupEvent` writes the state after
one now ([marmot-kmp.md](./marmot-kmp.md), Phase 8), which is why `NostrDao` reads inbound
events through the engine rather than through the library's processor directly.
`SkippedGenerationJvmTest` pins all of it: the secret is in the state the engine would
save, a group rebuilt from those bytes reads the late message, and the stored state does
not carry it yet. Its last test says what to do the day that changes.
**A correction to this note, while closing it.** Step 2 above is not merely half the fix
-- it is the whole of it, and this note's account of *why* the bug bit needs one word
changed. The losing pair was not "the cache is dropped" on its own. It was that the cache
was dropped *while the positions were kept*: `exportSenderStates` wrote that the ratchet
had passed generation N, and nothing carried N's secret, so the restored state refused a
message it had told itself it was past. mls-kmp writes both or neither, so a state saved
without the skipped keys is now an older **coherent** state, and a coherent state that has
not passed the late generation derives it forward. The three bullets of the mitigation
section above are therefore no longer describing a lost message. What an unwritten row
costs is the deriving -- every generation since the last full save, re-derived on each
restart, against `SecretTree`'s thousand-step forward cap -- and replay protection, which
step 4 does not give us in any case.
Which leaves the reason the receive-side write landed when it did, and it is not this note's
bug. Until Phase 8 every sent message wrote the whole group state, so the row could not
fall far behind inside an epoch. Phase 8 replaced that with a ~100-byte sender-ratchet
record, and from then on nothing would have updated the row between epoch changes: a
long-lived room could drift an unbounded number of generations from what the device had
actually read. The write keeps it current. The two halves are one change for that reason,
not for this one.
`SkippedGenerationJvmTest` pins what is true: the secret is in the state the engine would
save, a group rebuilt from those bytes reads the late message, the row carries what the
live group holds, and -- the one that matters for the paragraph above -- the row's ratchet
positions move with the secrets it keeps, so the two can never disagree again.
One thing this does not change: a device that loses a message this way can still be sent
a new one, which is encrypted at a generation it has not passed. That is still the