Skip to content

fix(memory): enforce token bounds in oversized source chunks - #406

Open
Afloat16 wants to merge 1 commit into
simplexai-labs:mainfrom
Afloat16:afloat/memory-chunk-token-bound
Open

Afloat16 wants to merge 1 commit into
simplexai-labs:mainfrom
Afloat16:afloat/memory-chunk-token-bound

Conversation

@Afloat16

@Afloat16 Afloat16 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

What and why

Enforce both the 3,000 UTF-16-character and 500 search-token bounds when splitting oversized source paragraphs. Dense short-word and Han text must not exceed the token limit merely because it fits the character limit. Source offsets, Unicode character boundaries and deterministic chunk IDs remain intact.

Cap overlap at the smaller of 200 characters and half of the current chunk. NFKC normalization can expand a short source span into many tokens; proportional progress prevents that case from producing nearly identical chunks one character apart.

How it was verified

Comparison base: 77abdcb37f779f9c9d2de89fa245efa88d3f6584. Linux, Node 26.5.0 and pnpm 11.7.0. The single published commit is e19b0e38e8a1d910c51d627575b5edb0575d89fb.

  • The original short-word, Han-bigram and astral-Han regressions fail on the comparison base; the ordinary-paragraph control passes.
  • Two additional NFKC-expansion regressions fail on the previous head d3b12f2b: 600 Arabic ligatures and 600 squared Han words produced 72,210 and 59,500 stored characters. Both now satisfy the bound of twice the input length, while retaining token limits, exact slices, continuous coverage, whole Unicode characters and deterministic results.
  • All 60 tests across four complete related files pass: chunk-token-bound, raw-query-reliability, chunk-index and raw-knowledge-query.
  • The existing output-budget fixture uses three-byte accented Latin letters so it still exercises byte truncation under the token bound. Its character/byte counts and all budget, section, continuation and surrogate assertions are retained.
  • The repository's changed-file check passes Prettier, ESLint and the English-only rule; git diff --check passes.

Complete owning-package gate

pnpm --filter @linger/node-services check exits 0 on the published tree 44316a227c03a51925509e72e5f6f66ac8af3c19: feature-catalog verification, TypeScript checking and lint pass; Vitest reports 269 files passed, 8 skipped; 2,717 tests passed, 51 skipped. Dependencies were installed with the frozen lockfile in an isolated worktree. The normal suite configuration and a task-local temporary directory were used; no timeout or skip settings changed.

  • Focused tests for the changed behavior
  • make check BASE=<target-ref> or all affected fast checks
  • No contract regeneration required

Boundary

The owning behavior documentation is updated. There are no wire-contract or dependency changes. The original fix, fixture adaptation and overlap correction are combined into one validated commit on the original comparison base. Integration with current main follows the merge queue described in CONTRIBUTING.md. Live-service/E2E results are not claimed.

@Afloat16
Afloat16 marked this pull request as ready for review November 25, 2026 06:09

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes (1 P1)

Scope: base main, merge base 77abdcb3; 2 commits, 4 files reviewed at d3b12f2b. Loaded coderbook (sections 2, 3, 5), ponytail-review (sections 1–3) and karpathy-guidelines (sections 2–3). Ran in a separate session.

Findings

P1

apps/node-services/src/memory/search/chunks.ts:175: the new token bound can make the oversized-block loop advance by one character per chunk, so chunk count and CPU blow up

The step after each chunk is still start = Math.max(start + 1, end - OVERSIZED_BLOCK_OVERLAP_CHARS) with a fixed 200-character overlap. Before this PR every chunk was 3,000 characters, so each step moved forward about 2,800 characters. Now the binary search can make a chunk shorter than 200 UTF-16 characters. When that happens, end - 200 < start + 1 and the loop moves forward by exactly one character per chunk.

That happens with real input because tokenizeSearchText applies NFKC first (src/bm25.ts:51-52), so one source character can turn into several tokens. For example, U+FDFA expands to four Arabic words, and U+337F (the squared "corporation" sign) expands to four Han characters, which give about four bigram tokens. Their chunks are 166 and 125 characters long. I extracted base and PR chunkSource into a temp dir and ran both:

input base chunks / ms PR chunks / stored chars / ms
1,000 × U+FDFA 1 / 2 835 / 138,610 / 2,487
2,000 × U+FDFA 1 / 3 1,835 / 304,610 / 7,045
2,000 × U+337F 1 / 3 1,876 / 234,500 / 2,421
10,000 Han chars (control) 4 / 13 33 / 16,400 / 45

20,000 × U+FDFA did not finish within 120 s. chunkSource runs synchronously on the event loop of the shared node-services process (Agent, Memory and LLM Wiki together). It is called:

  • in the periodic raw_chunk_sync (src/memory/main.ts:101-106 → chunk-index.ts:692), on every source each interval;
  • at query time (search/raw-query.ts:136,178, knowledge-query.ts:502, session-fact-index.ts:298).

A single user-supplied source up to MAX_SOURCE_BYTES (5 MB, search/source-store.ts:93) holding one paragraph of such characters would produce roughly a million near-duplicate chunk rows and block the process for a very long time. It would do so again on every sync.

Fix: keep the overlap below the chunk length so each step makes proportional progress, e.g. start = Math.max(start + 1, end - Math.min(OVERSIZED_BLOCK_OVERLAP_CHARS, Math.floor((end - start) / 2))), keeping the existing low-surrogate adjustment. Then add a case such as "ﷺ".repeat(2000) to chunk-token-bound.test.ts that asserts a bounded chunk count, e.g. chunks.length <= Math.ceil(content.length / ((chunk length) / 2)) + 1, or simply < 50.

Verified as fine

  • The binary search always returns a prefix within the token bound: low starts at start + 1 (one character never comes near 500 tokens) and only moves to a middle that passed the <= MAX_CHUNK_TOKENS check (chunks.ts:149-161). Moving back from a high surrogate only shrinks the prefix (chunks.ts:164-170).
  • Offsets stay exact and IDs stay deterministic: ranges are still slices of the unchanged source and id is still chunk-<digest>-<start> (chunks.ts:85-95).
  • Already-indexed dense sources get rebuilt even though INDEX_PROFILE was not bumped. #indexChunkSource re-chunks on every sync and rewrites when chunk_count !== prepared.length (chunk-index.ts:715-722). A block that now hits the token bound always yields more chunks than before, and the periodic raw_chunk_sync visits every raw source (chunk-index.ts:565-575, main.ts:101-106).
  • The fixture change in raw-knowledge-query.test.ts:1217-1221 keeps the code points 3-byte UTF-8 (U+1E00–U+1E7F) and single-UTF-16-unit. The budget, truncation and surrogate assertions still mean the same thing.
  • README is updated (src/memory/README.md:24-26). No contract, env or dependency changes, no CJK in added lines or commit messages, no cross-app imports.

Process notes

  • The branch is 337 commits behind main (merge state BLOCKED) and needs a rebase.
  • d3b12f2b test(memory): keep output-budget fixtures within token bounds only repairs a test that 4d6554d6 broke. Since main takes rebase merges, 4d6554d6 would land with a failing test; squash the two commits.

CI

The checks that ran passed: changes, repository-gate, check (web); the rest were skipped. CI does not run the node-services Vitest suite, so the PR's focused tests and pnpm --filter @linger/node-services check are covered only by the author's local run. I did not re-run the suite. My only run was a standalone base-vs-PR chunkSource comparison in a temp dir (results above).

Automated review by Claude Code


Automated review of d3b12f2 by Claude Code.

@Afloat16
Afloat16 force-pushed the afloat/memory-chunk-token-bound branch from d3b12f2 to e19b0e3 Compare November 25, 2026 06:58
@Afloat16

Copy link
Copy Markdown
Contributor Author

Addressed the P1 in review 6052725861 in e19b0e38e8a1d910c51d627575b5edb0575d89fb.

Overlap is now min(200, floor(chunkLength / 2)), retaining the existing surrogate-boundary adjustment. Two public-behavior regressions for NFKC-expanding Arabic ligatures and squared Han words failed on the previous head and now pass. They check bounded stored text, token limits, exact source ranges, continuous coverage, complete Unicode characters and deterministic output.

All four related test files pass (60 tests), and the complete Node Services gate passes on the published tree: 269 files / 2,717 tests, with the existing 8 files / 51 tests skipped. Typecheck, feature-catalog verification, lint and the repository's changed-file format/lint/English-only checks also pass.

The original implementation, its output-budget fixture correction and this overlap fix are now one validated commit, addressing the intermediate failing-commit concern. I kept the original base: CONTRIBUTING.md says the merge queue rebases approved changes onto current main and explicitly asks contributors not to rebase by hand just to catch up. The PR description now records the final scope and evidence.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve with nits (1 P2)

