Skip to content

Commit cb4c2c3

Browse files
committed
fix missed short values in document comparisons
1 parent 778ef49 commit cb4c2c3

2 files changed

Lines changed: 186 additions & 4 deletions

File tree

‎serviette/server/documents.py‎

Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,8 @@
135135
# Two documents sharing at least this fraction of their lines are compared
136136
# as versions of one text (a diff); below it they are different documents.
137137
_VERSION_OVERLAP = 0.3
138-
# Lines shorter than this (after squashing) are not compared: codes and
139-
# table cells repeat throughout a document and say nothing on their own.
138+
# Only lines at least this long (after squashing) establish that documents
139+
# are versions of one text. Short values still participate in the diff.
140140
_MIN_LINE = 12
141141
# From this many lines on, a chunk's first and last line are taken to be cut
142142
# by the splitter and are not compared (shorter chunks are whole paragraphs).
@@ -685,8 +685,14 @@ class _Lines:
685685

686686
def __init__(self, chunks: list[dict[str, Any]]) -> None:
687687
self.chunks = chunks
688-
# squashed line -> index of the first chunk containing it
688+
# Long lines establish version similarity and running headers;
689+
# short values are kept separately for exact matching in the diff.
689690
self.lines: dict[str, int] = {}
691+
self.short_lines: set[str] = set()
692+
# Adjacent lines can be one line in another PDF extraction. Only
693+
# spans containing a short line need this extra exact-match index.
694+
self.short_contexts: dict[str, set[str]] = {}
695+
self.joined_short_lines: set[str] = set()
690696
# per chunk: its lines as (squashed, raw), in order
691697
self.by_chunk: list[list[tuple[str, str]]] = []
692698
squashed_chunks = []
@@ -702,7 +708,44 @@ def __init__(self, chunks: list[dict[str, Any]]) -> None:
702708
for squashed, _raw in rows:
703709
if len(squashed) >= _MIN_LINE:
704710
self.lines.setdefault(squashed, index)
711+
elif squashed:
712+
self.short_lines.add(squashed)
713+
nonempty = [squashed for squashed, _raw in rows if squashed]
714+
for width in (2, 3):
715+
for start in range(len(nonempty) - width + 1):
716+
span = nonempty[start : start + width]
717+
short = [line for line in span if len(line) < _MIN_LINE]
718+
if short:
719+
joined = "".join(span)
720+
self.joined_short_lines.add(joined)
721+
for line in short:
722+
self.short_contexts.setdefault(line, set()).add(joined)
705723
self.by_chunk.append(rows)
724+
# Overlapping windows may end with a tiny chunk already covered by
725+
# the previous window. Its cut-off first word is not a standalone
726+
# short value. Check only short suffixes, keeping the work linear
727+
# in the corpus size; do not confuse 100 with the suffix of 1100.
728+
short_chunks: dict[str, set[int]] = {}
729+
for index, text in enumerate(squashed_chunks):
730+
if text and len(text) < _MIN_LINE:
731+
short_chunks.setdefault(text, set()).add(index)
732+
self.redundant_short_chunks: set[int] = set()
733+
if short_chunks:
734+
for covering_chunk, text in zip(chunks, squashed_chunks):
735+
for size in range(1, min(len(text), _MIN_LINE)):
736+
suffix = text[-size:]
737+
if suffix[0].isdigit() and (
738+
text[-size - 1].isdigit() or text[-size - 1] in "+-.,"
739+
):
740+
continue
741+
for index in short_chunks.get(suffix, ()):
742+
# Windows of one parsed document overlap verbatim.
743+
# Case/punctuation normalization alone is too weak
744+
# to establish that a chunk is redundant.
745+
raw = chunks[index]["text"].strip()
746+
covering = covering_chunk["text"].rstrip()
747+
if len(raw) < len(covering) and covering.endswith(raw):
748+
self.redundant_short_chunks.add(index)
706749
# The whole text, for finding a line that the other file wraps
707750
# differently (so it is no line of its own there).
708751
self.text = "\x00".join(squashed_chunks)
@@ -763,6 +806,21 @@ def contains_line(line: str) -> bool:
763806
return False
764807

