From 831373cdf6b77f77ec11ca6a0b42bd97405555d7 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 21:12:12 +0000 Subject: [PATCH 01/10] The TypeScript merge copies records instead of parsing whole indexes scip_merge_indexes.py parsed each member's index as one scip.Index, and python-protobuf refuses a whole message when any string in it is not UTF-8. scip-typescript writes such strings, so one document failed the merge, and the pass, after every member had been indexed. The merge now reads the top-level records and each document's relative_path with the converter's reader, applies the same ownership rule, and writes the kept records out byte for byte. Nothing is decoded, the parts are memory-mapped, and the converter decides what to do with a document it cannot read. The output is written beside its target and swapped in with os.replace, so --output may name one of the inputs while those are still mapped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 137 ++++++++++++--------- tests/unit/test_scip_merge_indexes.py | 98 ++++++++++++--- 2 files changed, 164 insertions(+), 71 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index c4a32d9fb21..be7e81fd44e 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -12,46 +12,43 @@ the first non-empty input. External symbols are concatenated. An all-empty input list, or only empty files, writes a zero-byte output so the converter treats it as an empty index. + +The merge reads only the top-level records and each document's +relative_path, and copies the records it keeps byte for byte. Nothing is +decoded, so a document python-protobuf would refuse (a string field that +is not UTF-8) reaches the converter, which decides what to do with it. """ from __future__ import annotations import argparse import importlib.util -import sys +import os from pathlib import Path -from typing import Any +from typing import Any, BinaryIO _HARNESS = Path(__file__).resolve().parent -_VENDOR = _HARNESS / "vendor" -def _load_ts_projects() -> Any: - spec = importlib.util.spec_from_file_location( - "scip_ts_projects", _HARNESS / "scip_ts_projects.py" - ) +def _load_harness_module(name: str) -> Any: + path = _HARNESS / f"{name}.py" + spec = importlib.util.spec_from_file_location(name, path) if spec is None or spec.loader is None: - raise SystemExit(f"cannot load {_HARNESS / 'scip_ts_projects.py'}") + raise SystemExit(f"cannot load {path}") mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod -_ts_projects = _load_ts_projects() +_ts_projects = _load_harness_module("scip_ts_projects") project_owns = _ts_projects.project_owns project_scope = _ts_projects.project_scope +_converter = _load_harness_module("scip_to_delta") +_read_index = _converter._read_index +_top_level_records = _converter._top_level_records +_document_path = _converter._document_path - -def _ensure_scip_pb2() -> Any: - if str(_VENDOR) not in sys.path: - sys.path.insert(0, str(_VENDOR)) - try: - import scip_pb2 - except Exception as e: # ImportError, or protobuf VersionError - raise SystemExit( - f"cannot load vendor/scip_pb2.py ({e}): merging indexes needs protobuf>=7.35.1" - ) from e - return scip_pb2 +_METADATA, _DOCUMENT, _EXTERNAL_SYMBOL = 1, 2, 3 def _scope_specificity(project: str) -> int: @@ -75,6 +72,38 @@ def _preferred_owner(projects: list[str], relpath: str) -> str | None: return tied[0] +def _keeps(project: str, relpath: str, owners: list[str]) -> bool: + # Keep documents this member owns. Documents followed through + # TypeScript project references into another package are + # dropped even when that package is not in this merge, so a + # subset rebuild cannot overwrite the other package's rows. + # owners is the full discovered set: a root-level tsconfig owns + # every path, so ownership still prefers a longer member that + # was not indexed in this run. + if not project_owns(project, relpath): + return False + owner = _preferred_owner(owners, relpath) + # Compare scopes, not raw project strings: a generated member + # target is dir/tsconfig.scip.json, while --known-project still + # names dir. + return owner is None or project_scope(owner) == project_scope(project) + + +def _encode_varint(value: int) -> bytes: + out = bytearray() + while value > 0x7F: + out.append(value & 0x7F | 0x80) + value >>= 7 + out.append(value) + return bytes(out) + + +def _write_record(out: BinaryIO, field: int, payload: Any) -> None: + out.write(_encode_varint(field << 3 | 2)) # wire type 2, length-delimited + out.write(_encode_varint(len(payload))) + out.write(payload) + + def merge_indexes( paths: list[Path], output: Path, @@ -83,49 +112,43 @@ def merge_indexes( ) -> None: if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") - scip_pb2 = _ensure_scip_pb2() - merged = scip_pb2.Index() - documents: dict[str, object] = {} + owners = known_projects if known_projects is not None else (projects or []) + metadata = None + documents: dict[str, Any] = {} + external_symbols: list[Any] = [] has_payload = False for i, path in enumerate(paths): - data = path.read_bytes() if path.is_file() else b"" + data = _read_index(str(path)) if path.is_file() else b"" if not data: continue - idx = scip_pb2.Index() - idx.ParseFromString(data) - if not has_payload and idx.HasField("metadata"): - merged.metadata.CopyFrom(idx.metadata) project = projects[i] if projects is not None else None - for doc in idx.documents: - rel = doc.relative_path - if projects is not None and project is not None: - # Keep documents this member owns. Documents followed through - # TypeScript project references into another package are - # dropped even when that package is not in this merge, so a - # subset rebuild cannot overwrite the other package's rows. - # known_projects is the full discovered set: a root-level - # tsconfig owns every path, so ownership still prefers a - # longer member that was not indexed in this run. - if not project_owns(project, rel): - continue - owners = known_projects if known_projects is not None else projects - owner = _preferred_owner(owners, rel) - # Compare scopes, not raw project strings: a generated - # member target is dir/tsconfig.scip.json, while - # --known-project still names dir. - if owner is not None and project_scope(owner) != project_scope(project): - continue - copied = scip_pb2.Document() - copied.CopyFrom(doc) - documents[rel] = copied - merged.external_symbols.extend(idx.external_symbols) + for field, payload in _top_level_records(data): + if field == _METADATA and not has_payload: + metadata = payload + elif field == _DOCUMENT: + rel = _document_path(payload) + if project is None or _keeps(project, rel, owners): + documents[rel] = payload + elif field == _EXTERNAL_SYMBOL: + external_symbols.append(payload) has_payload = True - if not has_payload: - output.write_bytes(b"") - return - for doc in documents.values(): - merged.documents.append(doc) - output.write_bytes(merged.SerializeToString()) + # The parts stay mapped while the output is written, so write beside the + # output and swap it in; truncating an input that is also the output would + # pull the mapped pages away. + tmp = output.with_name(output.name + ".tmp") + try: + with open(tmp, "wb") as out: + if has_payload: + if metadata is not None: + _write_record(out, _METADATA, metadata) + for payload in documents.values(): + _write_record(out, _DOCUMENT, payload) + for payload in external_symbols: + _write_record(out, _EXTERNAL_SYMBOL, payload) + os.replace(tmp, output) + except BaseException: + tmp.unlink(missing_ok=True) + raise def main(argv: list[str] | None = None) -> int: diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 45c2990217f..f663d73d288 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -2,17 +2,27 @@ from __future__ import annotations +import importlib import importlib.util +import sys from pathlib import Path +from typing import Any _SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" _SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) _MOD = importlib.util.module_from_spec(_SPEC) _SPEC.loader.exec_module(_MOD) +_VENDOR = _SCRIPT.parent / "vendor" + + +def _scip_pb2() -> Any: + if str(_VENDOR) not in sys.path: + sys.path.insert(0, str(_VENDOR)) + return importlib.import_module("scip_pb2") def _index_with_docs(relative_paths: list[str], texts: list[str] | None = None) -> bytes: - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() idx = scip_pb2.Index() idx.metadata.project_root = "file:///repo" for i, path in enumerate(relative_paths): @@ -32,7 +42,7 @@ def test_merge_concatenates_documents_and_skips_empty_parts(tmp_path: Path) -> N empty.write_bytes(b"") out = tmp_path / "merged.scip" _MOD.merge_indexes([a, empty, b], out) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) assert merged.metadata.project_root == "file:///repo" @@ -67,7 +77,7 @@ def test_merge_drops_referenced_documents_in_favor_of_the_owner(tmp_path: Path) out, projects=["packages/app", "packages/lib"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -84,7 +94,7 @@ def test_merge_without_projects_keeps_the_last_copy_of_a_path(tmp_path: Path) -> second.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["second"])) out = tmp_path / "merged.scip" _MOD.merge_indexes([first, second], out) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/lib/src/b.ts"] @@ -107,7 +117,7 @@ def test_merge_prefers_the_longest_project_scope(tmp_path: Path) -> None: out, projects=["packages/app", "packages/app/widget"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -129,7 +139,7 @@ def test_merge_keeps_documents_from_sibling_tsconfigs(tmp_path: Path) -> None: out, projects=["packages/app/tsconfig.app.json", "packages/app/tsconfig.test.json"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -152,7 +162,7 @@ def test_merge_sibling_tsconfigs_keep_the_last_copy_of_an_overlapping_path( out, projects=["packages/app/tsconfig.app.json", "packages/app/tsconfig.test.json"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/app/src/shared.ts"] @@ -170,7 +180,7 @@ def test_merge_drops_unowned_references_when_the_owner_is_absent(tmp_path: Path) ) out = tmp_path / "merged.scip" _MOD.merge_indexes([dependent], out, projects=["packages/app"]) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -183,7 +193,7 @@ def test_merge_keeps_documents_from_a_root_level_tsconfig(tmp_path: Path) -> Non app.write_bytes(_index_with_docs(["src/main.ts"], ["from-app"])) out = tmp_path / "merged.scip" _MOD.merge_indexes([app], out, projects=["tsconfig.app.json"]) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -206,7 +216,7 @@ def test_merge_prefers_a_nested_member_over_a_root_tsconfig(tmp_path: Path) -> N out, projects=["tsconfig.app.json", "packages/app"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -231,7 +241,7 @@ def test_merge_drops_followed_docs_from_a_root_tsconfig_when_the_member_is_absen projects=["tsconfig.app.json"], known_projects=["tsconfig.app.json", "packages/app"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -251,7 +261,7 @@ def test_merge_keeps_docs_when_project_is_a_generated_tsconfig_scip_json( projects=["packages/app/tsconfig.scip.json"], known_projects=["packages/app"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -283,7 +293,7 @@ def test_merge_drops_root_docs_when_sibling_app_configs_share_the_owner_scope( "tsconfig.app.json", ], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -312,8 +322,68 @@ def test_merge_prefers_a_one_character_member_over_a_root_tsconfig(tmp_path: Pat projects=["tsconfig.app.json", "a"], known_projects=["tsconfig.app.json", "a"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} assert docs == {"src/main.ts": "from-root", "a/src/a.ts": "from-a"} + + +def test_merge_copies_a_document_whose_strings_are_not_utf8(tmp_path: Path) -> None: + """scip-typescript can write a string that is not UTF-8. The merge copies + the document as it is and leaves the decision to the converter.""" + part = tmp_path / "app.scip" + raw = _index_with_docs( + ["packages/app/src/a.ts", "packages/app/src/bad.ts", "packages/lib/src/b.ts"], + ["from-app", "ZZBADUTF8ZZ", "from-app-ref"], + ) + part.write_bytes(raw.replace(b"ZZBADUTF8ZZ", b"\xff\xfeBADUTF8ZZ")) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [part], + out, + projects=["packages/app"], + known_projects=["packages/app", "packages/lib"], + ) + data = out.read_bytes() + assert b"\xff\xfeBADUTF8ZZ" in data + merged = _scip_pb2().Index() + merged.ParseFromString(data.replace(b"\xff\xfeBADUTF8ZZ", b"ZZBADUTF8ZZ")) + assert merged.metadata.project_root == "file:///repo" + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"packages/app/src/a.ts": "from-app", "packages/app/src/bad.ts": "ZZBADUTF8ZZ"} + + +def test_merge_keeps_every_parts_external_symbols(tmp_path: Path) -> None: + scip_pb2 = _scip_pb2() + parts = [] + for name in ("lodash", "react"): + idx = scip_pb2.Index() + idx.metadata.project_root = "file:///repo" + idx.external_symbols.add().symbol = f"scip-typescript npm {name} 1.0.0 `index.d.ts`/" + part = tmp_path / f"{name}.scip" + part.write_bytes(idx.SerializeToString()) + parts.append(part) + out = tmp_path / "merged.scip" + _MOD.merge_indexes(parts, out) + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + assert [s.symbol for s in merged.external_symbols] == [ + "scip-typescript npm lodash 1.0.0 `index.d.ts`/", + "scip-typescript npm react 1.0.0 `index.d.ts`/", + ] + + +def test_merge_may_write_over_one_of_its_inputs(tmp_path: Path) -> None: + a = tmp_path / "a.scip" + b = tmp_path / "b.scip" + a.write_bytes(_index_with_docs(["packages/app/src/a.ts"])) + b.write_bytes(_index_with_docs(["packages/lib/src/b.ts"])) + _MOD.merge_indexes([a, b], a) + merged = _scip_pb2().Index() + merged.ParseFromString(a.read_bytes()) + assert [d.relative_path for d in merged.documents] == [ + "packages/app/src/a.ts", + "packages/lib/src/b.ts", + ] + assert not (tmp_path / "a.scip.tmp").exists() From a4c39d1827fb8d4f8d82159fedce09282a973083 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:10:31 +0000 Subject: [PATCH 02/10] The record reader refuses a record that runs past the end of its data _top_level_records cut a record to the bytes that were left when its declared length ran past the end of the data. The merge then wrote a fresh header for the shorter slice, so a truncated or damaged part came out as a valid document where the whole-index parse had refused it. The converter read the same slice and converted it. The reader now raises ValueError naming the offset and how far the record overruns. The merge stops with the part's name for that error and for a part that ends inside a record header. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 27 ++++++++----- scripts/scip_harness/scip_to_delta.py | 2 + tests/unit/test_scip_merge_indexes.py | 46 ++++++++++++++++++++++ tests/unit/test_scip_to_delta_cli.py | 21 ++++++++++ 4 files changed, 86 insertions(+), 10 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index be7e81fd44e..9eaf079a8f8 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -16,7 +16,9 @@ The merge reads only the top-level records and each document's relative_path, and copies the records it keeps byte for byte. Nothing is decoded, so a document python-protobuf would refuse (a string field that -is not UTF-8) reaches the converter, which decides what to do with it. +is not UTF-8) reaches the converter, which decides what to do with it. A +record that runs past the end of its part is corrupt: the merge stops and names +the part, as the whole-index parse used to. """ from __future__ import annotations @@ -122,15 +124,20 @@ def merge_indexes( if not data: continue project = projects[i] if projects is not None else None - for field, payload in _top_level_records(data): - if field == _METADATA and not has_payload: - metadata = payload - elif field == _DOCUMENT: - rel = _document_path(payload) - if project is None or _keeps(project, rel, owners): - documents[rel] = payload - elif field == _EXTERNAL_SYMBOL: - external_symbols.append(payload) + try: + for field, payload in _top_level_records(data): + if field == _METADATA and not has_payload: + metadata = payload + elif field == _DOCUMENT: + rel = _document_path(payload) + if project is None or _keeps(project, rel, owners): + documents[rel] = payload + elif field == _EXTERNAL_SYMBOL: + external_symbols.append(payload) + except ValueError as e: + raise SystemExit(f"{path}: corrupt part: {e}") from e + except IndexError as e: + raise SystemExit(f"{path}: corrupt part: it ends inside a record header") from e has_payload = True # The parts stay mapped while the output is written, so write beside the # output and swap it in; truncating an input that is also the output would diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index d4777f7e10d..c23bd7927f1 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -822,6 +822,8 @@ def varint(p: int) -> tuple[int, int]: field, wire = tag >> 3, tag & 7 if wire == 2: # length-delimited length, pos = varint(pos) + if pos + length > end: + raise ValueError(f"record at {pos} runs {pos + length - end} bytes past the end") payload = data[pos : pos + length] pos += length yield field, payload diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index f663d73d288..ba1771673b7 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -8,6 +8,8 @@ from pathlib import Path from typing import Any +import pytest + _SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" _SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) _MOD = importlib.util.module_from_spec(_SPEC) @@ -387,3 +389,47 @@ def test_merge_may_write_over_one_of_its_inputs(tmp_path: Path) -> None: "packages/lib/src/b.ts", ] assert not (tmp_path / "a.scip.tmp").exists() + + +def _last_record_header(raw: bytes) -> tuple[int, int]: + """The offset of the last document's length byte and that length. The index + ends with the document, whose length is below 128.""" + last = _scip_pb2().Index.FromString(raw).documents[-1].SerializeToString() + at = len(raw) - len(last) - 1 + assert raw[at] == len(last) < 0x80 + return at, len(last) + + +def _damaged(raw: bytes, how: str) -> bytes: + at, length = _last_record_header(raw) + if how == "length one byte too long": + return raw[:at] + bytes([length + 1]) + raw[at + 1 :] + if how == "last byte cut off": + return raw[:-1] + return raw[:at] # ends right after the record's tag + + +@pytest.mark.parametrize( + "how", ["length one byte too long", "last byte cut off", "ends inside the record header"] +) +def test_merge_rejects_a_part_whose_record_runs_past_its_end(tmp_path: Path, how: str) -> None: + """The old merge parsed the whole index and refused such a part. Copying the + record with a fresh header would turn the corruption into a valid document.""" + good = tmp_path / "good.scip" + broken = tmp_path / "broken.scip" + good.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["from-lib"])) + raw = _index_with_docs(["packages/app/src/a.ts", "packages/app/src/c.ts"], ["a", "c"]) + broken.write_bytes(_damaged(raw, how)) + out = tmp_path / "merged.scip" + with pytest.raises(SystemExit, match=r"broken\.scip: corrupt part"): + _MOD.merge_indexes([good, broken], out) + assert not out.exists() + assert not (tmp_path / "merged.scip.tmp").exists() + + +def test_the_reader_names_the_offset_of_a_record_that_runs_past_the_end() -> None: + raw = _index_with_docs(["packages/app/src/a.ts"], ["a"]) + at, _ = _last_record_header(raw) + grown = _damaged(raw, "length one byte too long") + with pytest.raises(ValueError, match=rf"record at {at + 1} runs 1 bytes past the end"): + list(_MOD._top_level_records(grown)) diff --git a/tests/unit/test_scip_to_delta_cli.py b/tests/unit/test_scip_to_delta_cli.py index 1e74c15ae35..4afbd9fa074 100644 --- a/tests/unit/test_scip_to_delta_cli.py +++ b/tests/unit/test_scip_to_delta_cli.py @@ -344,3 +344,24 @@ def test_only_a_scip_clang_index_claims_constructor_calls( assert (delta.get("features") == ["ctor_calls"]) is claims assert (delta["stats"]["factory_ctor_edges"] == 1) is claims assert bool(factory) is claims + + +def test_a_record_that_runs_past_the_end_of_the_index_fails_the_run(tmp_path: Path) -> None: + """The reader used to cut such a record to the bytes left, so one more byte + in a document's length made the run succeed on the document it had.""" + index = _index(tmp_path) + raw = index.read_bytes() + last = _pb().Index.FromString(raw).documents[-1].SerializeToString() + at = len(raw) - len(last) - 1 + assert raw[at] == len(last) < 0x80 + index.write_bytes(raw[:at] + bytes([len(last) + 1]) + raw[at + 1 :]) + proc = subprocess.run( + [sys.executable, str(_CONVERTER), "--index", str(index), "--commit", "h" * 40] + + ["--source-root", "", "--dry-run", str(tmp_path / "delta.json")], + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode != 0 + assert "past the end" in proc.stderr + assert not (tmp_path / "delta.json").exists() From 619be75bc3da58d9307a47c2cc6b38250a755941 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:43:37 +0000 Subject: [PATCH 03/10] The record reader refuses every truncated wire type _top_level_records bounds-checked length-delimited records only. A fixed32 or fixed64 field cut short was skipped by moving past the end of the data, so a part whose valid records were followed by one payload byte merged and converted with exit 0 where the protobuf parser refuses the index. The reader now refuses what the parser refuses and raises ValueError in the existing form: fixed32 and fixed64 spans that run past the end, a varint or tag that runs off the end or exceeds ten bytes, field number 0, and unbalanced or mismatched groups and wire types 6 and 7. A closed group in an unknown field is skipped, as the parser skips it. The merge's IndexError branch is gone because the reader no longer raises it. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 7 +-- scripts/scip_harness/scip_to_delta.py | 68 +++++++++++++++++----- tests/unit/test_scip_merge_indexes.py | 63 ++++++++++++++++++++ tests/unit/test_scip_to_delta_cli.py | 54 +++++++++++++++++ 4 files changed, 174 insertions(+), 18 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 9eaf079a8f8..b30eab0aaef 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -17,8 +17,9 @@ relative_path, and copies the records it keeps byte for byte. Nothing is decoded, so a document python-protobuf would refuse (a string field that is not UTF-8) reaches the converter, which decides what to do with it. A -record that runs past the end of its part is corrupt: the merge stops and names -the part, as the whole-index parse used to. +record, fixed-width value, varint, tag or group that the protobuf parser would +refuse is corrupt: the merge stops and names the part, as the whole-index parse +used to. """ from __future__ import annotations @@ -136,8 +137,6 @@ def merge_indexes( external_symbols.append(payload) except ValueError as e: raise SystemExit(f"{path}: corrupt part: {e}") from e - except IndexError as e: - raise SystemExit(f"{path}: corrupt part: it ends inside a record header") from e has_payload = True # The parts stay mapped while the output is written, so write beside the # output and swap it in; truncating an input that is also the output would diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index c23bd7927f1..23c3da6d4fd 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -804,37 +804,77 @@ def _factory_type_ref_span( def _top_level_records(data: bytes): """Yield (field, payload) for every length-delimited top-level record of - an Index message (1 = metadata, 2 = documents, 3 = external_symbols).""" - pos, end = 0, len(data) + an Index message (1 = metadata, 2 = documents, 3 = external_symbols). + + Every other field is skipped the way the protobuf parser skips it, and + anything the parser refuses is refused here with a ValueError: a record, + fixed-width value, varint or tag that runs past the end, a varint longer + than ten bytes, field number 0, an unbalanced group, and wire types 6 and 7. + """ + end, max_depth = len(data), 100 # the parser's own group nesting limit def varint(p: int) -> tuple[int, int]: shift = result = 0 + start = p while True: + if p >= end: + raise ValueError(f"record at {start} runs past the end inside a varint") b = data[p] result |= (b & 0x7F) << shift p += 1 if not b & 0x80: return result, p shift += 7 - + if shift >= 70: + raise ValueError(f"varint at {start} is longer than 10 bytes") + + def span(p: int, size: int) -> int: + if p + size > end: + raise ValueError(f"record at {p} runs {p + size - end} bytes past the end") + return p + size + + def skip(p: int, wire: int, field: int, depth: int) -> int: + """The position after one value of an unknown field.""" + if wire == 0: + return varint(p)[1] + if wire == 1: + return span(p, 8) + if wire == 5: + return span(p, 4) + if wire == 2: + length, p = varint(p) + return span(p, length) + if wire == 3: + if depth >= max_depth: + raise ValueError(f"group at {p} nests deeper than {max_depth}") + while True: + if p >= end: + raise ValueError(f"group {field} at {p} is not closed before the end") + tag, p = varint(p) + inner, inner_wire = tag >> 3, tag & 7 + if inner == 0: + raise ValueError(f"field number 0 at {p}") + if inner_wire == 4: + if inner != field: + raise ValueError(f"group {field} is closed by group {inner} at {p}") + return p + p = skip(p, inner_wire, inner, depth + 1) + raise ValueError(f"unexpected wire type {wire} at {p}") + + pos = 0 while pos < end: tag, pos = varint(pos) field, wire = tag >> 3, tag & 7 + if field == 0: + raise ValueError(f"field number 0 at {pos}") if wire == 2: # length-delimited length, pos = varint(pos) - if pos + length > end: - raise ValueError(f"record at {pos} runs {pos + length - end} bytes past the end") - payload = data[pos : pos + length] - pos += length + stop = span(pos, length) + payload = data[pos:stop] + pos = stop yield field, payload - elif wire == 0: - _, pos = varint(pos) - elif wire == 5: - pos += 4 - elif wire == 1: - pos += 8 else: - raise ValueError(f"unexpected wire type {wire} at {pos}") + pos = skip(pos, wire, field, 0) def _document_path(payload) -> str: diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index ba1771673b7..6dfe301c4a5 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -9,6 +9,7 @@ from typing import Any import pytest +from google.protobuf.message import DecodeError _SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" _SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) @@ -433,3 +434,65 @@ def test_the_reader_names_the_offset_of_a_record_that_runs_past_the_end() -> Non grown = _damaged(raw, "length one byte too long") with pytest.raises(ValueError, match=rf"record at {at + 1} runs 1 bytes past the end"): list(_MOD._top_level_records(grown)) + + +# Bytes after a valid index that the protobuf parser refuses. Each is a field 9 +# (tag byte 0x48 | wire type) unless the case is about the tag itself. +_REFUSED_TAILS = { + "fixed32 with one payload byte": bytes([0x4D, 0x01]), + "fixed32 with no payload": bytes([0x4D]), + "fixed64 with seven payload bytes": bytes([0x49]) + bytes(7), + "fixed64 with no payload": bytes([0x49]), + "varint that runs off the end": bytes([0x48, 0x80]), + "varint with no byte": bytes([0x48]), + "varint longer than ten bytes": bytes([0x48]) + bytes([0x80] * 10) + bytes([0x00]), + "tag that runs off the end": bytes([0x80]), + "field number 0": bytes([0x00, 0x01]), + "group that is never closed": bytes([0x4B, 0x08, 0x01]), + "group closed by another field": bytes([0x4B, 0x54]), + "end group with no start": bytes([0x4C]), + "wire type 6": bytes([0x4E]), + "wire type 7": bytes([0x4F]), + "unknown record with a long length": bytes([0x4A, 0x05, 0x01]), +} +_REFUSED = pytest.mark.parametrize("how", list(_REFUSED_TAILS)) + + +def _refused_part(how: str) -> bytes: + raw = _index_with_docs(["packages/app/src/a.ts"], ["a"]) + _REFUSED_TAILS[how] + with pytest.raises(DecodeError): + _scip_pb2().Index.FromString(raw) # the case is one the parser refuses + return raw + + +@_REFUSED +def test_the_reader_refuses_what_the_protobuf_parser_refuses(how: str) -> None: + with pytest.raises(ValueError): + list(_MOD._top_level_records(_refused_part(how))) + + +@_REFUSED +def test_merge_rejects_a_part_the_protobuf_parser_rejects(tmp_path: Path, how: str) -> None: + """A fixed-width value, varint or group cut short is as corrupt as a cut record.""" + good = tmp_path / "good.scip" + broken = tmp_path / "broken.scip" + good.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["from-lib"])) + broken.write_bytes(_refused_part(how)) + out = tmp_path / "merged.scip" + with pytest.raises(SystemExit, match=r"broken\.scip: corrupt part"): + _MOD.merge_indexes([good, broken], out) + assert not out.exists() + assert not (tmp_path / "merged.scip.tmp").exists() + + +def test_merge_accepts_a_part_with_a_balanced_unknown_group(tmp_path: Path) -> None: + """The parser skips a closed group in a field it does not know, nested or not.""" + part = tmp_path / "grouped.scip" + part.write_bytes( + _index_with_docs(["packages/app/src/a.ts"], ["a"]) + bytes([0x4B, 0x53, 0x54, 0x4C]) + ) + _scip_pb2().Index.FromString(part.read_bytes()) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + merged = _scip_pb2().Index.FromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["packages/app/src/a.ts"] diff --git a/tests/unit/test_scip_to_delta_cli.py b/tests/unit/test_scip_to_delta_cli.py index 4afbd9fa074..96539d99089 100644 --- a/tests/unit/test_scip_to_delta_cli.py +++ b/tests/unit/test_scip_to_delta_cli.py @@ -12,6 +12,7 @@ from pathlib import Path import pytest +from google.protobuf.message import DecodeError _HARNESS = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" _CONVERTER = _HARNESS / "scip_to_delta.py" @@ -365,3 +366,56 @@ def test_a_record_that_runs_past_the_end_of_the_index_fails_the_run(tmp_path: Pa assert proc.returncode != 0 assert "past the end" in proc.stderr assert not (tmp_path / "delta.json").exists() + + +# Bytes after a valid index that the protobuf parser refuses (field 9 unless the case +# is about the tag itself). +_REFUSED_TAILS = { + "fixed32 with one payload byte": bytes([0x4D, 0x01]), + "fixed32 with no payload": bytes([0x4D]), + "fixed64 with seven payload bytes": bytes([0x49]) + bytes(7), + "fixed64 with no payload": bytes([0x49]), + "varint that runs off the end": bytes([0x48, 0x80]), + "varint with no byte": bytes([0x48]), + "varint longer than ten bytes": bytes([0x48]) + bytes([0x80] * 10) + bytes([0x00]), + "tag that runs off the end": bytes([0x80]), + "field number 0": bytes([0x00, 0x01]), + "group that is never closed": bytes([0x4B, 0x08, 0x01]), + "group closed by another field": bytes([0x4B, 0x54]), + "end group with no start": bytes([0x4C]), + "wire type 6": bytes([0x4E]), + "wire type 7": bytes([0x4F]), + "unknown record with a long length": bytes([0x4A, 0x05, 0x01]), +} + + +def _convert_raw(tmp_path: Path, raw: bytes) -> subprocess.CompletedProcess[str]: + index = tmp_path / "damaged.scip" + index.write_bytes(raw) + return subprocess.run( + [sys.executable, str(_CONVERTER), "--index", str(index), "--commit", "h" * 40] + + ["--source-root", "", "--dry-run", str(tmp_path / "delta.json")], + capture_output=True, + text=True, + check=False, + ) + + +@pytest.mark.parametrize("how", list(_REFUSED_TAILS)) +def test_the_converter_refuses_what_the_protobuf_parser_refuses(tmp_path: Path, how: str) -> None: + """A fixed-width value, varint, tag or group cut short used to be skipped, so + the run converted the records before it and exited 0.""" + raw = _index(tmp_path).read_bytes() + _REFUSED_TAILS[how] + with pytest.raises(DecodeError): + _pb().Index.FromString(raw) # the case is one the parser refuses + proc = _convert_raw(tmp_path, raw) + assert proc.returncode != 0 + assert "ValueError" in proc.stderr + assert not (tmp_path / "delta.json").exists() + + +def test_the_converter_skips_a_balanced_unknown_group(tmp_path: Path) -> None: + raw = _index(tmp_path).read_bytes() + bytes([0x4B, 0x53, 0x54, 0x4C]) + _pb().Index.FromString(raw) + proc = _convert_raw(tmp_path, raw) + assert proc.returncode == 0, proc.stderr From f1205719c6b6a2730e2a5ba99d11d7d1fcb69a3c Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:52:53 +0000 Subject: [PATCH 04/10] The record reader applies the protobuf parser's tag and length bounds _top_level_records refused only field number 0. A field number of 2**29 or more, at the top level or in a group tag, is refused by the parser but was skipped here, so a part carrying one merged and converted with exit 0. Tags and length prefixes are now read as the parser reads them: a varint of at most five bytes that fits in 32 bits, which bounds the field number to 1..2**29 - 1. Value varints keep the ten-byte limit. The reserved range 19000..19999 and redundant trailing zero bytes inside the five-byte limit are accepted, as the parser accepts them. Lengths of 2**63 and above were already refused and are pinned. Behaviour was compared with the upb parser, the installed default. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 43 +++++++++------ tests/unit/test_scip_merge_indexes.py | 77 +++++++++++++++++++++++++++ tests/unit/test_scip_to_delta_cli.py | 65 ++++++++++++++++++++++ 3 files changed, 170 insertions(+), 15 deletions(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 23c3da6d4fd..2fb24da5009 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -808,12 +808,17 @@ def _top_level_records(data: bytes): Every other field is skipped the way the protobuf parser skips it, and anything the parser refuses is refused here with a ValueError: a record, - fixed-width value, varint or tag that runs past the end, a varint longer - than ten bytes, field number 0, an unbalanced group, and wire types 6 and 7. + fixed-width value, varint or tag that runs past the end, a value varint + longer than ten bytes, a tag or length varint longer than five bytes or + beyond 32 bits, a field number outside 1..2**29 - 1, an unbalanced group, + and wire types 6 and 7. Field numbers in the reserved range 19000..19999 + and redundant trailing zero bytes inside the five-byte limit are accepted, + as the parser accepts them. """ end, max_depth = len(data), 100 # the parser's own group nesting limit + max_field = (1 << 29) - 1 - def varint(p: int) -> tuple[int, int]: + def varint(p: int, max_bytes: int = 10) -> tuple[int, int]: shift = result = 0 start = p while True: @@ -825,8 +830,22 @@ def varint(p: int) -> tuple[int, int]: if not b & 0x80: return result, p shift += 7 - if shift >= 70: - raise ValueError(f"varint at {start} is longer than 10 bytes") + if shift >= 7 * max_bytes: + raise ValueError(f"varint at {start} is longer than {max_bytes} bytes") + + def word32(p: int) -> tuple[int, int]: + """A tag or a length: the parser reads it as a 32-bit varint.""" + value, after = varint(p, 5) + if value >> 32: + raise ValueError(f"varint at {p} does not fit in 32 bits") + return value, after + + def tag_at(p: int) -> tuple[int, int, int]: + tag, after = word32(p) + field = tag >> 3 + if not 1 <= field <= max_field: + raise ValueError(f"field number {field} at {p} is outside 1..{max_field}") + return field, tag & 7, after def span(p: int, size: int) -> int: if p + size > end: @@ -842,7 +861,7 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: if wire == 5: return span(p, 4) if wire == 2: - length, p = varint(p) + length, p = word32(p) return span(p, length) if wire == 3: if depth >= max_depth: @@ -850,10 +869,7 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: while True: if p >= end: raise ValueError(f"group {field} at {p} is not closed before the end") - tag, p = varint(p) - inner, inner_wire = tag >> 3, tag & 7 - if inner == 0: - raise ValueError(f"field number 0 at {p}") + inner, inner_wire, p = tag_at(p) if inner_wire == 4: if inner != field: raise ValueError(f"group {field} is closed by group {inner} at {p}") @@ -863,12 +879,9 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: pos = 0 while pos < end: - tag, pos = varint(pos) - field, wire = tag >> 3, tag & 7 - if field == 0: - raise ValueError(f"field number 0 at {pos}") + field, wire, pos = tag_at(pos) if wire == 2: # length-delimited - length, pos = varint(pos) + length, pos = word32(pos) stop = span(pos, length) payload = data[pos:stop] pos = stop diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 6dfe301c4a5..80cb38a47d7 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -455,6 +455,65 @@ def test_the_reader_names_the_offset_of_a_record_that_runs_past_the_end() -> Non "wire type 7": bytes([0x4F]), "unknown record with a long length": bytes([0x4A, 0x05, 0x01]), } + + +def _varint(n: int) -> bytes: + out = bytearray() + while True: + low, n = n & 0x7F, n >> 7 + out.append(low | (0x80 if n else 0)) + if not n: + return bytes(out) + + +def _tag(field: int, wire: int) -> bytes: + return _varint(field << 3 | wire) + + +_MAX_FIELD = (1 << 29) - 1 + +# More bytes the protobuf parser refuses: field numbers outside 1..2**29 - 1 (also in +# group tags), tags and lengths longer than five bytes or beyond 32 bits, huge lengths. +_REFUSED_TAILS.update( + { + "field number 2**29": _tag(_MAX_FIELD + 1, 2) + b"\x00", + "field number 2**29 on a varint": _tag(_MAX_FIELD + 1, 0) + b"\x01", + "field number 2**32": _tag(1 << 32, 2) + b"\x00", + "group with field number 2**29": _tag(_MAX_FIELD + 1, 3) + _tag(_MAX_FIELD + 1, 4), + "group holding field number 2**29": ( + _tag(9, 3) + _tag(_MAX_FIELD + 1, 0) + b"\x01" + _tag(9, 4) + ), + "tag of six bytes": b"\xc8\x80\x80\x80\x80\x00\x01", + "tag of ten bytes": b"\xc8" + b"\x80" * 8 + b"\x00\x01", + "tag of five bytes beyond 32 bits": b"\xc8\xff\xff\xff\x1f\x01", + "length of six bytes": _tag(9, 2) + b"\x80" * 5 + b"\x00", + "length of ten bytes": _tag(9, 2) + b"\x80" * 9 + b"\x00", + "length of five bytes beyond 32 bits": _tag(9, 2) + b"\x80\x80\x80\x80\x10", + "length 2**63": _tag(9, 2) + _varint(1 << 63), + "length 2**64 - 1": _tag(9, 2) + _varint((1 << 64) - 1), + "group tag of six bytes inside a group": ( + _tag(9, 3) + b"\xc8\x80\x80\x80\x80\x00\x01" + _tag(9, 4) + ), + } +) + +# Bytes the parser accepts and skips: the reserved range 19000..19999, the largest +# field number, and redundant trailing zero bytes within five bytes. +_ACCEPTED_TAILS = { + "largest field number": _tag(_MAX_FIELD, 2) + b"\x00", + "largest field number on a varint": _tag(_MAX_FIELD, 0) + b"\x01", + "group with the largest field number": _tag(_MAX_FIELD, 3) + _tag(_MAX_FIELD, 4), + "reserved field 19000": _tag(19000, 2) + b"\x00", + "reserved field 19999 on a varint": _tag(19999, 0) + b"\x01", + "group holding a reserved field": _tag(9, 3) + _tag(19500, 0) + b"\x01" + _tag(9, 4), + "tag with one redundant zero byte": b"\xc8\x00\x01", + "tag padded to five bytes": b"\xc8\x80\x80\x80\x00\x01", + "end group tag padded": _tag(9, 3) + b"\xcc\x00", + "length padded to five bytes": _tag(9, 2) + b"\x81\x80\x80\x80\x00" + b"x", + "length with one redundant zero byte": _tag(9, 2) + b"\x81\x00" + b"x", +} + + _REFUSED = pytest.mark.parametrize("how", list(_REFUSED_TAILS)) @@ -496,3 +555,21 @@ def test_merge_accepts_a_part_with_a_balanced_unknown_group(tmp_path: Path) -> N _MOD.merge_indexes([part], out) merged = _scip_pb2().Index.FromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/app/src/a.ts"] + + +@pytest.mark.parametrize("how", list(_ACCEPTED_TAILS)) +def test_the_reader_accepts_what_the_protobuf_parser_accepts(how: str) -> None: + raw = _index_with_docs(["packages/app/src/a.ts"], ["a"]) + _ACCEPTED_TAILS[how] + _scip_pb2().Index.FromString(raw) # the case is one the parser accepts + assert [f for f, _ in _MOD._top_level_records(raw)][:2] == [1, 2] + + +@pytest.mark.parametrize("how", list(_ACCEPTED_TAILS)) +def test_merge_keeps_a_part_the_protobuf_parser_accepts(tmp_path: Path, how: str) -> None: + part = tmp_path / "part.scip" + part.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["a"]) + _ACCEPTED_TAILS[how]) + _scip_pb2().Index.FromString(part.read_bytes()) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + merged = _scip_pb2().Index.FromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["packages/app/src/a.ts"] diff --git a/tests/unit/test_scip_to_delta_cli.py b/tests/unit/test_scip_to_delta_cli.py index 96539d99089..cbdd0d5fe8d 100644 --- a/tests/unit/test_scip_to_delta_cli.py +++ b/tests/unit/test_scip_to_delta_cli.py @@ -389,6 +389,63 @@ def test_a_record_that_runs_past_the_end_of_the_index_fails_the_run(tmp_path: Pa } +def _varint(n: int) -> bytes: + out = bytearray() + while True: + low, n = n & 0x7F, n >> 7 + out.append(low | (0x80 if n else 0)) + if not n: + return bytes(out) + + +def _tag(field: int, wire: int) -> bytes: + return _varint(field << 3 | wire) + + +_MAX_FIELD = (1 << 29) - 1 + +# More bytes the protobuf parser refuses: field numbers outside 1..2**29 - 1 (also in +# group tags), tags and lengths longer than five bytes or beyond 32 bits, huge lengths. +_REFUSED_TAILS.update( + { + "field number 2**29": _tag(_MAX_FIELD + 1, 2) + b"\x00", + "field number 2**29 on a varint": _tag(_MAX_FIELD + 1, 0) + b"\x01", + "field number 2**32": _tag(1 << 32, 2) + b"\x00", + "group with field number 2**29": _tag(_MAX_FIELD + 1, 3) + _tag(_MAX_FIELD + 1, 4), + "group holding field number 2**29": ( + _tag(9, 3) + _tag(_MAX_FIELD + 1, 0) + b"\x01" + _tag(9, 4) + ), + "tag of six bytes": b"\xc8\x80\x80\x80\x80\x00\x01", + "tag of ten bytes": b"\xc8" + b"\x80" * 8 + b"\x00\x01", + "tag of five bytes beyond 32 bits": b"\xc8\xff\xff\xff\x1f\x01", + "length of six bytes": _tag(9, 2) + b"\x80" * 5 + b"\x00", + "length of ten bytes": _tag(9, 2) + b"\x80" * 9 + b"\x00", + "length of five bytes beyond 32 bits": _tag(9, 2) + b"\x80\x80\x80\x80\x10", + "length 2**63": _tag(9, 2) + _varint(1 << 63), + "length 2**64 - 1": _tag(9, 2) + _varint((1 << 64) - 1), + "group tag of six bytes inside a group": ( + _tag(9, 3) + b"\xc8\x80\x80\x80\x80\x00\x01" + _tag(9, 4) + ), + } +) + +# Bytes the parser accepts and skips: the reserved range 19000..19999, the largest +# field number, and redundant trailing zero bytes within five bytes. +_ACCEPTED_TAILS = { + "largest field number": _tag(_MAX_FIELD, 2) + b"\x00", + "largest field number on a varint": _tag(_MAX_FIELD, 0) + b"\x01", + "group with the largest field number": _tag(_MAX_FIELD, 3) + _tag(_MAX_FIELD, 4), + "reserved field 19000": _tag(19000, 2) + b"\x00", + "reserved field 19999 on a varint": _tag(19999, 0) + b"\x01", + "group holding a reserved field": _tag(9, 3) + _tag(19500, 0) + b"\x01" + _tag(9, 4), + "tag with one redundant zero byte": b"\xc8\x00\x01", + "tag padded to five bytes": b"\xc8\x80\x80\x80\x00\x01", + "end group tag padded": _tag(9, 3) + b"\xcc\x00", + "length padded to five bytes": _tag(9, 2) + b"\x81\x80\x80\x80\x00" + b"x", + "length with one redundant zero byte": _tag(9, 2) + b"\x81\x00" + b"x", +} + + def _convert_raw(tmp_path: Path, raw: bytes) -> subprocess.CompletedProcess[str]: index = tmp_path / "damaged.scip" index.write_bytes(raw) @@ -419,3 +476,11 @@ def test_the_converter_skips_a_balanced_unknown_group(tmp_path: Path) -> None: _pb().Index.FromString(raw) proc = _convert_raw(tmp_path, raw) assert proc.returncode == 0, proc.stderr + + +@pytest.mark.parametrize("how", list(_ACCEPTED_TAILS)) +def test_the_converter_accepts_what_the_protobuf_parser_accepts(tmp_path: Path, how: str) -> None: + raw = _index(tmp_path).read_bytes() + _ACCEPTED_TAILS[how] + _pb().Index.FromString(raw) + proc = _convert_raw(tmp_path, raw) + assert proc.returncode == 0, proc.stderr From 0267d571370f7675ce71eaf098473d47a1db07a8 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 05:05:35 +0000 Subject: [PATCH 05/10] The record reader keeps the last value of a singular field _document_path returned the first relative_path record in a document. The protobuf parser keeps the last value of a singular field, so a document carrying pkg/first.ts then pkg/second.ts is pkg/second.ts, and the merge treated it as pkg/first.ts and dropped a separate pkg/first.ts document as its duplicate. The converter shares the reader and ordered, filtered and deduplicated by the wrong path. _document_path now returns the last relative_path. Metadata is the other singular field read from raw records: the parser merges repeated metadata records, but _project_root used the first and the merge copied only the last. _project_root now merges every metadata record before the first document, and the merge copies every metadata record of the first part. Document, symbol and occurrence fields are parsed by the protobuf runtime and need no change. Each reader is compared with the parser on the same bytes. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 11 +-- scripts/scip_harness/scip_to_delta.py | 27 +++--- tests/unit/test_scip_merge_indexes.py | 99 ++++++++++++++++++++++ 3 files changed, 120 insertions(+), 17 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index b30eab0aaef..f12f4b6c1c7 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -9,7 +9,8 @@ project references. Sibling tsconfigs in the same directory share a scope, so each keeps the documents it emitted and a path present in more than one of those indexes keeps the last copy. Metadata is taken from -the first non-empty input. External +the first non-empty input, every metadata record in it, as the parser +merges them. External symbols are concatenated. An all-empty input list, or only empty files, writes a zero-byte output so the converter treats it as an empty index. @@ -116,7 +117,7 @@ def merge_indexes( if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") owners = known_projects if known_projects is not None else (projects or []) - metadata = None + metadata: list[Any] = [] documents: dict[str, Any] = {} external_symbols: list[Any] = [] has_payload = False @@ -128,7 +129,7 @@ def merge_indexes( try: for field, payload in _top_level_records(data): if field == _METADATA and not has_payload: - metadata = payload + metadata.append(payload) elif field == _DOCUMENT: rel = _document_path(payload) if project is None or _keeps(project, rel, owners): @@ -145,8 +146,8 @@ def merge_indexes( try: with open(tmp, "wb") as out: if has_payload: - if metadata is not None: - _write_record(out, _METADATA, metadata) + for payload in metadata: + _write_record(out, _METADATA, payload) for payload in documents.values(): _write_record(out, _DOCUMENT, payload) for payload in external_symbols: diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 2fb24da5009..559175615d4 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -892,11 +892,13 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: def _document_path(payload) -> str: """A serialized Document's relative_path (field 1), read without parsing - its occurrences.""" + its occurrences. A singular field written more than once takes its last + value, as the protobuf parser takes it.""" + path = b"" for field, value in _top_level_records(payload): if field == 1: - return bytes(value).decode("utf-8", "replace") - return "" + path = bytes(value) + return path.decode("utf-8", "replace") def _stream_documents(data, scip_pb2, *, paths: set[str] | None = None, ordered: bool = False): @@ -939,18 +941,19 @@ def _index_scheme(data: bytes, scip_pb2) -> str: def _project_root(data: bytes, scip_pb2) -> Path | None: """The checkout the index was produced from (Index.metadata.project_root, - a file:// URI), or None when the metadata record is absent.""" + a file:// URI), or None when the metadata record is absent. Metadata + records before the first document merge into one message, as the protobuf + parser merges a repeated singular message.""" + md = scip_pb2.Metadata() for field, payload in _top_level_records(data): if field == 1: - md = scip_pb2.Metadata() - md.ParseFromString(payload) - root = str(md.project_root or "") - if root.startswith("file://"): - root = root[len("file://") :] - return Path(root) if root else None - if field == 2: + md.MergeFromString(payload) + elif field == 2: break # metadata precedes documents; do not scan the whole index - return None + root = str(md.project_root or "") + if root.startswith("file://"): + root = root[len("file://") :] + return Path(root) if root else None # The parser tier's generated-file rule, harness-side: Go's generated-file header diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 80cb38a47d7..bf2897bf7c6 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -573,3 +573,102 @@ def test_merge_keeps_a_part_the_protobuf_parser_accepts(tmp_path: Path, how: str _MOD.merge_indexes([part], out) merged = _scip_pb2().Index.FromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/app/src/a.ts"] + + +def _record(field: int, payload: bytes, wire: int = 2) -> bytes: + return _tag(field, wire) + (_varint(len(payload)) if wire == 2 else b"") + payload + + +def _path_record(*paths: str) -> bytes: + """One document record whose relative_path (field 1) is written once per path.""" + return _record(2, b"".join(_record(1, p.encode()) for p in paths)) + + +_REPEATED_PATH_DOCS = { + "two paths then the first again": [("pkg/first.ts", "pkg/second.ts"), ("pkg/first.ts",)], + "two paths, the second alone": [("pkg/first.ts", "pkg/second.ts"), ("pkg/second.ts",)], + "three paths": [("a.ts", "b.ts", "c.ts")], +} + + +@pytest.mark.parametrize("how", list(_REPEATED_PATH_DOCS)) +def test_merge_keys_a_document_by_the_last_relative_path_the_parser_keeps( + tmp_path: Path, how: str +) -> None: + """A singular field written twice takes its last value, as the parser takes it.""" + raw = b"".join(_path_record(*paths) for paths in _REPEATED_PATH_DOCS[how]) + parsed = _scip_pb2().Index.FromString(raw) + part = tmp_path / "part.scip" + part.write_bytes(raw) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + merged = _scip_pb2().Index.FromString(out.read_bytes()) + expected = {d.relative_path: d for d in parsed.documents} # last copy of a path wins + assert {d.relative_path for d in merged.documents} == set(expected) + assert len(merged.documents) == len(expected) + + +def test_merge_keeps_both_documents_of_the_reviewers_pair(tmp_path: Path) -> None: + """One document carrying first.ts then second.ts is second.ts; a separate + first.ts is another file. The merge keeps both.""" + raw = _path_record("pkg/first.ts", "pkg/second.ts") + _path_record("pkg/first.ts") + assert [d.relative_path for d in _scip_pb2().Index.FromString(raw).documents] == [ + "pkg/second.ts", + "pkg/first.ts", + ] + part = tmp_path / "part.scip" + part.write_bytes(raw) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + merged = _scip_pb2().Index.FromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["pkg/second.ts", "pkg/first.ts"] + + +_DOCUMENT_PATH_PAYLOADS = { + "no path": b"", + "one path": _record(1, b"a.ts"), + "last of two": _record(1, b"a.ts") + _record(1, b"b.ts"), + "last of three around another field": ( + _record(1, b"a.ts") + _record(5, b"text") + _record(1, b"b.ts") + _record(1, b"c.ts") + ), + "an empty last path": _record(1, b"a.ts") + _record(1, b""), + "a varint on field 1 is not the path": _record(1, b"a.ts") + _record(1, b"\x05", wire=0), + "a varint on field 1 alone": _record(1, b"\x05", wire=0), +} + + +@pytest.mark.parametrize("how", list(_DOCUMENT_PATH_PAYLOADS)) +def test_document_path_is_what_the_protobuf_parser_reads(how: str) -> None: + payload = _DOCUMENT_PATH_PAYLOADS[how] + doc = _scip_pb2().Document.FromString(payload) + assert _MOD._document_path(payload) == doc.relative_path + + +_REPEATED_METADATA = { + "project_root twice": _record(1, _record(3, b"file:///a")) + + _record(1, _record(3, b"file:///b")), + "the later record sets other fields": ( + _record(1, _record(3, b"file:///a")) + _record(1, _record(1, b"\x01", wire=0)) + ), + "tool info then project_root": ( + _record(1, _record(2, _record(1, b"scip-typescript"))) + + _record(1, _record(3, b"file:///c")) + ), +} + + +@pytest.mark.parametrize("how", list(_REPEATED_METADATA)) +def test_the_converter_and_merge_read_repeated_metadata_as_the_parser_does( + tmp_path: Path, how: str +) -> None: + raw = _REPEATED_METADATA[how] + _path_record("a.ts") + parsed = _scip_pb2().Index.FromString(raw) + root = parsed.metadata.project_root + assert _MOD._converter._project_root(raw, _scip_pb2()) == ( + Path(root.removeprefix("file://")) if root else None + ) + part = tmp_path / "part.scip" + part.write_bytes(raw) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + assert _scip_pb2().Index.FromString(out.read_bytes()).metadata == parsed.metadata From 1c0d2ba179922465a349c2ee20f68af70c474ef6 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 05:25:59 +0000 Subject: [PATCH 06/10] Pin the ten-byte value varint the record reader accepts A value varint of ten bytes is accepted whatever its tenth byte holds. The protobuf parser (upb, and the pure-Python backend) accepts it, so a part with such a trailing unknown varint parses whole and merges the same way. Tag and length varints are bounded at five bytes and refused beyond, as the parser refuses them. The reader already matches, so this adds tests only: a value varint ending in 0x00, 0x01, 0x02 or 0x7f, at top level and inside a group, is accepted by the reader and the merge, each compared with the parser. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- tests/unit/test_scip_merge_indexes.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index bf2897bf7c6..eb18da4d165 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -513,6 +513,15 @@ def _tag(field: int, wire: int) -> bytes: "length with one redundant zero byte": _tag(9, 2) + b"\x81\x00" + b"x", } +# A value varint of ten bytes is accepted whatever its tenth byte holds (upb and the +# pure-Python backend agree); an eleventh byte is refused above. +for _last in (0x00, 0x01, 0x02, 0x7F): + _ten = b"\xff" * 9 + bytes([_last]) + _ACCEPTED_TAILS[f"value varint of ten bytes ending 0x{_last:02x}"] = _tag(9, 0) + _ten + _ACCEPTED_TAILS[f"group value varint of ten bytes ending 0x{_last:02x}"] = ( + _tag(9, 3) + _tag(9, 0) + _ten + _tag(9, 4) + ) + _REFUSED = pytest.mark.parametrize("how", list(_REFUSED_TAILS)) From c3ed4e4c23271f673d8015845ae8bb09c139a6aa Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 06:48:06 +0000 Subject: [PATCH 07/10] Key merged documents by their raw path bytes The merge keyed documents by the relative_path decoded with replacement, so two paths that differ only by a malformed byte and a literal U+FFFD collapsed to one key and the later document replaced the earlier one. Reversing the inputs dropped the other document. The merge now keys on the raw path bytes (the last value of field 1) and decodes the path only to ask which project owns it. Ownership is unchanged: both names decode to the same text, so both get the same answer. scip_to_delta gains _document_path_bytes; _document_path decodes it as before. The new test merges a document named with a 0xff byte and one named with U+FFFD, in both input orders, with and without a project; both survive. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 18 +++++++++----- scripts/scip_harness/scip_to_delta.py | 15 ++++++++---- tests/unit/test_scip_merge_indexes.py | 28 ++++++++++++++++++++++ 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index f12f4b6c1c7..20d959a218a 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -15,9 +15,10 @@ writes a zero-byte output so the converter treats it as an empty index. The merge reads only the top-level records and each document's -relative_path, and copies the records it keeps byte for byte. Nothing is -decoded, so a document python-protobuf would refuse (a string field that -is not UTF-8) reaches the converter, which decides what to do with it. A +relative_path, and copies the records it keeps byte for byte. Documents +are told apart by the raw path bytes; the path is decoded only to ask which +project owns it. A document python-protobuf would refuse (a string field +that is not UTF-8) reaches the converter, which decides what to do with it. A record, fixed-width value, varint, tag or group that the protobuf parser would refuse is corrupt: the merge stops and names the part, as the whole-index parse used to. @@ -51,6 +52,7 @@ def _load_harness_module(name: str) -> Any: _read_index = _converter._read_index _top_level_records = _converter._top_level_records _document_path = _converter._document_path +_document_path_bytes = _converter._document_path_bytes _METADATA, _DOCUMENT, _EXTERNAL_SYMBOL = 1, 2, 3 @@ -118,7 +120,7 @@ def merge_indexes( raise SystemExit("--project count must match the number of indexes") owners = known_projects if known_projects is not None else (projects or []) metadata: list[Any] = [] - documents: dict[str, Any] = {} + documents: dict[bytes, Any] = {} external_symbols: list[Any] = [] has_payload = False for i, path in enumerate(paths): @@ -131,9 +133,13 @@ def merge_indexes( if field == _METADATA and not has_payload: metadata.append(payload) elif field == _DOCUMENT: - rel = _document_path(payload) + # Key on the raw bytes: two names that differ only by a + # malformed byte and a literal U+FFFD decode alike but are + # two documents. Ownership reads the decoded text. + raw = _document_path_bytes(payload) + rel = raw.decode("utf-8", "replace") if project is None or _keeps(project, rel, owners): - documents[rel] = payload + documents[raw] = payload elif field == _EXTERNAL_SYMBOL: external_symbols.append(payload) except ValueError as e: diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 559175615d4..f40b12aa1e4 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -890,15 +890,20 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: pos = skip(pos, wire, field, 0) -def _document_path(payload) -> str: - """A serialized Document's relative_path (field 1), read without parsing - its occurrences. A singular field written more than once takes its last - value, as the protobuf parser takes it.""" +def _document_path_bytes(payload: bytes | memoryview) -> bytes: + """A serialized Document's relative_path (field 1) as the raw bytes, read + without parsing its occurrences. A singular field written more than once + takes its last value, as the protobuf parser takes it.""" path = b"" for field, value in _top_level_records(payload): if field == 1: path = bytes(value) - return path.decode("utf-8", "replace") + return path + + +def _document_path(payload) -> str: + """The relative_path as text; a malformed byte reads as U+FFFD.""" + return _document_path_bytes(payload).decode("utf-8", "replace") def _stream_documents(data, scip_pb2, *, paths: set[str] | None = None, ordered: bool = False): diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index eb18da4d165..0ad7ed43c3d 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -633,6 +633,34 @@ def test_merge_keeps_both_documents_of_the_reviewers_pair(tmp_path: Path) -> Non assert [d.relative_path for d in merged.documents] == ["pkg/second.ts", "pkg/first.ts"] +@pytest.mark.parametrize("reverse", [False, True], ids=["malformed first", "literal first"]) +@pytest.mark.parametrize("projects", [None, ["pkg"]], ids=["no project", "owned by pkg"]) +def test_merge_keeps_paths_that_differ_only_by_a_malformed_byte( + tmp_path: Path, reverse: bool, projects: list[str] | None +) -> None: + """A path with a stray 0xff byte decodes to the same text as one with a + literal U+FFFD. They are two documents; the merge keeps both, in either + input order. Ownership still reads the decoded text, which is the same + for both.""" + malformed = _record(2, _record(1, b"pkg/a\xff.ts")) + literal = _record(2, _record(1, "pkg/a\ufffd.ts".encode())) + inputs = [literal, malformed] if reverse else [malformed, literal] + parts = [] + for i, raw in enumerate(inputs): + part = tmp_path / f"part{i}.scip" + part.write_bytes(raw) + parts.append(part) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + parts, + out, + projects=None if projects is None else projects * len(parts), + known_projects=projects, + ) + kept = [bytes(p) for field, p in _MOD._top_level_records(out.read_bytes()) if field == 2] + assert kept == [raw[2:] for raw in inputs] # a two-byte record header, then the payload + + _DOCUMENT_PATH_PAYLOADS = { "no path": b"", "one path": _record(1, b"a.ts"), From d958be34067ff24df5615b8d2d662f89867e90a5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 06:49:08 +0000 Subject: [PATCH 08/10] Type the raw path reader as bytes mypy on the two modules stays at its baseline of 54 errors. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index f40b12aa1e4..a8cccb76df6 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -890,7 +890,7 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: pos = skip(pos, wire, field, 0) -def _document_path_bytes(payload: bytes | memoryview) -> bytes: +def _document_path_bytes(payload: bytes) -> bytes: """A serialized Document's relative_path (field 1) as the raw bytes, read without parsing its occurrences. A singular field written more than once takes its last value, as the protobuf parser takes it.""" From 4f34de0f1185717054474051ed600db25df0f2ba Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 07:35:48 +0000 Subject: [PATCH 09/10] Return the merge's kept paths as text The merge keys its documents on raw bytes, so a caller that matches the kept set against member paths (text) would never find a path in it. merge_indexes now returns the kept paths decoded with "replace", the same text ownership reads, and deduplication still runs on the bytes. The unused `_document_path` alias is gone; the one test that read the converter's function through it names the converter. Assisted-by: Claude Code:claude-sonnet-5-5 Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 5 +++-- tests/unit/test_scip_merge_indexes.py | 15 ++++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 20d959a218a..485c01142ba 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -51,7 +51,6 @@ def _load_harness_module(name: str) -> Any: _converter = _load_harness_module("scip_to_delta") _read_index = _converter._read_index _top_level_records = _converter._top_level_records -_document_path = _converter._document_path _document_path_bytes = _converter._document_path_bytes _METADATA, _DOCUMENT, _EXTERNAL_SYMBOL = 1, 2, 3 @@ -115,7 +114,8 @@ def merge_indexes( output: Path, projects: list[str] | None = None, known_projects: list[str] | None = None, -) -> None: +) -> set[str]: + """Write the merged index; return the paths whose document it holds, as text.""" if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") owners = known_projects if known_projects is not None else (projects or []) @@ -162,6 +162,7 @@ def merge_indexes( except BaseException: tmp.unlink(missing_ok=True) raise + return {raw.decode("utf-8", "replace") for raw in documents} def main(argv: list[str] | None = None) -> int: diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 0ad7ed43c3d..360416d6ff4 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -678,7 +678,7 @@ def test_merge_keeps_paths_that_differ_only_by_a_malformed_byte( def test_document_path_is_what_the_protobuf_parser_reads(how: str) -> None: payload = _DOCUMENT_PATH_PAYLOADS[how] doc = _scip_pb2().Document.FromString(payload) - assert _MOD._document_path(payload) == doc.relative_path + assert _MOD._converter._document_path(payload) == doc.relative_path _REPEATED_METADATA = { @@ -709,3 +709,16 @@ def test_the_converter_and_merge_read_repeated_metadata_as_the_parser_does( out = tmp_path / "merged.scip" _MOD.merge_indexes([part], out) assert _scip_pb2().Index.FromString(out.read_bytes()).metadata == parsed.metadata + + +def test_merge_returns_the_kept_paths_as_text(tmp_path: Path) -> None: + """The paths a caller matches against its own member paths are text, while the + merge keys its documents on raw bytes: a stray 0xff byte reads as U+FFFD.""" + plain = tmp_path / "plain.scip" + plain.write_bytes(_index_with_docs(["pkg/a.ts"])) + odd = tmp_path / "odd.scip" + odd.write_bytes(_record(2, _record(1, b"pkg/b\xff.ts"))) + out = tmp_path / "merged.scip" + kept = _MOD.merge_indexes([plain, odd], out) + assert kept == {"pkg/a.ts", "pkg/b\ufffd.ts"} + assert all(isinstance(path, str) for path in kept) From cdc76feb675900c97e30a5df776be3b71424ff93 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 08:55:54 +0000 Subject: [PATCH 10/10] Write the merged index through a unique temporary file An input named .tmp was truncated when the merge opened its temporary output, and removed on an error. Create the temporary beside the output with exclusive creation under a fresh name, then replace the output once the write succeeds. Assisted-by: Claude Code Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 9 ++++++--- tests/unit/test_scip_merge_indexes.py | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 485c01142ba..bd3f7cf12ea 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -29,6 +29,7 @@ import argparse import importlib.util import os +import tempfile from pathlib import Path from typing import Any, BinaryIO @@ -147,10 +148,12 @@ def merge_indexes( has_payload = True # The parts stay mapped while the output is written, so write beside the # output and swap it in; truncating an input that is also the output would - # pull the mapped pages away. - tmp = output.with_name(output.name + ".tmp") + # pull the mapped pages away. The temporary is created exclusively under a + # fresh name, so it can never be one of the inputs. + fd, tmp_name = tempfile.mkstemp(dir=output.parent, prefix=output.name + ".", suffix=".tmp") + tmp = Path(tmp_name) try: - with open(tmp, "wb") as out: + with os.fdopen(fd, "wb") as out: if has_payload: for payload in metadata: _write_record(out, _METADATA, payload) diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 360416d6ff4..a28a229e618 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -722,3 +722,25 @@ def test_merge_returns_the_kept_paths_as_text(tmp_path: Path) -> None: kept = _MOD.merge_indexes([plain, odd], out) assert kept == {"pkg/a.ts", "pkg/b\ufffd.ts"} assert all(isinstance(path, str) for path in kept) + + +def test_merge_does_not_truncate_an_input_named_like_the_temporary(tmp_path: Path) -> None: + first = tmp_path / "result.scip.tmp" + second = tmp_path / "second.scip" + first.write_bytes(_index_with_docs(["packages/app/src/a.ts"])) + second.write_bytes(_index_with_docs(["packages/lib/src/b.ts"])) + before = first.read_bytes() + out = tmp_path / "result.scip" + _MOD.merge_indexes([first, second], out) + assert first.read_bytes() == before + merged = _scip_pb2().Index() + merged.ParseFromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == [ + "packages/app/src/a.ts", + "packages/lib/src/b.ts", + ] + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "result.scip", + "result.scip.tmp", + "second.scip", + ]