Skip to content

Skip a save that adds nothing, and merge its contributors #704

Open

Description

@HMarzban

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.

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:

  1. 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) and persistMigratedSnapshot (hocuspocus.config.ts:52-64). The last two take only FOR UPDATE today, so under READ COMMITTED they can still hit P2002.
  2. Head FOR UPDATE, as today, also reading contributors, commitMessage, trigger and createdAt.
  3. Merge raw, then strip, as today.
  4. Skip rule: if Buffer.equals(versionData, head.data), the job is an unnamed websocket save with no versionForceKey, and the head is not the first row:
    • UPDATE the head's contributors to 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}:saved with the head version;
    • skip the change summary, the grid preview and the content-change fan-out.
  5. 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. enqueueStoreDocument writes the claim-check key before Queue.add (queue.ts:168). When add returns 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 in apps/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 of buildStoreJobId (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.

  1. Reload. Type, wait for "synced", reload. The text is there.
  2. Two browsers. Edit one pad in two browsers. Both end with the same text.
  3. Offline, then online. Type offline, go online. The server receives the text.
  4. Fast tab close. Close the tab 50 ms after typing, then reopen. The text is there.
  5. Replica restart while typing. No text is lost or doubled.
  6. Production, 7 days after the deploy. Failed store jobs, document_persist_fallback_total and the store dead-letter queue stay at 0.
  7. After a skipped save, reload: the head's contributors include the second editor.
  8. 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.ts pins 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.
  • orphanStateKeys reads 0 in every bench-content-write.ts run, all modes.
  • Every content-safety check passes.
  • The before and after are in Measured comments, 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

  1. added this to the v2.3.0 milestone on Nov 6, 2026
  2. added
    Performance
    on Nov 6, 2026
  3. modified the milestones: v2.3.0, v2.3.6 on Nov 9, 2026
  4. HMarzban commented on Nov 10, 2026

    @HMarzban
    CollaboratorAuthor

    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 92 edit_blocks writes 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:

    • A write to a room that stays loaded returns before its job commits (apps/hocuspocus.server/src/modules/document-content/infra/liveWrite.ts:310-312). So the next write's job can run beside it.
    • The second store of one write can fall into the next 10 s window of 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.

  5. HMarzban commented on Nov 10, 2026

    @HMarzban
    CollaboratorAuthor

    Notes for the builder, 2026-11-10. From the storage-at-scale review; the maintainer agreed ("yes"). Neither note blocks this issue.

    • Orphan claim-check keys. enqueueStoreDocument writes the claim-check key before Queue.add (apps/hocuspocus.server/src/lib/queue.ts:168). When the jobId matches a job that already exists, add does nothing, and nothing deletes the new key. It then lives until its 1 h TTL. When this issue reworks the producer, delete the key when add returns an existing job, or write it only when no job holds that id. Low priority.
    • A known loss path, to record. A DLQ entry keeps no state above 512 KiB (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 in apps/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.
  6. HMarzban commented on Nov 10, 2026

    @HMarzban
    CollaboratorAuthor

    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 blocks write 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:

    1. DirectConnection.transact() and DirectConnection.disconnect() both run the store hooks (@hocuspocus/server 3.4.4, dist/hocuspocus-server.esm.js:2097 and :2113). Both saves hold the same bytes, so they get one job id.
    2. The first job finishes in 0.15 to 0.17 s, and the worker deletes its key (apps/hocuspocus.server/src/lib/queue.ts:496-498).
    3. The second save comes about 1 s later, after the Redis extension's disconnectDelay sleep. enqueueStoreDocument writes the key again (queue.ts:169), and Queue.add drops the job as a duplicate of the finished one. Nothing deletes that key.
    4. In the other 10 to 11 writes of each run, the two saves fell into different 10 s windows. Those writes made two jobs and two rows, and no orphan. This is inferred from the row and key counts. The job ids were not read.

    What it costs:

    • Local Redis runs --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.
    • Production runs --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.
    • The 2026-11-09 session made 92.4 writes on a document of 1 to 4 MiB, so it left at most about 90 orphans. The real count may be far lower. A second save that arrives while its first job still runs leaves no orphan. The store-job p95 that night was 2.4 to 4.5 s. Step 0 on Cut MCP write time on large pads and stop its four false alerts #726 now reads production Redis memory for that window.

    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 reports orphanStateKeys for each run. After the fix, that count should read 0.

  7. HMarzban commented on Nov 11, 2026

    @HMarzban
    CollaboratorAuthor

    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.ts and accessRealtime.ts send saved and access frames to local connections only, and a subscriber-reconnect counter is added. The Done-when line "saved reaches each client once, and stateless_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 saved frames. It needs its own check and its own exact metric (saved frames per client per save at 2 replicas).

    Added to this issue:

    • The advisory lock goes in one helper, called from every head + 1 insert. That includes appendBackupRow and persistMigratedSnapshot, which take only FOR UPDATE today.
    • What to build now holds three items from the 2026-11-10 comments: the orphan claim-check fix, the DLQ 512 KiB note and the two concurrent-job test paths.
    • The skip sits behind DOC_STORE_SKIP_UNCHANGED, with a rollback.
    • The standard content-safety list and a Benchmark section.
    • Effort moves from S to M.

    The London before comes from the #726 before-2 session and the #703 production SQL. Each after-read names whether #737 had shipped.

  8. modified the milestones: v2.3.6, v2.3.7 on Nov 12, 2026
  9. HMarzban commented on Nov 12, 2026

    @HMarzban
    CollaboratorAuthor

    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.

  10. HMarzban commented on Nov 13, 2026

    @HMarzban
    CollaboratorAuthor

    Deployed, 2026-11-13: push 1

    Push 1 deployed at 13:44Z, as 3d90636a9 ((build): front back). It carries #750 in d966d5838, 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: adds HyperlinkBase, and changes bun.lock, so the backend image has new dependencies.
    • 13cd8ab27: the webapp loads HyperlinkBase in the pad and the composer. The trigger included front, so this webapp change is live.

    Checks at 14:12Z, all clean. All 8 size_class seeds report on both WebSocket replicas. Failed store jobs 0, dead-letter queues 0, store queue waiting 0, persist fallbacks 0. QUEUE_LOG_LEVEL is warn on both workers.

    For this issue. store_job_phase_seconds and document_head_bytes now report in production. A before for this issue can read them from 13:44Z on.

  11. HMarzban commented on Nov 13, 2026

    @HMarzban
    CollaboratorAuthor

    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) and c70850341 (alert rules incident-oom-kill and incident-rss-peak). The observability deploy also loaded #750's realtime-ws-loaded-bytes rule.

    Confounds in this push. Three commits from the hyperlink track shipped with it: ead539a38, 2a69e2e92 and 35c0b6892. The trigger had no front, so no webapp change went live. 35c0b6892 adds a pull-request-only job to the deploy workflow. It was skipped in this run.

    Checks at 16:06Z to 16:09Z, all clean.

    • Both new workers read BULLMQ_CONCURRENCY=1 and DB_POOL_SIZE=10, with a memory limit of 2147483648 B. The WebSocket server stays at 1 GiB.
    • The Fail the observability deploy when Grafana or its provisioned rules do not load #753 Verify read want=63 got=63 error_health=0.
    • store_job_wait_seconds reports at 0.
    • During the worker restart: failed store jobs 0, store rejections 0 and persist fallbacks 0. Dead-letter queues 0, store queue waiting 0 and kernel OOM kills 0. Host MemAvailable stayed at 6.63 GB or more.
    • The 2 h soak after push 1 was clean too: 0 failed store jobs and 0 fallbacks, from 13:46Z to 15:44Z.

    For this issue. Concurrency 1 also changes how often saves clash. So a version-clash read must name its side of 16:06Z.

  12. HMarzban commented on Nov 16, 2026

    @HMarzban
    CollaboratorAuthor

    Review, 2026-11-16 (maintainer approved).

  13. HMarzban commented on Nov 17, 2026

    @HMarzban
    CollaboratorAuthor

    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).

  14. HMarzban commented on Nov 21, 2026

    @HMarzban
    CollaboratorAuthor

    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 and persistSnapshot), d8d748e1b (the skip rule and the orphan fix), ead05698a (tests), ebc3c1986 (docs).

    What it does

    • Every head + 1 writer takes pg_advisory_xact_lock(hashtext('doc-store:' || documentId)) first: the worker, the queue-down fallback, appendBackupRow and persistMigratedSnapshot.
    • An unnamed, unforced websocket save 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 publishes saved and starts no summary, preview or fan-out. A guard against a newer row reruns once, then inserts as head-moved.
    • Orphan keys: a save whose job id names a completed or failed job no longer writes its claim-check key. A live job keeps the SET. The key is never deleted after a duplicate add, because the add may hit a live job.
    • DOC_STORE_SKIP_UNCHANGED (default on) is the rollback. lock_wait joins store_job_phase_seconds.

    Checks, local

    • Typecheck, 506 files. Backend unit tests: 1275 pass, 0 fail.
    • 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.ts and e2e-content-inject.ts also pass.
    • Each check was proved by breaking its rule: the union, the byte compare, the 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.
    • Bench smoke runs at 2 replicas (cold, 30 writes; held, 20 writes): unchanged 3 in each, orphan keys 0, failed attempts 0, fallbacks 0. A smoke run is not the after.

    Still owed

    • The content-safety checks 1 to 5, 7 and 8 (browser and replica restart).
    • The local n = 5 after, all three modes, on Bun 1.4.4 like the before. bench-content-write.ts now also prints the save outcomes, after the timed window, so its sha256 changes. The after will name both hashes.
    • Check 6: the 7-day production read after a (build): back deploy.
  15. HMarzban commented on Nov 22, 2026

    @HMarzban
    CollaboratorAuthor

    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 the Documents rows in local Postgres.

    # Check Result
    1 Reload Pass. The typed line came back after a reload. The clean Incognito browser showed it from the server, and row v1 holds it.
    2 Two browsers Pass. Each browser typed one line. Both show all three lines, and row v2 holds both.
    3 Offline, then online Pass. Browser A's WebSocket dropped every outgoing message (5 dropped) while it typed. The server and browser B did not get the line. After the socket came back and reconnected, row v3 and browser B hold it.
    4 Fast tab close Pass. The text was inserted, then the tab closed at once. The tool gap was under 4 s, not exactly 50 ms. Row v4 holds the text, and a reopened tab shows it.
    5 Restart while typing Pass. Browser A typed w01…w60 and r01…r80, one word every 150 ms. The WS server reloaded twice mid-run (ws_connections_total reset). 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_wait was 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.

  16. HMarzban commented on Nov 24, 2026

    @HMarzban
    CollaboratorAuthor

    Measured, 2026-11-24: 2-replica content-safety checks 7 and 8

    • Setup: Local 2-replica WebSocket stack (wsA + wsB) with signed-in users (userA, userB) and production-mode worker on main, Apple M5 Max laptop, Bun 1.4.5. Run 2026-11-24T16:25:11Z → 16:35:36Z.
    • Script: Notes/release-2.3.7/bench/704-737/check-704-7-8.ts (sha256: f8568bd639174dba4d13ff23baa6ee1831e1f9938f4fff56dde49bdcb67c90e5).

    Results

    Check Result Details
    Check 7 (no-op save merges contributors across 2 WS replicas) PASS headVersionAfterSkip: 3 (unchanged); contributors merged from [userA] → [userA, userB]; unchanged counter +1; reload shows both edits.
    Check 8 (10-minute 2-replica co-typing + full version restore) PASS 600 s, 30 rounds, 60 tokens, 31 original versions; both clients and DB converged equal (missingOrDoubled: 0/0/0); stateless revert to v1 succeeded (backupVersion: 32, converged); 31 of 31 versions restored with 0 mismatches; inserted: 63, unchanged: 1, failedJobs: 0, retriedJobs: 0, fallbacks: 0, dlqTotal: 0.

    Remaining to close #704

    • Overnight mixed bench rerun on a quiet machine (Bun 1.4.4, bench/726-after/run-mixed-rerun.sh), then post the shared Measured after.
    • Production 7-day Check 6 read on or after 2026-11-30 07:49Z.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Performance

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions