Skip to content

fix(storage): merge per-device session page logs - #245

Merged
zo-sol merged 7 commits into
IQCoreTeam:mainfrom
NubsCarson:codex/cloud-resume-isolation-20260916
Sep 17, 2026
Merged

zo-sol merged 7 commits into
IQCoreTeam:mainfrom
NubsCarson:codex/cloud-resume-isolation-20260916

Conversation

@NubsCarson

@NubsCarson NubsCarson commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Two devices could overwrite the same cloud session page (#113). This follows Zo’s proposed per-device logs: each writer appends to its own chain, readers merge the chains, and the conversation keeps one session ID. Existing encrypted legacy pages stay readable and unchanged.

Real Mac + Seeker QA found and fixed one additional display bug: the phone skipped merged messages from the Mac when its own latest message already had the newest timestamp. Reconciliation now also checks the page contents, so earlier interleaved messages appear after restore.

Validation: both devices used the same wallet and Google Drive account, produced real model replies, continued the same conversation from independently open copies, and restored all six messages after restart. The separate live-Drive harness preserved 92 online messages and 96 after offline Korean-text writes reconnected; pagination, sealed pages, and legacy bytes were verified. Post-rebase core: 547 passed, 5 skipped; required Chromium panel checks: 6 passed; core typecheck, localhost/webview builds and isolated Android debug APK build passed.

Physical-device evidence and limits · Live-Drive receipt

Merged Mac and Seeker conversation on the physical phone

Writers include a process incarnation to avoid same-device collisions; sealed pages stay immutable and pagination tracks each chain. Old clients cannot display new-format messages. This does not recover previously overwritten data or add distributed deletion tombstones or server-side fencing for timed-out uploads. Physical QA used an isolated debug package with development rootfs assets; this is not production APK release certification. No on-chain posts or transactions were made.

Refs #113. Replaces the original branch-on-resume approach. Latest follow-up: 46b5258c, rebased onto 1690b0ee after #238/#244 merged. The identical newest-page case now adopts the merged cursor and hasMore without repainting. A regression with real SessionStore device chains reproduces the pre-fix failure and verifies that B's three older Korean messages remain reachable behind A's 30 newer messages. This cursor follow-up passed the suite, typecheck, six Chromium checks and localhost/webview builds; physical-device evidence above is from the earlier six-message test. Hosted CI is running on the new head.

@zo-sol

zo-sol commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

Proposal: per-device page logs instead of branch-on-every-resume

Thanks for this. The failure it targets (#113, two devices silently overwriting each other's pages) is real and worth solving, and the QA harness here is genuinely reusable. But before accepting the always-branch tradeoffs (a new session id on every cloud resume, a full history copy and re-upload per resume, one [cloud resume xxxx] list entry per resume), I want to propose the mechanism that serverless multi-device sync systems have converged on: single-writer append-only logs, one per device, merged on read.

Why not conflict detection

You were right that detection is impossible here: Drive API v3 has no conditional writes (no If-Match / etag precondition on files.update), so a git-style compare-and-swap on a shared key cannot exist, and any read-check-write is still racy. But the alternative to "detect conflicts" is "make conflicts unrepresentable": if no two writers ever share a key, there is nothing to detect and nothing to lose.

Prior art

This is the standard answer in local-first / serverless sync, not an invention:

  • Keet (Holepunch): a chat app where each writer appends only to its own Hypercore log; Autobase linearizes the logs into one causal order
  • Secure Scuttlebutt / Manyverse: pioneered replicated single-writer append-only feeds
  • Bluesky (AT Protocol): one signed single-writer repo per account, merged by consumers, at production scale
  • Matrix: homeservers race legitimately; events form an append-only DAG and readers resolve the order
  • Actual Budget: per-client CRDT message log ordered by hybrid logical clocks, over dumb storage
  • Amazon Dynamo cart: concurrent writes stored side by side and merged on read, because losing data is worse than merging

The pattern across the industry: systems with a server use a server sequencer (WhatsApp, Figma, Linear); systems without one all use per-writer logs. We are in the second group by design (the user's own Drive, no AgentNet server), and our payload is easier than any of the above: an append-only chat message sequence, so "merge" is just an interleave sort, no CRDT library needed.

Sketch

Key scheme changes from {sessionId}__p{N} to {sessionId}__{deviceId}__p{N}. Each device appends only to its own chain and rolls its own pages at PAGE_SIZE. Full pages stay immutable (unchanged from today); the only mutable object per device is its own current page, which no other device ever touches. Reads list all chains for the session and interleave records. Meta stays last-record-wins across the merged stream, and we already carry lastDevice in meta.

flowchart TB
    subgraph W["Write path: no shared keys, overwrite impossible"]
        DA["Device A"] -->|append| PA["sess__devA__p0..pN"]
        DB["Device B"] -->|append| PB["sess__devB__p0..pM"]
        LG["Old client"] -->|append| PL["sess__p0..pK legacy chain"]
    end
    subgraph R["Read path, any device"]
        PA --> M["interleave records by ts, deviceId"]
        PB --> M
        PL --> M
        M --> V["one conversation, identical on every device"]
    end
Loading

The #113 scenario becomes:

sequenceDiagram
    participant A as Device A
    participant D as Drive
    participant B as Device B
    Note over A,B: both resume the SAME session id, both online
    A->>D: append msg to sess__A__p3
    B->>D: append msg to sess__B__p1
    Note over D: different keys, both writes land, nothing overwritten
    B->>D: list sess__*
    D-->>B: chains from A and B
    Note over B: merge by ts and deviceId, B sees A's turn too
Loading

Ordering: records already carry ts. Interleave by (ts, deviceId), and on resume seed the device's clock from the max ts seen in the merged log (HLC style bump) so a skewed wall clock cannot order new messages before ones it has already seen.

Migration: the read side treats legacy {sessionId}__p{N} as one more chain (deviceId = legacy), the write side switches to device-scoped keys. No data migration, old sessions stay readable forever. Old clients keep appending to the legacy chain, which new clients read as just another device chain, so a mixed-version fleet degrades to today's behavior at worst instead of leaving a permanent gap.

What this buys vs always-branch

branch-per-resume (#245) per-device logs
#113 data loss prevented by isolation prevented structurally, keys cannot collide
Session id new UUID every resume canonical id forever (on-chain refs, share links stay valid)
Resume cost full history copy + re-upload zero, each device only appends its own page
Session list one new entry per resume unchanged
Mixed old/new clients unprotected window old clients become one more merged chain

Direction

I want to go this way rather than branch-per-resume. Concretely: keep this PR's QA spec and harness, rework the mechanism to device-scoped chains in account/store.ts (pageKey, currentPage, loadLatest/loadOlder merge) and drop the fork-on-resume in runtime/index.ts. Happy to do the rework on top of your branch, or review if you would rather take it. Either way #113 closes with the session id kept stable.

@NubsCarson

Copy link
Copy Markdown
Contributor Author

sorry zo, I should have made this a draft PR — it wasn’t ready. sorry for giving you a headache, and thank you for taking the time to explain the better direction. I’ll rework it around the per-device logs you described and keep the QA harness, then test the replacement before calling it ready.

@NubsCarson
NubsCarson marked this pull request as draft September 17, 2026 02:30
@NubsCarson
NubsCarson force-pushed the codex/cloud-resume-isolation-20260916 branch from dc5672f to 37b537a Compare September 17, 2026 02:41
@NubsCarson NubsCarson changed the title fix(runtime): isolate cloud resumes before writing session pages fix(storage): merge per-device session page logs Sep 17, 2026
@NubsCarson
NubsCarson marked this pull request as ready for review September 17, 2026 03:59
@zo-sol

zo-sol commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator

Reviewed the rework at 9e8275a in depth. This is a faithful implementation of the per-device log design, and the quality is high: the __dp key namespace deviation is correctly motivated (a key containing __p would be adopted by old clients as a writable page of a phantom session, and the spec proves the new keys cannot round-trip through the legacy parser), sealed pages stay immutable, the incarnation scheme handles same-device collisions, legacy chains merge without rewrites, mixed old/new clients degrade gracefully instead of corrupting, and the QA receipts reconcile against the diff and the live CI runs. The harness is opt-in only and clean. I also appreciate the drive-by fix for mirror.append replacing the whole local log on put-only adapters.

One substantive defect blocks merge, and it is exactly the failure class this PR exists to eliminate:

Stale local cursor permanently omits remote chains from scrollback.

  • First paint builds its cursor from loadSessionLocal, which calls devicePages.page(id, undefined, local=true); those positions come from listLocal() only, and the mirror never caches other writers' chains locally (your own spec proves loadLatestLocal is empty after merged cloud reads).
  • The reconcile pass in session.ts (lines around 394-399) skips adoption when the merged newest window is byte-identical to the local window: JSON.stringify(page.messages) === localMessages.
  • When that skip fires, the UI keeps the local-only cursor. The traversal snapshots positions and never adds newly discovered chains mid-scroll (by design), so loadOlder on this device structurally excludes every cloud-only chain.

Reachable scenario: device B writes some messages, then device A writes 30 or more consecutive newer messages. A's merged newest-30 window is now byte-identical to A's local window, adoption is skipped on every open, and B's older history never appears in A's scroll-up. The data is intact on disk and a fresh reader, load(), export, and fork all include B, but on device A the symptom is silent cross-device history omission, reproduced on a fully new client via pagination.

Suggested fix (small and localized): on the equal-window skip, still adopt the merged page's cursor and hasMore (or construct the local first paint without a cursor whenever cloud chains exist for the session). A regression test would be: B writes N messages, A writes 30 newer ones, reopen on A, scroll up, assert B's messages appear.

Two non-blocking notes for later: a chain head that fails to decode makes meta()/loadLatest() throw loudly where the legacy listMine tolerated it (deliberate fail-closed, fine, just noting the behavior change), and backfill()'s per-key catch aborts the whole backfill silently on one transient get error.

Everything else is merge-ready. Fix the cursor adoption, add the regression test, and I will merge. #244 and #238 are already merged, so a quick rebase will be needed as well.

@NubsCarson
NubsCarson force-pushed the codex/cloud-resume-isolation-20260916 branch from 9e8275a to 46b5258 Compare September 17, 2026 04:37
@NubsCarson

Copy link
Copy Markdown
Contributor Author

Thank you — reproduced and fixed in 46b5258, rebased onto main after #238/#244. Identical newest messages now still adopt the merged cursor/hasMore, without repainting.

The regression uses real SessionStore chains: B writes three older Korean messages, A writes 30 newer messages, then A reopens and scrolls up. It failed before the fix and now retrieves all of B’s messages. Post-rebase: 547 tests passed, 5 skipped; typecheck, six Chromium checks and both web builds passed. New hosted CI is running. Updated evidence is in the PR description; the sleeping phone was not rerun for this cursor-only follow-up.

@zo-sol
zo-sol merged commit bfbe88e into IQCoreTeam:main Sep 17, 2026
2 checks passed
@NubsCarson
NubsCarson deleted the codex/cloud-resume-isolation-20260916 branch December 2, 2026 03:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants