Skip to content

Run one large snapshot decode at a time in rest-api, which has 512 MiB #754

Open

Description

@HMarzban

Summary

rest-api decodes whole pad heads and version rows with no size bound, inside a 512 MiB limit. One decode of a 12.5 MB head adds about 173 MiB in a local probe. On the 2026-11-09 peak, that alone reaches the limit. An out-of-memory kill drops every in-flight export, MCP call and pad read on that replica. Any signed-in reader can start an export.

This issue lets each rest-api process run one decode above 4 MiB at a time. A second large decode waits up to 10 s, then gets a 503 with Retry-After: 10. It also measures the real decode peak of the largest head, to decide whether the limit must rise to 768M.

Benchmark

Field Value
Metric Peak REST RSS for two large exports at once (/usr/bin/time -l maximum resident set size, MiB, exact per run). HTTP statuses of both exports. Wall time of one export (s). large_decode_total by outcome (count). Production rest-api RSS 7-day max (bytes). rest-api RestartCount (count).
Before Gate removed, local: not measured yet: agent in the repo, before step 4, in a Measured comment. Context: local probe 2026-11-08, Bun 1.4.4, a synthetic 12.5 MB head: one decode +173 MiB, two +321 MiB (lower bounds). Production, 2026-11-11: rest-api RSS 7-day max 356,745,216 B (Before reads). Heads and version rows above 4 MiB after the #738 backfill (step 1): not measured yet: maintainer. Real decode peak on the host (step 1): not measured yet: maintainer, only if that count is above 0.
After not measured yet
Condition make dev-local, named laptop, Bun 1.4.4, the #738 step 6 seed (a synthetic 12.5 MB head, fixed seed), both SHAs recorded. Restart the REST process before every run. Production: deployed SHA, 512 MiB limit, 2 replicas.
How to run Run the REST process under /usr/bin/time -l per run, and read its maximum resident set size. Fire two exports at once with the curl loop below. 5 runs per side.
Pass rule Peak at least 100 MiB lower than the gate-removed before, median of 5. Both exports 200, and one shows outcome="waited". Production: rest-api RSS 7-day max does not rise; large_decode_total{outcome="refused"} 1 or fewer per day over 7 days; RestartCount unchanged in 7 days. Stop rule: if one export of the 12.5 MB head takes more than 8 s, raise LARGE_DECODE_WAIT_MS before shipping.
Guard Exports of a large and a small pad are byte-equal to exports from before the change. Two MCP version reads of a large pad at once: the second gets a retryable answer, not a raw 503. Out-of-memory restarts of rest-api stay at 0 in 7 days (RestartCount unchanged).
Owner Agent in the repo: code and local runs. Maintainer: step 1, the gate decision (Decision 2), deploy and production reads.
Claim Ops: "Peak REST memory with two large exports at once: <x> MiB -> <y> MiB (local, n = 5)." The restart count is a guard, not a gain: its before is already 0.

Before reads

Production, read-only, 2026-11-11.

Read Value Source
rest-api limit 536,870,912 B (512 MiB), 2 replicas docker inspect; docker-compose.prod.yml:283
rest-api RSS, 7-day max 356,745,216 B (340 MiB), on 2026-11-09 max(max_over_time(process_resident_memory_bytes{job="rest-api"}[7d]))
rest-api RSS, daily max, 11-04 to 11-10 286, 278, 293, 337, 317, 357, 315 MB same metric, [1d] windows
rest-api container working set, 7-day max 284,864,512 B container_memory_working_set_bytes{name=~"docsplus-rest-api-.+"}
Largest head 12,518,586 B; 3 heads above 4 MiB SQL, aggregates only, 12:15Z
MCP calls, 7 days 1,656 http_requests_total{job="rest-api",route="/api/mcp"}
Export, version read and diff calls, 14 days export has no series; diff 0 http_requests_total{job="rest-api"} by route
  • Local probe (2026-11-08, Bun 1.4.4, a synthetic 12.5 MB head): one decode added 173 MiB, and two decodes added 321 MiB. These are lower bounds.
  • 340 MiB plus 173 MiB is 513 MiB, at the limit. Two decodes at once pass it at any recent daily peak.
  • Exports are rare today, so the risk is a burst, not steady traffic. An MCP read_document on a cold room decodes in rest-api too.