Scope: follow-up on d3b12f2 (that commit is no longer fetchable after the force-push, so this review covers the full merge-base diff). Base main, merge base 77abdcb3, 1 commit, 4 files. Loaded coderbook (sections 2, 3, 5). ponytail-review and karpathy-guidelines were not loaded; their criteria were applied from the review skill's checklist. Ran in a separate session.

Previous findings

  • NFKC-expanding characters made oversized splitting advance one character per chunk: Resolved. apps/node-services/src/memory/search/chunks.ts:173-177 now caps the overlap at min(200, floor((end - start) / 2)), so each step advances at least half a chunk. The new bounds repeated source storage for %s cases in tests/memory/chunk-token-bound.test.ts assert that the total stored characters stay at or below twice the input. I measured 100,000 × U+FDFA: 1,204 chunks and 199,849 stored characters (before: one chunk per character).

Findings

P2

  • apps/node-services/src/memory/search/chunks.ts:146-163: The binary search makes splitting dense text much more CPU-heavy, and the chunker also runs at query time. Every oversized chunk retokenizes a window of up to 3,000 characters about 12 times (NFKC normalization, regex passes and Han bigrams on each pass), even when the final chunk is only a few hundred characters or fewer. chunkSource runs synchronously on the read path as well as at indexing time: src/memory/search/raw-query.ts:136 and :178, and src/memory/knowledge-query.ts:502. Measured with Node 26.5 on this host, using chunkSource from the merge base vs. this head:

    • 1,000,000 UTF-16 chars of unspaced Han ("一二" repeated, no blank lines): 319 ms → 4,789 ms (358 → 3,333 chunks)
    • 100,000 × U+FDFA: 136 ms → 11,044 ms

    A large extracted or OCR'd CJK document with no blank lines is realistic. Every raw query that reads such a source blocks the shared node-services event loop for seconds, and a crafted ligature upload blocks it for minutes. Possible fixes: cap the search's upper bound near the previous chunk's length (for example start + min(MAX_CHUNK_CHARS, 2 * previousLength), widening only when the token count stays under the limit), or tokenize the block once and pick the cut from cumulative token offsets. Either keeps the same bounds without the repeated full-window tokenization.

Verified as fine

  • Token bound: when the 3,000-char window exceeds 500 tokens, the search returns the largest end in [start+1, end] whose slice tokenizes to 500 tokens or fewer (chunks.ts:149-162). The surrogate pullback at :164-170 can only shorten the slice. Because low >= start + 1 and the step is start = max(start + 1, end - overlap), the loop always progresses.
  • No empty or broken chunks in practice: one code point expands to at most about 18 NFKC characters, which can't exceed 500 tokens. So end is at least one whole code point past start, and the low-surrogate skip at :178-183 keeps chunk starts on character boundaries.
  • Chunk IDs stay deterministic (chunk-${digest}-${start}, chunks.ts:85). Sources already indexed with the old split are re-chunked on the next agent sync: the skip condition in src/memory/chunk-index.ts:716-722 compares chunk_count with the new prepared.length, and the token-bounded split changes the count for every affected block.
  • Fixture change in tests/memory/raw-knowledge-query.test.ts:1217-1221: U+1E00–U+1E7F are still three UTF-8 bytes each and have no Han bigrams, so the output-budget tests still exercise byte truncation. This is why the fixture had to change, so it is in scope.
  • README (src/memory/README.md) documents both bounds and the overlap rule in the same PR. No new env vars or contract changes, no CJK in added lines or in the commit message, and no merge commits.

Process notes

  • The branch is 338 commits behind main, and main requires up-to-date branches, so it needs a rebase. src/memory/README.md changed on main since the merge base, so check that hunk during the rebase.
  • The commit author is linked to GitHub (Afloat16).

CI

changes, repository-gate and check (web) pass; everything else was skipped. No node-services check appears in this run, so CI did not execute the memory tests. The PR body reports a local pnpm --filter @linger/node-services check pass. I didn't re-run the suite because dependencies aren't installed here. I only ran the chunkSource benchmark above with node --experimental-strip-types against copies of chunks.ts (base and head) and bm25.ts.

Automated review by Claude Code


Automated review of e19b0e3 by Claude Code.

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