765808
def present(squashed: str) -> bool:
809+
if len(squashed) < _MIN_LINE:
810+
# A short value must match a whole line: "100" inside
811+
# "1100", or "On" inside another word, is not unchanged.
812+
# Joining neighbouring lines also permits wrapping changes,
813+
# but the resulting span must still match a whole line.
814+
return (
815+
squashed in other.short_lines
816+
or squashed in other.joined_short_lines
817+
or any(
818+
context in other.lines
819+
or context in other.short_lines
820+
or context in other.joined_short_lines
821+
for context in self.short_contexts.get(squashed, ())
822+
)
823+
)
766824
if squashed in other.lines:
767825
return True
768826
mask = _DIGITS.sub("#", squashed)
@@ -780,10 +838,12 @@ def present(squashed: str) -> bool:
780838
reported: set[str] = set()
781839
passages: list[tuple[str, int]] = []
782840
for index, rows in enumerate(self.by_chunk):
841+
if index in self.redundant_short_chunks:
842+
continue
783843
run: list[str] = []
784844
for squashed, raw in [*rows, ("", "")]:
785845
missing = False
786-
if len(squashed) >= _MIN_LINE and squashed not in reported:
846+
if squashed and squashed not in reported:
787847
if squashed not in verdicts:
788848
verdicts[squashed] = present(squashed)
789849
missing = not verdicts[squashed]

‎tests/test_documents.py‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,128 @@ def test_version_diff_preserves_numeric_meaning(old, new):
397397
assert "1 passages changed" in built.notice
398398

399399

400+
def _compare_text_versions(old: str, new: str, window_size: int | None = None):
401+
entries = [{"id": name, "metadata": {}, "chunks": 1} for name in ("old.txt", "new.txt")]
402+
chunks = [
403+
_windows(text, window_size) if window_size else [{"text": text, "metadata": {}}]
404+
for text in (old, new)
405+
]
406+
return docmode.compare_context(entries, chunks, fake_embedding("q"), budget=24_000)
407+
408+
409+
@pytest.mark.parametrize(
410+
"old,new",
411+
[
412+
("Rate: 10%", "Rate: 20%"),
413+
("100", "200"),
414+
("100", "1100"),
415+
("100", "-100"),
416+
("+100", "-100"),
417+
("1.5", "15"),
418+
("15%", "15"),
419+
("01.02.2026", "02.02.2026"),
420+
("Да", "Нет"),
421+
("On", "Off"),
422+
],
423+
)
424+
@pytest.mark.parametrize("window_size", [None, 160, 240])
425+
def test_version_diff_reports_short_value_changes(old, new, window_size):
426+
before = "\n".join(SHARED[:3]) + "\n"
427+
after = "\n" + "\n".join(SHARED[3:])
428+
built = _compare_text_versions(before + old + after, before + new + after, window_size)
429+
blocks = built.context[1:]
430+
assert "share most of their text" in built.context[0]
431+
assert any(f"old.txt: {old}" in b or f"[only in old.txt] {old}" in b for b in blocks)
432+
assert any(f"new.txt: {new}" in b or f"[only in new.txt] {new}" in b for b in blocks)
433+
assert "No differences were found" not in built.context[0]
434+
assert not any("Unchanged provision" in b for b in blocks)
435+
436+
437+
@pytest.mark.parametrize("value", ["100", "Да", "Rate: 10%"])
438+
@pytest.mark.parametrize("added", [False, True])
439+
def test_version_diff_reports_short_line_additions_and_removals(value, added):
440+
unchanged = "\n".join(SHARED)
441+
changed = unchanged + "\n" + value
442+
old, new = (unchanged, changed) if added else (changed, unchanged)
443+
built = _compare_text_versions(old, new)
444+
name = "new.txt" if added else "old.txt"
445+
assert built.context[1:] == [f"[only in {name}] {value}"]
446+
447+
448+
@pytest.mark.parametrize(
449+
"old,new",
450+
[
451+
("Rate: 10%", " Rate : 10 % "),
452+
("Net: -100", "Net: − 100"),
453+
("Да", " ДА! "),
454+
("Café", "Cafe\u0301"),
455+
("office", "of\u00adfice"),
456+
("Rate: 10%", "Rate:\n10%"),
457+
("Rate:\n10%", "Rate: 10%"),
458+
("The status is Active", "The status is\nActive"),
459+
("The status is\nActive", "The status is Active"),
460+
("", "\n---\n...\n"),
461+
],
462+
)
463+
@pytest.mark.parametrize("window_size", [None, 160, 240])
464+
def test_version_diff_ignores_formatting_changes_around_short_lines(old, new, window_size):
465+
before = "\n".join(SHARED[:3]) + "\n"
466+
after = "\n" + "\n".join(SHARED[3:])
467+
built = _compare_text_versions(before + old + after, before + new + after, window_size)
468+
assert "share most of their text" in built.context[0]
469+
assert built.context[1:] == []
470+
assert "0 passages changed, 0 only in new.txt, 0 only in old.txt" in built.notice
471+
472+
473+
def test_short_common_values_do_not_make_unrelated_documents_versions():
474+
common = "\n".join(f"Code {i}" for i in range(30))
475+
old = common + "\n" + "\n".join(SHARED)
476+
new = common + "\n" + "\n".join(
477+
f"Chapter {i}. Instructions for preparing a vegetable soup." for i in range(6)
478+
)
479+
built = _compare_text_versions(old, new)
480+
assert built.system_prompt == docmode.EXCERPTS_SYSTEM_PROMPT
481+
assert "share little or no identical text" in built.context[0]
482+
483+
484+
@pytest.mark.parametrize(
485+
"old,new,other",
486+
[("100", "200", "1100"), ("On", "Off", "authentication.")],
487+
)
488+
def test_short_chunks_are_not_confused_with_other_value_suffixes(old, new, other):
489+
entries = [{"id": name, "metadata": {}, "chunks": 8} for name in ("old.txt", "new.txt")]
490+
common = [{"text": line, "metadata": {}} for line in SHARED]
491+
common.append({"text": "A separate unchanged field contains " + other, "metadata": {}})
492+
chunks = [[*common, {"text": value, "metadata": {}}] for value in (old, new)]
493+
built = docmode.compare_context(entries, chunks, fake_embedding("q"), budget=24_000)
494+
assert f"[only in old.txt] {old}" in built.context[1:]
495+
assert f"[only in new.txt] {new}" in built.context[1:]
496+
497+
498+
def test_rag_compares_short_values_from_named_documents(tmp_path, mock_server_embedder):
499+
path = tmp_path / "versions.duckdb"
500+
write_duckdb_rows(path, [
501+
{
502+
"id": name,
503+
"text": "\n".join([*SHARED, rate]),
504+
"metadata": {"path": name},
505+
"embedding": fake_embedding("rate"),
506+
}
507+
for name, rate in (("old.txt", "Rate: 10%"), ("new.txt", "Rate: 20%"))
508+
])
509+
llm = _ScriptedLLM()
510+
body = _ask(path, mock_server_embedder, llm, "Compare old.txt and new.txt")
511+
assert body["mode"] == "compare"
512+
assert "1 passages changed" in body["notice"]
513+
assert any(
514+
"Rate: 10%" in block and "Rate: 20%" in block
515+
for block in llm.calls[0]["context"][1:]
516+
)
517+
assert {source["metadata"]["path"] for source in body["sources"]} == {
518+
"old.txt", "new.txt"
519+
}
520+
521+
400522
@pytest.mark.parametrize("old,new", [
401523
("Balance is -100 dollars.", "Balance is − 100 dollars."),
402524
("Balance is -100 dollars.", "Balance is –100 dollars."),

0 commit comments

Comments
 (0)