Skip to content

Persist newer stamps merged onto unchanged content - #312

Open
jits wants to merge 1 commit into
tinyplex:mainfrom
jits:save-merged-stamps
Open

jits wants to merge 1 commit into
tinyplex:mainfrom
jits:save-merged-stamps

Conversation

@jits

@jits jits commented Nov 23, 2026 •

Copy link
Copy Markdown

Preamble

Hi 👋🏼 Big fan of this library. I'm using it to build a small personal app :)

Full caveat: I'm using this in my spare time and I've used Claude to detect, diagnose and propose this fix. I hope that's okay? Completely understand if you prefer to close this or need more clarity/time/etc. before going ahead. It seemed a potential bug worth reporting upstream with a potential fix.

Summary

A MergeableStore can merge a newer stamp for a Cell or Value whose content is the same. The store updates the stamp in memory, but autosave doesn't persist it. With this change, autosave persists it.

The content stays correct and nothing reports an error, so the effect appears only in synchronization. After each restart, the store's hashes differ from those of its peers, and the store pulls the same Cells again. A WsServerDurableObject repeats this each time it wakes from hibernation. In local workerd, with 1,900 Rows in this state and one client, each wake transferred about 750 KB in each direction. With this change, the client sent one message per wake and about 0 KB.

Worked example

A phone and a server synchronize one Cell, and the server saves to a file. In this table, dog@1 means the content dog with stamp 1.

Step Phone Server memory Server file
1. The phone sets the Cell, and the stores synchronize. dog@1 dog@1 dog@1
2. While offline, the phone sets the Cell to cat, then back to dog. dog@3 dog@1 dog@1
3. The phone reconnects, and the server merges dog@3. dog@3 dog@3 dog@1 (not saved)
4. The server restarts and loads its file. dog@3 dog@1 dog@1

After step 4, the server pulls dog@3 again and doesn't save it again. Each later restart repeats step 4. With this change, step 3 saves dog@3, so step 4 loads dog@3 and the hashes match.

This script runs those steps:

import {createMergeableStore} from 'tinybase';
import {createFilePersister} from 'tinybase/persisters/persister-file';

const pause = () => new Promise((resolve) => setTimeout(resolve, 100));
const hash = (store) => store.getMergeableContentHashes()[0];

const phone = createMergeableStore('phone');
const server = createMergeableStore('server');
const persister = createFilePersister(server, './server.json');
await persister.startAutoSave();

// Step 1
phone.setCell('pets', 'fido', 'species', 'dog');
server.applyMergeableChanges(phone.getMergeableContent());
await pause();

// Steps 2 and 3
phone.setCell('pets', 'fido', 'species', 'cat');
phone.setCell('pets', 'fido', 'species', 'dog');
server.applyMergeableChanges(phone.getMergeableContent());
await pause();
console.log('before restart:', hash(server) === hash(phone));

// Step 4
await persister.destroy();
const restarted = createMergeableStore('server');
await createFilePersister(restarted, './server.json').load();
console.log('after restart: ', hash(restarted) === hash(phone));

On main, the script prints true, then false. With this change, it prints true twice.

Cause

mergeContentOrChanges updates a stamp when the incoming HLC is newer. Autosave gets its changes from getTransactionMergeableChanges, which reads touchedCells and touchedValues. cellChanged and valueChanged fill those sets, and the underlying Store calls them only when content changes.

Change

The store keeps two more sets, stampedCells and stampedValues. They contain everything that was touched, and anything that a merge gave a different hash. Persisters ask for changes with hashes, so they read the new sets. Synchronizers ask for changes without hashes, so they read the existing sets.

Claude first added merged Cells to touchedCells. The existing tests passed, but that version isn't safe, because Synchronizers read touchedCells. Content from setDefaultContent has an empty stamp, and the merge treats an empty stamp as newer each time. Three stores in a ring, each with two Synchronizers, exchanged 1,640 messages in one second and 1,664 in the next. With the change in this PR, they exchange none, and one of the new tests covers that case.

Effects on existing apps

Method signatures, the wire format, and the stored format don't change. Apps might notice these effects:

  • A store with stale storage saves the stale Rows once, the first time it synchronizes after the upgrade. For 1,987 Rows in the fragmented Durable Object SQL Storage Persister, that save wrote 3,980 SQLite rows. startAutoSave writes the same number each time it starts.
  • This change doesn't correct Table hashes and content hashes that earlier versions saved. See Storage that earlier versions wrote.
  • If a client writes the same content with new stamps each time it starts, each merge is now saved. Before, it wrote nothing. Where writes are billed, this could add cost, so you might want to mention it in the release notes.
  • getTransactionMergeableChanges(true), and therefore the changes that a custom Persister receives, can include a Cell whose content is the same.
  • In a local benchmark, writing 60,000 Cells took about 3% longer, and merging them took about 7% longer.

Claude also restarted a WsServer twice with stale storage, 1,000 Rows, and 20 clients that reconnected together. This table shows the total traffic, measured once for each combination:

Mode Version First restart Second restart
Relay main 3,166 KB 3,189 KB
Relay This change 2,308 KB 53 KB
Hub main 3,981 KB 3,143 KB
Hub This change 3,460 KB 3 KB

First-restart traffic varies with the order in which clients answer.

Storage that earlier versions wrote

The first version of this description said that stale storage is saved once, and that was incomplete. Claude found this after deploying the change to the app.

If an earlier version merged new stamps and then saved a real edit, it wrote the Table hash and the content hash from memory, where the Rows were current, while the stored Rows were stale. A store adjusts those hashes but doesn't recompute them, so they stay wrong after this change saves the Rows. There are two outcomes:

  • The hashes match no peer. In local workerd, a WsServerDurableObject with two affected Tables and one client exchanged 11 messages on each wake with this change. In the app, three Tables were affected.
  • The hashes match the peers' hashes, so the stale Rows aren't pulled or saved. The content is correct, and the stored stamps stay old.

In the app, Claude now computes each Table hash from its Row hashes, and the content hash from the Table hashes, before each load. With 1,987 Rows that takes about 3 ms, and the same WsServerDurableObject exchanged one message on each wake. This PR doesn't include that step. It could be a separate change if you want TinyBase to do it.

The same step matters when a save fails and a later save succeeds. The later save writes hashes that include the lost Rows, so peers that match them don't send those Rows again. This happens with and without this PR.

How did you test this change?

Claude added four tests:

  • mergeable-store.test.ts: after such a merge, getTransactionMergeableChanges includes the changes with hashes and omits them without hashes. Merging the same content again adds nothing.
  • persisters/mergeable.test.ts: autosave persists the stamps once, for a Cell and a Value.
  • durable-object-sql-storage.test.ts: in fragmented mode, the stamps are saved when the same merge also changes another Cell. In that case, the content hash is correct after a reload, even when a Row isn't.
  • synchronizers.test.ts: the ring of stores described in the Change section sends no messages.

On main, the first three tests fail. On the touchedCells version, the first and fourth tests fail. With this change, all four pass.

Claude also ran these checks:

  • The unit, unit-types, unit-persisters, and unit-synchronizers projects pass in four runs (7,177 tests). On main, 7,173 tests pass. In earlier runs on a busy machine, synchronizers.test.ts failed intermittently on both versions.
  • convergence.fuzz, hub.fuzz, and efficiency pass with FUZZ_RUNS=500.
  • The added lines are covered, and ESLint and Prettier pass on the changed files.
  • The diff applies to beta.

Claude didn't run the projects that need database servers, the end-to-end tests, or the documentation build. The change adds one sentence to the getTransactionMergeableChanges documentation.

🤖 Generated with Claude Code

A merge can move a stamp and leave the content as it was. The new stamp
was kept in memory but not saved, so it was lost at the next restart, and
pulled again from a peer each time. Persisters are now told about it.
Synchronizers, which ask for changes without hashes, are not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

1 participant