diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index c4a32d9fb21..bd3f7cf12ea 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -9,49 +9,52 @@ 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. + +The merge reads only the top-level records and each document's +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. """ from __future__ import annotations import argparse import importlib.util -import sys +import os +import tempfile 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_bytes = _converter._document_path_bytes - -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,57 +78,94 @@ 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, 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") - 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: list[Any] = [] + documents: dict[bytes, 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) + try: + for field, payload in _top_level_records(data): + if field == _METADATA and not has_payload: + metadata.append(payload) + elif field == _DOCUMENT: + # 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[raw] = payload + elif field == _EXTERNAL_SYMBOL: + external_symbols.append(payload) + except ValueError as e: + raise SystemExit(f"{path}: corrupt part: {e}") from e 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. 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 os.fdopen(fd, "wb") as out: + if has_payload: + for payload in metadata: + _write_record(out, _METADATA, payload) + 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 + return {raw.decode("utf-8", "replace") for raw in documents} def main(argv: list[str] | None = None) -> int: diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index d4777f7e10d..a8cccb76df6 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -804,44 +804,106 @@ 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) - - def varint(p: int) -> tuple[int, int]: + 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 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, max_bytes: int = 10) -> 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 >= 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: + 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 = word32(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") + 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}") + 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 + field, wire, pos = tag_at(pos) if wire == 2: # length-delimited - length, pos = varint(pos) - payload = data[pos : pos + length] - pos += length + length, pos = word32(pos) + 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: - """A serialized Document's relative_path (field 1), read without parsing - its occurrences.""" +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.""" + 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 + + +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): @@ -884,18 +946,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 45c2990217f..a28a229e618 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -2,17 +2,30 @@ from __future__ import annotations +import importlib import importlib.util +import sys from pathlib import Path +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) _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 +45,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 +80,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 +97,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 +120,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 +142,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 +165,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 +183,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 +196,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 +219,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 +244,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 +264,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 +296,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 +325,422 @@ 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() + + +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)) + + +# 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]), +} + + +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", +} + +# 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)) + + +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"] + + +@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"] + + +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"] + + +@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"), + "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._converter._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 + + +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) + + +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", + ] diff --git a/tests/unit/test_scip_to_delta_cli.py b/tests/unit/test_scip_to_delta_cli.py index 1e74c15ae35..cbdd0d5fe8d 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" @@ -344,3 +345,142 @@ 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() + + +# 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 _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) + 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 + + +@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