Repository navigation
Description
Parent
#363 (Stage 1). Ruling 2026-11-06: option A. Ruling 2026-10-24: a skipped save's contributors merge into the head row.
Benchmark
| Field | Value |
|---|---|
| Metric | W5 version rows per write. W4 failed store attempts per 100 writes. After the #726 Decision 1 deploy, an early failed attempt counts as retried. So W4 = (failed + retried) per 100 writes, as #726 defines it. Cross-check with the Loki P2002 count on both sides. Orphan claim-check keys per run (count and bytes). document_store_outcome_total{outcome="unchanged"} (count). P2002 log lines (count). |
| Before | Local, 2026-11-10, 7a9b6b4c7, Apple M5 Max, Bun 1.4.4, 92 writes per run, held and cold, n = 3 each (#726 Measured comment): W5 1.11 (1.12 in one held run). Orphans 81 to 82 per run, 290,753,468 to 295,026,858 B. W4 0, because jobs did not overlap locally. Local at n = 5, held, cold and mixed, --gap-ms 14000, with a 70 ms round-trip delay on the Postgres proxy (#726 Measured comment, worker concurrency 1): orphan state data per 92-write run 298.6 MB held (295.5 to 302.2), 298.0 MB cold (292.6 to 316.6), 295.0 MB mixed (287.8 to 302.2); 80 to 88 keys a run. W4 0 and W5 1.10 to 1.11 in every mode. This is the before for the claim. Production context, NYC1, 2026-11-09: W4 21.8, W5 1.19 (#726 Step 0 comment). Production, London: #726 before-2, 2026-11-13 (Measured comment): W4 0 (0 failed, 103.6 completed), W5 1.14. The #703 adjacent byte-equal pairs SQL: not measured yet (maintainer, 7 days from 2026-11-11 08:34Z). |
| After | not measured yet |
| Condition | Local: named laptop, Bun 1.4.4, 2 WebSocket + 2 workers in production mode, Redis extension on, both SHAs and the script sha256 recorded. Run the before and the after at worker concurrency 1, as production runs since #737 (2026-11-13 16:06Z). Production: deployed SHA, collab database in London on PostgreSQL 18.6. Each read states whether #737 had shipped. |
| How to run | cd apps/hocuspocus.server && bun --env-file=../../.env.local scripts/bench-content-write.ts --mode <held|cold|mixed> --runs 5 --gap-ms 14000 --pg-delay-ms 70. Neither --pg-delay-ms nor --mode mixed exists yet. #726 owns both: --pg-delay-ms in startPgTlsProxy in scripts/lib/prodModeStack.ts and in bench-content-write.ts, and --mode mixed. They land before the n = 5 before. 70 ms models the NYC1 round trip, so jobs overlap and clashes can show. Production: the #726 after session, plus 7-day failed attempts, fallbacks and the dead-letter queue. |
| Pass rule | Orphans 0 in every run, all modes. unchanged above 0 at 2 replicas. W4 stays 0, as a guard. W5 not higher. The content-safety list passes. The before-2 W4 is 0, so the production W4 claim is dropped. Name the #737 side in each read. Stop rule: if a check fails, set DOC_STORE_SKIP_UNCHANGED=0 as Rollback says. |
| Guard | The content-safety list below. History restores each row with the text it showed. |
| Owner | Agent in the repo: code, tests and the local bench. Maintainer: deploy and production reads. |
| Claim | "Orphan claim-check data per 92-write session: 298 MB -> 0 (local, n = 5, --gap-ms 14000, 70 ms delay)." Quote only that before. The 290 MB figure is the n = 3 run with no gap and no delay, so it is context. |
Why
At 2+ replicas the worker can receive a snapshot equal to the head, mostly end-of-burst twin flushes. Today the worker always inserts version + 1, and each row starts a preview, a change summary, a fan-out and N copies of saved per client.
- The Count version-store outcomes and add an N-replica harness #703 production SQL gives the share of adjacent byte-equal unnamed rows, with its date and window. It replaces an older note of "6 of 60 neighbour rows" on the busiest pad, which had no date, method or window.
- Redis took in 4.55 GB in the 7 days to 2026-11-11, and store snapshots were 3.31 GB of it. So at least 73 % of Redis input is claim-check state (from the Stop a room on 3 replicas from saving a truncated document during a rolling deploy #705 note of 2026-11-11). The orphan fix below cuts part of it.
What to build
New module apps/hocuspocus.server/src/lib/persistSnapshot.ts. It imports Prisma and Yjs only, and opens no Redis socket on import. The worker and the queue-down fallback (saveMergedVersion, hocuspocus.config.ts ~L266-356) both call it. In one transaction:
pg_advisory_xact_lock(hashtext('doc-store:' || documentId))before the head SELECT. Put the lock in one helper. Call it from every head + 1 insert: the worker,saveMergedVersion,appendBackupRow(versionsStore.ts:168) andpersistMigratedSnapshot(hocuspocus.config.ts:52-64). The last two take onlyFOR UPDATEtoday, so under READ COMMITTED they can still hit P2002.- Head
FOR UPDATE, as today, also readingcontributors,commitMessage,triggerandcreatedAt. - Merge raw, then strip, as today.
- Skip rule: if
Buffer.equals(versionData, head.data), the job is an unnamedwebsocketsave with noversionForceKey, and the head is not the first row:UPDATEthe head'scontributorsto a union with no duplicates, in first-seen order;- guard:
AND NOT EXISTS (SELECT 1 FROM "Documents" WHERE "documentId" = $1 AND version > $headVersion); - delete the claim-check key, publish
doc:{id}:savedwith the head version; - skip the change summary, the grid preview and the content-change fan-out.
- Otherwise insert
version + 1, as today.
Head moved: if the guard matches 0 rows, rerun once with the fresh head. If it still misses, insert as today and count outcome="head-moved". Do not throw for a BullMQ retry, because worker.on('failed') feeds the store failure alert.
Never skip: named saves, checkpoints, restores, api, mcp, revert, revert-backup, schema-migration. Nothing skips into a named or machine head.
Put the skip behind DOC_STORE_SKIP_UNCHANGED. It defaults to on after the local run passes.
Add the lock_wait phase to store_job_phase_seconds (#750 step 13), so the lock time shows in production.
Also in this change, from the 2026-11-10 comments:
- Orphan claim-check keys.
enqueueStoreDocumentwrites the claim-check key beforeQueue.add(queue.ts:168). Whenaddreturns an existing job, delete the new key, or write it only when no job holds that id. - The DLQ loss path. A DLQ entry keeps no state above 512 KiB (
DLQ_MAX_INLINE_STATE_BYTES,queue.ts:139). Record inapps/hocuspocus.server/CLAUDE.md§Hocuspocus Server that a dead-lettered last-close save of a large document is lost. Do not raise the cap here. - Both concurrent-job paths in tests. A write to a room that stays loaded returns before its job commits (
liveWrite.ts:310-312). The second store of one write can fall into the next 10 s window ofbuildStoreJobId(queue.ts:161-165).
The local-only saved and access frames, and the subscriber-reconnect counter, moved out of this issue on 2026-11-11. They are a separate sync-path risk. See #758.
Out of scope: a block-fingerprint skip (the 5 zero-diff rows probably carry real toc-id/keyId ops), and a containment check before the merge (its CPU saving is unproven).
Content-safety checks
Run each check locally on a scratch pad that the builder creates and deletes after. Never type into /demo.
- Reload. Type, wait for "synced", reload. The text is there.
- Two browsers. Edit one pad in two browsers. Both end with the same text.
- Offline, then online. Type offline, go online. The server receives the text.
- Fast tab close. Close the tab 50 ms after typing, then reopen. The text is there.
- Replica restart while typing. No text is lost or doubled.
- Production, 7 days after the deploy. Failed store jobs,
document_persist_fallback_totaland the store dead-letter queue stay at 0. - After a skipped save, reload: the head's contributors include the second editor.
- Two replicas co-type for 10 minutes, and History restores each row with the text it showed.
Rollback
Set DOC_STORE_SKIP_UNCHANGED=0 in the source .env on the host and deploy. A skipped save loses no content, because the head already holds those bytes. Never edit only .env.production, because the next deploy overwrites it.
The flag covers only the skip. The advisory lock runs in four writers, and the orphan fix has no flag. If the lock or the orphan fix misbehaves, revert the commit and push a (build): back tip.
Stop rule for the first hour after the deploy: revert if store_job_phase_seconds{phase="lock_wait"} p95 passes 1 s, or if a store job fails.
Done when
-
src/lib/__tests__/persistSnapshot.test.tspins five cases. The contributors union has no duplicates after a skip. Per-block authors (DocumentClientAuthor) stay right. Named, forced and non-websocket jobs always insert. Twin flushes at 3 s, 8 s and 12 s gaps give one row. A lost-update race fails when the guard is removed. Sabotage proves each case. - A revert-backup append races a worker job, and both rows land. Proved by sabotage.
- Both concurrent-job paths above have a test.
-
document_store_outcome_total{outcome="unchanged"}moves in a local 2-replica run. -
orphanStateKeysreads 0 in everybench-content-write.tsrun, all modes. - Every content-safety check passes.
- The before and after are in
Measuredcomments, each naming whether Cap store jobs at 1 per worker replica and raise the worker limit to 2 GiB #737 had shipped. -
apps/hocuspocus.server/CLAUDE.md§Persistence describes the skip rule, and §Hocuspocus Server records the DLQ loss path.
Effort M. Needs the #703 counters first.
Related
#703 (counters and the production SQL). #726 (the before-2 and after sessions, and the shared local n = 5 before). #737 cuts concurrent jobs to 1 per replica, so clashes may fall before this lands. #706 (Stage 3) uses this lock. #758, takes the saved and access frames.
Activity
docs(hocuspocus): record the card, link and import changes
HMarzban commentedon Nov 10, 2026
Production evidence, 2026-11-10. On 2026-11-09, from 18:20Z to 18:47Z, the worker logged 20 P2002 failures on
Documents_documentId_version_key, all for one document of 1 to 4 MiB. An MCP session made 92edit_blockswrites to it in that window. Every retry succeeded, and nothing reached the DLQ.Two code paths created the concurrent jobs. Please cover both in this issue's tests:
apps/hocuspocus.server/src/modules/document-content/infra/liveWrite.ts:310-312). So the next write's job can run beside it.buildStoreJobId(apps/hocuspocus.server/src/lib/queue.ts:161-165). It then becomes a second job with the same bytes.The full record, and the benchmark that measures this fix, are in #726.
HMarzban commentedon Nov 10, 2026
Notes for the builder, 2026-11-10. From the storage-at-scale review; the maintainer agreed ("yes"). Neither note blocks this issue.
enqueueStoreDocumentwrites the claim-check key beforeQueue.add(apps/hocuspocus.server/src/lib/queue.ts:168). When the jobId matches a job that already exists,adddoes nothing, and nothing deletes the new key. It then lives until its 1 h TTL. When this issue reworks the producer, delete the key whenaddreturns an existing job, or write it only when no job holds that id. Low priority.DLQ_MAX_INLINE_STATE_BYTES,queue.ts:139). So if a last-close save of a large document dead-letters, the save is lost, not deferred, because no later debounced save follows. Record this inapps/hocuspocus.server/CLAUDE.md§Hocuspocus Server in the same change. Do not raise the cap here: the inline state would cost Redis memory that cannot be evicted.HMarzban commentedon Nov 10, 2026
Measured locally, 2026-11-10: the size of the orphan claim-check keys. This adds numbers to the orphan note above. They come from the local "before" benchmark on #726: commit
7a9b6b4c7, the maintainer's laptop, and a production-mode stack with the Redis extension on.Each MCP
blockswrite left one orphan key that holds the whole document state. The pad stored 3,587,342 to 3,595,311 B. Each run of 92 writes left 81 to 82 orphan keys, 290,753,468 to 295,026,858 B in total. Each key stays until its 1 h TTL ends. All 6 runs agreed, with the room held open and with it cold.Why one write leaves one orphan:
DirectConnection.transact()andDirectConnection.disconnect()both run the store hooks (@hocuspocus/server3.4.4,dist/hocuspocus-server.esm.js:2097and:2113). Both saves hold the same bytes, so they get one job id.apps/hocuspocus.server/src/lib/queue.ts:496-498).disconnectDelaysleep.enqueueStoreDocumentwrites the key again (queue.ts:169), andQueue.adddrops the job as a duplicate of the finished one. Nothing deletes that key.What it costs:
--maxmemory 512mb --maxmemory-policy noeviction. A first sweep kept the orphans between runs, and Redis filled during its second run. After that every enqueue failed, and each save took the queue-down fallback. That fallback writes Postgres directly with no dedupe, so each write made 2 rows.--maxmemory 3gb --maxmemory-policy volatile-lru(docker-compose.prod.yml:113-114). At that limit Redis evicts keys that carry a TTL, and these keys carry one.A hypothesis, not measured: lowering
disconnectDelay(#726 Decision 2) may remove most orphans. The second save would then arrive while the first job still runs.Next step for this issue: the fix in the note above still applies. Check it with
apps/hocuspocus.server/scripts/bench-content-write.ts, which reportsorphanStateKeysfor each run. After the fix, that count should read 0.test(hocuspocus): add a benchmark for MCP block writes
HMarzban commentedon Nov 11, 2026
Split, 2026-11-11: the frames part moves to #758
From the v2.3.6 milestone review. This issue keeps the skip of a save that adds nothing, and the contributors merge.
Moved out: the "Same change" paragraph.
redis-subscriber.extension.tsandaccessRealtime.tssendsavedand access frames to local connections only, and a subscriber-reconnect counter is added. The Done-when line "savedreaches each client once, andstateless_relay_dropped_total{reason="broadcast-frame"}does not fire" moved with it. See the frames issue, filed with this edit.Why: it is a separate sync-path risk. While a replica's subscriber is down, its clients miss
savedframes. It needs its own check and its own exact metric (saved frames per client per save at 2 replicas).Added to this issue:
appendBackupRowandpersistMigratedSnapshot, which take onlyFOR UPDATEtoday.DOC_STORE_SKIP_UNCHANGED, with a rollback.The London before comes from the #726 before-2 session and the #703 production SQL. Each after-read names whether #737 had shipped.
HMarzban commentedon Nov 12, 2026
Moved to v2.3.7, 2026-11-12 (maintainer ruling). v2.3.6 ships on 2026-11-14 with only finished, measured work, and it waits on an earlier result or a gate read. The before values and the plan in this issue stay as they are.
HMarzban commentedon Nov 13, 2026
Deployed, 2026-11-13: push 1
Push 1 deployed at 13:44Z, as
3d90636a9((build): front back). It carries #750 ind966d5838, with #726 Decision 3: the metrics extension now runs at priority 1001.Confounds in this push. Three commits from the hyperlink track shipped with it:
c9cd2c98a: autolink keeps links intact.f52630eed: addsHyperlinkBase, and changesbun.lock, so the backend image has new dependencies.13cd8ab27: the webapp loadsHyperlinkBasein the pad and the composer. The trigger includedfront, so this webapp change is live.Checks at 14:12Z, all clean. All 8
size_classseeds report on both WebSocket replicas. Failed store jobs 0, dead-letter queues 0, store queue waiting 0, persist fallbacks 0.QUEUE_LOG_LEVELiswarnon both workers.For this issue.
store_job_phase_secondsanddocument_head_bytesnow report in production. A before for this issue can read them from 13:44Z on.HMarzban commentedon Nov 13, 2026
Deployed, 2026-11-13: push 2
Push 2 deployed at 16:06Z, as
eeb1ab727((build): back observability, run 43457071472). It carries #737:e13739ac2(one store job at a time per worker, worker limit 2G,store_job_wait_seconds) andc70850341(alert rulesincident-oom-killandincident-rss-peak). The observability deploy also loaded #750'srealtime-ws-loaded-bytesrule.Confounds in this push. Three commits from the hyperlink track shipped with it:
ead539a38,2a69e2e92and35c0b6892. The trigger had nofront, so no webapp change went live.35c0b6892adds a pull-request-only job to the deploy workflow. It was skipped in this run.Checks at 16:06Z to 16:09Z, all clean.
BULLMQ_CONCURRENCY=1andDB_POOL_SIZE=10, with a memory limit of 2147483648 B. The WebSocket server stays at 1 GiB.want=63 got=63 error_health=0.store_job_wait_secondsreports at 0.MemAvailablestayed at 6.63 GB or more.For this issue. Concurrency 1 also changes how often saves clash. So a version-clash read must name its side of 16:06Z.
feat(hocuspocus): count store outcomes per save
HMarzban commentedon Nov 16, 2026
Review, 2026-11-16 (maintainer approved).
--pg-delay-msand--mode mixed.HMarzban commentedon Nov 17, 2026
Content-safety checklist. The shared checklist lives in release-product §Content-safety checklist. Run it for this issue, plus the extra checks in this body. Record each item as pass or fail in the Measured comment, as §Measured comment format says. The list in this body stays as it is (#762, ruling A).
test(hocuspocus): add a mixed mode and a delay to the write bench
HMarzban commentedon Nov 21, 2026
Built, 2026-11-21 (local, not pushed or deployed)
The whole plan in the body is built, as the maintainer ruled on 2026-11-21. Commits:
5484d35b4(the store lock andpersistSnapshot),d8d748e1b(the skip rule and the orphan fix),ead05698a(tests),ebc3c1986(docs).What it does
pg_advisory_xact_lock(hashtext('doc-store:' || documentId))first: the worker, the queue-down fallback,appendBackupRowandpersistMigratedSnapshot.websocketsave whose merged bytes equal the head keeps the head, when the head is unnamed, not a machine row, and not the first row. Its contributors merge in first-seen order. It publishessavedand starts no summary, preview or fan-out. A guard against a newer row reruns once, then inserts ashead-moved.completedorfailedjob no longer writes its claim-check key. A live job keeps the SET. The key is never deleted after a duplicateadd, because the add may hit a live job.DOC_STORE_SKIP_UNCHANGED(default on) is the rollback.lock_waitjoinsstore_job_phase_seconds.Checks, local
e2e-persist-snapshot.ts: PASSED.e2e-store-pipeline.ts: PASSED. That covers the orphan cases, twin flushes 3, 8 and 12 s apart giving one row with both contributors, and both concurrent-job paths.e2e-versions.tsande2e-content-inject.tsalso pass.websocket-only rule, the guard, the lock in both writers, the orphan check, and a delete-on-duplicate change. Each failed, then passed again with the code restored.unchanged3 in each, orphan keys 0, failed attempts 0, fallbacks 0. A smoke run is not the after.Still owed
bench-content-write.tsnow also prints the save outcomes, after the timed window, so its sha256 changes. The after will name both hashes.(build): backdeploy.HMarzban commentedon Nov 22, 2026
Content-safety checks, 2026-11-22 (local, checks 1 to 5)
Local dev stack (
make dev-local, started 01:53:54Z, after the #704 commits): 1 WS process, 1 worker, webapp on port 3000. Two browsers with separate storage (Default and Incognito profiles), signed out. One scratch pad, deleted after. Each check reads the pad in both browsers and theDocumentsrows in local Postgres.w01…w60andr01…r80, one word every 150 ms. The WS server reloaded twice mid-run (ws_connections_totalreset). Both browsers show each run exactly once, in order, with none missing. Row v6 holds both.Also read: 6 saves, all
inserted. 0 failed store jobs.lock_waitwas timed on each save (19 ms over the first 2).Not run yet: check 7 (contributors after a skipped save) and check 8 (two replicas co-type for 10 minutes). Both need two WS replicas linked through Redis, and check 7 needs two signed-in editors. The dev stack has one WS process, so a twin save never happens there. The worker-level parts are pinned by
e2e-store-pipeline.ts(twin flushes give one row and keep both contributors). Check 6 is the production read.feat(hocuspocus): add the store lock and the persistSnapshot write
feat(hocuspocus): keep the head for a save that adds nothing
test(hocuspocus): pin the skip rule, the store lock and orphan keys
docs(hocuspocus): record the skip rule, the lock and the DLQ loss path
HMarzban commentedon Nov 24, 2026
Measured, 2026-11-24: 2-replica content-safety checks 7 and 8
wsA+wsB) with signed-in users (userA,userB) and production-mode worker onmain, Apple M5 Max laptop, Bun1.4.5. Run2026-11-24T16:25:11Z→16:35:36Z.Notes/release-2.3.7/bench/704-737/check-704-7-8.ts(sha256: f8568bd639174dba4d13ff23baa6ee1831e1f9938f4fff56dde49bdcb67c90e5).Results
headVersionAfterSkip: 3(unchanged);contributorsmerged from[userA]→[userA, userB];unchangedcounter+1; reload shows both edits.600 s,30rounds,60tokens,31original versions; both clients and DB converged equal (missingOrDoubled: 0/0/0); stateless revert to v1 succeeded (backupVersion: 32, converged); 31 of 31 versions restored with0mismatches;inserted: 63,unchanged: 1,failedJobs: 0,retriedJobs: 0,fallbacks: 0,dlqTotal: 0.Remaining to close #704
mixedbench rerun on a quiet machine (Bun 1.4.4,bench/726-after/run-mixed-rerun.sh), then post the shared Measured after.