Decode sites at 0b302b222 (paths under apps/hocuspocus.server/src):

Path Who can call it Decode
Export (docx, md, odt) any signed-in reader (deny(c, meta, 'read'), modules/document-conversion/http/controller.ts:128) head, :136
Duplicate requireUser (api/routers/documents.router.ts:100) head, only if it holds a media route, api/services/documents.service.ts:879
MCP read_document, cold room MCP bearer head, modules/document-content/infra/contentClient.ts:141
Content read service role head, modules/document-content/http/controller.ts:132
Version read service role one row, modules/document-versions/http/controller.ts:148
Version diff service role two rows, modules/document-versions/http/controller.ts:245

The hovercard read is already gated at 1 MiB. The owner-list preview fill decodes only heads with a SQL NULL preview, and the worker writes a preview on every save.

What to change

  1. Maintainer, after the Clear y-tiptap position-migration maps on the server, so big pads load faster #738 backfill. First read, with aggregate SQL, the count of heads and of version rows above 4 MiB. If both counts are 0, the gate can never fire: close this issue with that read. Otherwise, once, at a quiet hour, measure the real decode peak of the largest head in a throwaway container. It prints numbers only:

    cat > /tmp/decode-peak.ts <<'EOF'
    import { Worker, isMainThread, parentPort } from 'node:worker_threads'
    if (!isMainThread) {
      // The decode blocks the main thread, so RSS is sampled here, every 50 ms.
      let max = 0
      const t = setInterval(() => { max = Math.max(max, process.memoryUsage().rss) }, 50)
      parentPort!.once('message', () => { clearInterval(t); parentPort!.postMessage(max) })
    } else {
      const { prisma } = await import('./src/lib/prisma')
      const { ydocToPmJson } = await import('./src/lib/nested-flat-migration')
      const [h] = await prisma.$queryRaw<{ data: Uint8Array }[]>`
        SELECT d.data FROM "Documents" d
        JOIN (SELECT "documentId", max(version) v FROM "Documents" GROUP BY 1) m
          ON m."documentId" = d."documentId" AND m.v = d.version
        ORDER BY octet_length(d.data) DESC LIMIT 1`
      const sampler = new Worker(new URL(import.meta.url))
      await new Promise((r) => setTimeout(r, 200))
      const rss0 = process.memoryUsage().rss
      const r = ydocToPmJson(Buffer.from(h.data))
      const sampledPeak = await new Promise<number>((res) => { sampler.once('message', res); sampler.postMessage('stop') })
      await sampler.terminate()
      const peak = process.resourceUsage().maxRSS * 1024 // maxRSS is in KiB
      if (peak === 0) throw new Error('maxRSS read 0, abort')
      console.log(JSON.stringify({ bytes: h.data.length, ok: r.ok, rssBefore: rss0, peakRss: peak, sampledPeakRss: sampledPeak, addedBytes: peak - rss0 }))
      await prisma.$disconnect()
    }
    EOF
    docker run --rm --memory 1g --network <app network> --env-file <production env file> \
      -v /tmp/decode-peak.ts:/app/apps/hocuspocus.server/decode-peak.ts:ro -w /app/apps/hocuspocus.server \
      --entrypoint bun docsplus-rest-api:<deployed tag> decode-peak.ts
    rm /tmp/decode-peak.ts

    Run it 5 times and record the median and range of addedBytes. Post the numbers here. They settle Decision 1.

    The script must print maxRSS beside a 50 ms process.memoryUsage().rss sample, and abort if maxRSS reads 0. The script above does both. The sampler runs in a worker thread, because the synchronous decode would block a timer on the main thread. Agent in the repo: run it once locally on the Clear y-tiptap position-migration maps on the server, so big pads load faster #738 step 6 seed before the maintainer runs it.
    Steps 3-11 wait on Decision 2.

  2. Done: Bound DOCX import memory: exact zip count, per-part Word text cap, one import at a time #577 landed lib/largeDecodeGate.ts in 3c4f14764, and Import uses it (modules/document-conversion/http/controller.ts:289). Reuse it as it is. Keep the waitMs parameter, which Bound DOCX import memory: exact zip count, per-part Word text cap, one import at a time #577 calls with 0. The module has no imports. Export LARGE_DECODE_BYTES = 4 * 1024 * 1024 and LARGE_DECODE_WAIT_MS = 10_000. Export acquireLargeDecode(bytes: number, waitMs = LARGE_DECODE_WAIT_MS): Promise<(() => void) | null>:

    • below the threshold, it returns a no-op release at once;
    • above it, it takes the one slot in FIFO order, or returns null after waitMs;
    • release is idempotent.

    JSDoc in at most 4 lines: one large decode per process, because rest-api has 512 MiB.

  3. Agent in the repo. In lib/metrics.ts, add large_decode_total{route, outcome} (outcome run, waited or refused). Use a metric, not a log line: rest-api runs at LOG_LEVEL=error, so an info or warn line never reaches Loki.

  4. Agent in the repo. Gate the export: in modules/document-conversion/http/controller.ts, call acquireLargeDecode(head.data.byteLength) before ydocToPmJson(head.data) (:136). On null, run c.header('Retry-After', '10') and return fail(c, 503, 'SERVICE_UNAVAILABLE', 'A large document is being read. Try again shortly.'). Call release() in a finally, after renderExport returns (:155).

  5. Agent in the repo. Gate the duplicate: in api/services/documents.service.ts:879, wrap rehostMediaUrls the same way. On null, throw new AppError('A large document is being read. Try again shortly.', 503, 'SERVICE_UNAVAILABLE') (lib/errors.ts).

  6. Agent in the repo. Gate the cold content read in modules/document-content/infra/contentClient.ts:141. On null, return { status: 'unavailable' }, the existing arm (:147).

  7. Agent in the repo. Gate the content read (modules/document-content/http/controller.ts:132), the version read (modules/document-versions/http/controller.ts:148) and the diff (:245). For the diff, acquire once with the larger of the two rows. On null, answer as in step 4. MCP calls the version read and the diff, so the MCP tool must map that 503 to a retryable answer. The agent names the tool file that maps it, starting from modules/mcp/tools/documentTools.ts.

  8. Agent in the repo. Add lib/__tests__/largeDecodeGate.test.ts: FIFO order, a timeout returns null, and release is idempotent. This is dense branching, which AGENTS.md §Test Policy case (c) allows. Prove each case by sabotage: it fails when its guarded line is removed.

  9. Agent in the repo. In apps/webapp/src/api/documents/conversionErrors.ts, add 503: 'This document is busy. Try again in a few seconds.' to BY_STATUS (:15-22). Today a 503 shows "Something went wrong on our end".

  10. Agent in the repo. Through the tech-writer skill, add one bullet to apps/hocuspocus.server/CLAUDE.md §Runtime limits: the gate, its 4 MiB threshold and 10 s wait, and the metric. Gates: bun run --filter @docs.plus/hocuspocus typecheck, bun run --filter @docs.plus/hocuspocus test and bun run --filter @docs.plus/webapp typecheck. Stop at a review checkpoint.

  11. Maintainer. Commit through the commit-review skill and push with a (build): back front tip.

Local method

Local, make dev-local, on a synthetic 12.5 MB head with no user data. Use the #738 step 6 seed, the one 12.5 MB seed in the repo. It is built from a fixed seed: 400 paragraphs and a large __tiptap_position_migrations:root:default map from 56 clients. So the after reuses the same bytes. Then insert one documentMetadata row and one documents row.

Restart the REST process before every run, gated and ungated. Bun does not return freed memory, so a warm process measures heap reuse. Read the exact peak from /usr/bin/time -l. Fire the two exports with this loop:

for i in 1 2; do curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $SUPABASE_SERVICE_ROLE_KEY" "http://localhost:4000/api/documents/<local pad id>/export?format=md" & done; wait

Use the local service-role key from .env.local only. The export route checks deny(c, meta, 'read'), so check once that it accepts the service-role key. If it refuses, use a local signed-in user's token from make dev-local.

Measure Before (gate removed) After (pass) n
Peak REST RSS, two exports at once (/usr/bin/time -l) record it at least 100 MiB lower than before, median of 5 n = 5 each, median and range
HTTP status of both exports 200, 200 200, 200, and one shows outcome="waited" n = 5
Wall time of one export of the 12.5 MB head record it at most 8 s, or raise LARGE_DECODE_WAIT_MS before shipping n = 5
Production rest-api RSS, 7-day max 356,745,216 B no rise; large_decode_total{outcome="refused"} 1 or fewer per day over 7 days 7 days after the deploy

