Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 99 additions & 59 deletions scripts/scip_harness/scip_merge_indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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):
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
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:
Expand Down
125 changes: 94 additions & 31 deletions scripts/scip_harness/scip_to_delta.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
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):
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading