adeu icon indicating copy to clipboard operation
adeu copied to clipboard

Word-level diff silently replaces tokens named after Object.prototype members, and shifts _match_start_index

Open vidrpatel opened this issue 3 months ago • 1 comments

Summary _words_to_chars uses a plain object literal as its word→code table and tests membership with in, which walks the prototype chain. Any token that happens to be named after an Object.prototype member — constructor, toString, valueOf, hasOwnProperty, isPrototypeOf, propertyIsEnumerable, toLocaleString — is therefore "found" in the table before a single word has been seen, and resolves to character code 0.

Code 0 decodes to token_array[0]: the first word of the original text.

There are two consequences, and the second is the more serious:

The word is replaced by an unrelated word in the emitted edit. A token like this that is not being changed at all still shifts _match_start_index for every later edit in the same text, because the index is advanced by the length of the decoded string. Both are silent — process_batch returns status: "ok", edits_applied: 1, failed: [].

constructor is a common term for many use cases, which is how we hit this.

Reproduction generate_edits_from_text is exported, so no document is needed. Verified on @adeu/[email protected], Node 24.

import { generate_edits_from_text } from '@adeu/core';

// A — the word is replaced generate_edits_from_text( 'The visual layers can be generated.', 'Layer constructor 404 can generate the visual layers.', ); [{ "type": "modify", "target_text": "The visual layers can be generated", "new_text": "Layer The 404 can generate the visual layers", "comment": "Diff: Replacement", "_match_start_index": 0 }] constructor became The — the first token of the original text.

// B — an UNCHANGED occurrence shifts the offset of a later edit generate_edits_from_text( 'The system uses a constructor to build widgets and then ships them.', 'The system uses a constructor to build widgets and then delivers them.', ); [{ "type": "modify", "target_text": "ships", "new_text": "delivers", "comment": "Diff: Replacement", "_match_start_index": 48 }] "ships" is at index 56. The reported index is 48 — short by exactly 'constructor'.length - 'The'.length = 8. Position 48 is "nd then ".

Replacing constructor with builder in the same sentence gives _match_start_index: 52, which is correct.

Applied to a real .docx through RedlineEngine.process_batch, case B writes:

asked for "…build widgets and then delivers them." adeu wrote "…build widgets adeliversen ships them." status: ok The replacement lands eight characters early, in the middle of a word.

Root cause node/packages/core/src/diff.ts (lines 258–274 on main today):

const token_array: string[] = []; const token_hash: Record<string, number> = {}; ... if (token in token_hash) { encoded_chars += String.fromCharCode(token_hash[token]); } else { const code = token_array.length; token_hash[token] = code; ... } 'constructor' in {} is true, so token_hash['constructor'] returns Object.prototype.constructor — a function rather than a number. String.fromCharCode coerces it to NaN and returns U+0000. Decoding then reads token_array[0], the first token ever registered, which is the first word of text1.

The offset shift in case B comes from generate_edits_from_text:

current_original_index += text.length; // text is the DECODED string An equal segment containing constructor (11 chars) decodes to The (3), so the running index under-counts by 8 from that point on.

Twelve tokens collide at the encoder. Through the engine, seven corrupt today; the five underscore-bearing ones (proto, defineGetter, defineSetter, lookupGetter, lookupSetter) currently take a whole-string replacement path that skips the word diff, so they are latent rather than safe.

Why it went unnoticed The declared type is Record<string, number>, so String.fromCharCode(token_hash[token]) typechecks cleanly while receiving a function at runtime. Nothing in the code looks wrong.

The Python implementation does not share this flaw python/src/adeu/diff.py is the same code — token_hash: Dict[str, int] = {}, if token in token_hash — and in Python it is simply right, because a dict has no prototype chain. This looks like a faithful transliteration into a language where in means something different, rather than a design difference. The two implementations diverge in behavior on the inputs above.

Suggested fix An expression:

const token_hash: Record<string, number> = Object.create(null); A Map is more idiomatic but changes three call sites; Object.create(null) preserves the in and [] syntax exactly.

Same pattern elsewhere Lower severity, reported together only because the root cause is identical. extract_all_domain_metadata uses plain object literals keyed by strings taken from the document:

definitions[term] — a document defining constructor as a term is recorded as a duplicate definition, and can never be reported as an unused one, because Object.constructor.count is undefined rather than 0 raw_anchors[b_name] — keyed on bookmark names candidates_by_term[term]

These misreport rather than corrupt, and reach only build_structural_appendix.

vidrpatel avatar Aug 27 '26 03:08 vidrpatel

Thanks for the detailed reproduction and root cause breakdown. The fix is merged into main and will be included in the next release.

Git-Uzair avatar Aug 27 '26 09:08 Git-Uzair