Checks

UX.

  • One export of a large pad runs as fast as today: the gate is free when no other large decode runs.
  • A second large export waits, then downloads. It does not fail. This holds only if one export takes under 10 s, which the wall-time row measures.
  • Past 10 s, the person sees "This document is busy. Try again in a few seconds." A retry works.
  • Small pads (under 4 MiB) never wait.
  • An MCP read_document that meets a busy gate gets the existing "unavailable" answer, not an error from a killed process.
  • Two MCP version reads of a large pad at once: the second gets a retryable answer, not a raw 503.

Content safety. No save path changes, and no stored byte changes. Still check: export a large pad and a small pad, and diff the files against exports from before the change. They are equal.

Config. docker inspect shows the rest-api limit unchanged at 536870912, unless Decision 1 raises it.

Rollback

Revert the commit and push a (build): back front tip. The gate acts only when two large decodes meet on one replica, so a revert changes nothing else.

Acceptance criteria

  • The gate test passes, and each case fails when its guarded line is removed.
  • The local benchmark passes, with the n = 5 numbers in a Measured comment.
  • The post-Clear y-tiptap position-migration maps on the server, so big pads load faster #738 count of heads and version rows above 4 MiB is posted. If it is above 0, the step 1 decode-peak numbers are posted, and Decision 2 follows them.
  • The gate-removed before is in a Measured comment before step 4.
  • 7 days after the deploy, large_decode_total shows the gate ran. docker inspect RestartCount on both rest-api containers is unchanged, and dmesg shows no rest-api out-of-memory kill. large_decode_total{outcome="refused"} is 1 or fewer per day.

Decisions

  1. Raise the rest-api limit from 512M to 768M (docker-compose.prod.yml:283)? Recommended: only if step 1 shows one real decode of the largest head above 150 MiB. Then the 340 MiB peak plus one decode passes 90 % of 512 MiB, and the gate cannot help. rest-api runs 2 replicas, so the raise reserves 512 MiB more in all. The host has 16,789,094,400 B, and its 7-day minimum of available memory was 5,623,955,456 B. If raised, move the rest-api arm of the RSS alert on Cap store jobs at 1 per worker replica and raise the worker limit to 2 GiB #737 to 80 % of 768 MiB. Owner: maintainer.
  2. Build the gate at all? Owner: maintainer, after the post-Clear y-tiptap position-migration maps on the server, so big pads load faster #738 count read and, if it is above 0, step 1. Steps 3-11 wait on it. Clear y-tiptap position-migration maps on the server, so big pads load faster #738 cut a synthetic head by 66 %, so the large heads may fall below the 4 MiB threshold. If the gate is dropped, close this issue with the count read or the decode-peak numbers. The Bound DOCX import memory: exact zip count, per-part Word text cap, one import at a time #577 module stays either way.

Related

#737 (RSS alert thresholds name this limit). #738 and #701 shrink heads; after them, mostly old version rows stay large. Step 1 runs only after #738. #577 (Word import peak; #724 folded into it; owns lib/largeDecodeGate.ts). #726 (MCP writes on large pads).

Activity

  1. added this to the v2.3.6 milestone on Nov 11, 2026
  2. added
    bug
    Performance
    on Nov 11, 2026
  3. modified the milestones: v2.3.6, v2.3.7 on Nov 12, 2026
  4. 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 reruns after #738, which moved too. The before values and the plan in this issue stay as they are.

  5. HMarzban commented on Nov 16, 2026

    @HMarzban
    CollaboratorAuthor

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

  6. modified the milestones: v2.3.7, v2.3.8 on Nov 24, 2026
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

    Performancebug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions