Skip to content

fix: avoid stack overflow in Trie subtree traversal - #811

Open
xiaoyao-666-coder wants to merge 1 commit into
NaturalNode:masterfrom
xiaoyao-666-coder:fix/trie-subtree-stack-overflow
Open

xiaoyao-666-coder wants to merge 1 commit into
NaturalNode:masterfrom
xiaoyao-666-coder:fix/trie-subtree-stack-overflow

Conversation

@xiaoyao-666-coder

@xiaoyao-666-coder xiaoyao-666-coder commented Nov 14, 2026 •

Copy link
Copy Markdown

After inserting a 50,000-character key, contains() succeeds but getSize() and keysWithPrefix('') both throw RangeError: Maximum call stack size exceeded. The remaining recursive subtree walks cannot handle the depth that iterative insertion now supports.

const { Trie } = require('natural')
const trie = new Trie()
const key = 'a'.repeat(50000)
trie.addString(key)
trie.contains(key)       // true
trie.getSize()           // before: RangeError; after: 50001
trie.keysWithPrefix('')  // before: RangeError; after: [key]

Proposed Changes

  • Use explicit stacks for subtree collection and node counting.
  • Push child keys in reverse enumeration order so collection retains the existing depth-first result order, including numeric property keys and terminal prefixes.
  • Add five Jasmine specs covering deep traversal, ordering, empty keys, empty tries, and missing prefixes.

This follows up on #780, which deliberately left these recursive walks unchanged. It does not modify the case-sensitivity condition addressed by #802. No public signature or type declaration changes are needed.

Validation

On Node 24.22.1 / Windows:

  • New tests against unmodified source: 33 specs, 2 stack-overflow failures
  • Fixed Trie suite: 33 specs, 0 failures
  • npm test: 903 specs, 0 failures
  • 9,734 comparisons against the baseline across 200 generated tries: identical node counts and ordered prefix results for inputs that fit the old call stack
  • npm run build:tests and npm run lint
  • Standard JS and focused jscpd check for lib/natural/trie/trie.js
  • npm run build:esm and npm run smoke:esm
  • git diff --check

The database-backed I/O suite was not run. Companion documentation targets gh-pages in #812, as required by CONTRIBUTING.md.

Checklist before merging

  • Added Jasmine tests
  • TypeScript declarations: no signature changes required

Prepared with Codex assistance.

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