diff --git a/docs/dev/scripts/itl_1347/README.md b/docs/dev/scripts/itl_1347/README.md new file mode 100644 index 000000000..03843795d --- /dev/null +++ b/docs/dev/scripts/itl_1347/README.md @@ -0,0 +1,53 @@ +# ITL-1347 measurement and differential harness + +Scripts for the stages of `docs/dev/specs/itl-1347-job-table-transport.md`. None of them +changes the library. They use only the public API, except where `instrument.py` wraps +internals for the duration of a block. + +| Script | What it does | +|---|---| +| `instrument.py` | `counting()`: datagrams made, by node kind and class; `_rows_to_table` calls, rows and seconds, by caller; node `execute` / `async_execute` calls and inclusive seconds. `edges_per_node(job)`. | +| `fixtures.py` | Fixture jobs on the tutorial dataset: `tutorial` (the tutorial's pipeline) and `spikes` (one row per spike, every operator kind once, a side effect). `ITL1347_SPIKES_MAX` limits the spike rows for a quick check. | +| `dump.py` | Runs one fixture in one mode (`cold`, `warm`, `held`, `load_only`) on one orchestrator, and dumps the run summary, the warnings, a recording observer's events, every node's `as_table(all_info=True)`, every stored table and its Delta version count, peak RSS and wall time. | +| `compare.py` | Compares two dumps: `--mode exact` (byte for byte, row order included) or `--mode set` (rows as a multiset, columns by name). Floats are compared by their bits (Arrow's `equals` holds NaN unequal to itself). `--calibrate` finds the volatile columns (values a run makes afresh: a `uuid7` datagram id, a write time, the source-info tokens that embed them) from two dumps of the same checkout. Those, and `__pf_var_git_hash` (the checkout's git state), are the only columns left out. Observer events are compared node by node, because `main` starts independent nodes in an order that varies between runs. | +| `differential.py` | Runs the whole differential: every fixture, mode, orchestrator and Polars thread count, under two interpreters, then the three comparisons. `--compare-only` redoes the comparisons on existing dumps. | +| `join_order_plugin.py` | A pytest plugin (ITL-1357, report only): every Polars inner join without `maintain_order` is recomputed with `maintain_order="left_right"` and the row orders are compared. | + +## The differential (each stage's gate) + +1. Build one environment per Orcapod under test, from a built wheel: pinned `main` and the + stage branch. `uv run --with ` can reuse a cached build of the same version + string, so install each wheel into its own environment and check the version and file + it imports before measuring. +2. For each fixture, mode, orchestrator and Polars thread count (`POLARS_MAX_THREADS=1` and + the default), run `dump.py` with each environment's interpreter, in its own work + directory. A `warm` or `load_only` dump runs in the work directory a `cold` dump left. +3. Calibrate the volatile columns from two dumps of the same environment. +4. Compare: + - sync on the branch against sync on `main`, `--mode exact`; + - async on the branch against sync on the branch, `--mode set`; + - async on the branch against async on `main`, `--mode set`. + + Only the differences the spec lists by name may remain. + +Outputs are raw records: keep them outside the repository. + +## What stage 5 adds to the differential + +The spec's gate (section "Proof", item 3) is complete. This harness implements what stages +1–4 need: sync against pinned `main` byte for byte, async against sync and against `main`'s +async as multisets. Stage 5, where `Batch` and order-dependent `PolarsFilter` see arrival +orders the sync run never produces, adds the recorded-arrival checks: + +1. **The arrival-dependent set**: every `Batch`, or `PolarsFilter` with an order-dependent + predicate, whose input arrived in another order than on sync in either async run (the + branch's or `main`'s), together with all its descendants in the job's graph. +2. **Recorded arrivals**: for each node in the set, the rows of each input in the order the + node received them. Record them by wrapping the node's input channels, with no library + change. +3. **Per-node consistency**: recompute the node with pinned `main`'s operator, on the sync + path, over those recorded inputs in that order. The node's async output must equal the + recomputation as a multiset, apart from the spec's named differences. +4. **Edge conservation**: on every edge into or inside the set, the recorded input rows + equal the producer's output rows in the same run, as a multiset with multiplicity. +5. **Everything outside the set** is compared as above. diff --git a/docs/dev/scripts/itl_1347/compare.py b/docs/dev/scripts/itl_1347/compare.py new file mode 100644 index 000000000..6ac088422 --- /dev/null +++ b/docs/dev/scripts/itl_1347/compare.py @@ -0,0 +1,252 @@ +"""ITL-1347 differential, the comparison: two dumps of ``dump.py``, exactly or as sets. + + uv run python compare.py --mode exact|set [--volatile volatile.json] + uv run python compare.py --calibrate volatile.json + +- ``exact`` (sync branch against sync pinned ``main``): every node table and stored table is + equal byte for byte (``Table.equals(check_metadata=True)`` on combined chunks, schemas + field by field), the row order included. The same holds for the run summary, the errors, + the warnings, the observer events and the Delta version counts. Only the volatile columns + are left out of the value comparison. Their schema and null pattern are still compared. +- ``set`` (async against sync): the same, except that rows are compared as a multiset, with + columns matched by name; observer events are compared as a multiset too. +- ``--calibrate``: compares two dumps of the **same** checkout and writes the columns whose + values differ between them (identifiers and timestamps a run makes, such as a ``uuid7`` + datagram id or a write time) to ``volatile.json``. Only those columns are ever left out. + +Exit status 0 when equal, 3 when the comparison completed and found differences (every +difference is printed). Any other status (Python's 1 on an uncaught error) means the +comparison could not complete. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any + +import pyarrow as pa + + +def _read(path: Path) -> pa.Table: + with pa.memory_map(str(path), "r") as source: + return pa.ipc.open_file(source).read_all().combine_chunks() + + +# Columns whose value depends on the environment, not on the code under test: the git +# state of the file a function is defined in (``-dirty``, ``-untracked``), which changes +# whenever a file is added to the checkout during a run. Left out like volatile columns. +ENVIRONMENT_COLUMNS = frozenset({"__pf_var_git_hash"}) + + +# The exit status of a completed comparison that found differences. It is distinct from +# Python's 1 for an uncaught error, so a caller can tell the two apart. +DIFFERENCES_FOUND = 3 + + +def _events_by_node(events: list[Any]) -> dict[str, list[str]]: + """Each node's events, in order; run-level events under ``""``. + + The order in which ``main`` starts independent nodes (two sources, say) varies from one + process to the next, so only each node's own sequence of events is a result. + """ + grouped: dict[str, list[str]] = {} + for event in events: + label = event[1] if len(event) > 1 else "" + grouped.setdefault(label, []).append(json.dumps(event)) + return grouped + + +def _tables(dump: Path) -> dict[str, pa.Table]: + manifest = json.loads((dump / "manifest.json").read_text()) + found: dict[str, pa.Table] = {} + for group in ("nodes", "stored"): + for name, entry in manifest[group].items(): + if "file" in entry: + found[f"{group}:{name}"] = _read(dump / entry["file"]) + return found + + +def _schema_differences(key: str, a: pa.Table, b: pa.Table) -> list[str]: + if a.schema.equals(b.schema, check_metadata=True): + return [] + lines = [f"{key}: schemas differ"] + for name in sorted(set(a.column_names) | set(b.column_names)): + if name not in a.column_names or name not in b.column_names: + lines.append(f" column {name!r} only in one side") + continue + fa, fb = a.schema.field(name), b.schema.field(name) + if not fa.equals(fb, check_metadata=True): + lines.append(f" {name!r}: {fa} != {fb}") + if a.column_names != b.column_names: + lines.append(f" column order: {a.column_names} != {b.column_names}") + return lines + + +_FLOAT_BITS = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()} + + +def _bits(array: Any) -> Any: + """``array`` with every float as its integer bits, so equality is bit for bit. + + Arrow's ``equals`` holds NaN unequal to itself; two tables with the same NaN bits must + compare equal, and ``0.0`` must stay distinct from ``-0.0``. Lists, fixed-size lists + and structs are rebuilt over their converted children, keeping their validity. + """ + kind = array.type + if pa.types.is_floating(kind): + return array.view(_FLOAT_BITS[kind.bit_width]) + if pa.types.is_list(kind) or pa.types.is_large_list(kind): + cls = pa.LargeListArray if pa.types.is_large_list(kind) else pa.ListArray + return cls.from_arrays(array.offsets, _bits(array.values), mask=array.is_null()) + if pa.types.is_fixed_size_list(kind): + return pa.FixedSizeListArray.from_arrays( + _bits(array.values), kind.list_size, mask=array.is_null() + ) + if pa.types.is_struct(kind): + children = [_bits(array.field(i)) for i in range(kind.num_fields)] + return pa.StructArray.from_arrays( + children, + fields=[ + kind.field(i).with_type(child.type) for i, child in enumerate(children) + ], + mask=array.is_null(), + ) + return array + + +def _bitwise(table: pa.Table) -> pa.Table: + """``table`` with every column through ``_bits`` (names kept).""" + columns = [_bits(column.combine_chunks()) for column in table.columns] + return pa.Table.from_arrays(columns, names=table.column_names) + + +def _without(table: pa.Table, volatile: set[str]) -> pa.Table: + return table.drop_columns([c for c in table.column_names if c in volatile]) + + +def _rows_as_multiset(table: pa.Table) -> list[str]: + """The rows as a sorted list of their serialized values, duplicates kept. + + Floats are taken by their bits (``_bitwise``), so NaN payloads stay distinct. + """ + table = _bitwise(table) + names = sorted(table.column_names) + return sorted( + json.dumps([repr(row[n]) for n in names]) + for row in table.select(names).to_pylist() + ) + + +def compare( + a: Path, b: Path, mode: str, volatile_by_table: dict[str, list[str]] +) -> list[str]: + """Every difference between dumps ``a`` and ``b``.""" + problems: list[str] = [] + ma = json.loads((a / "manifest.json").read_text()) + mb = json.loads((b / "manifest.json").read_text()) + for field in ("error", "summary", "warnings"): + if ma[field] != mb[field]: + problems.append(f"{field}: {ma[field]!r} != {mb[field]!r}") + events_a: Any = _events_by_node(ma["events"]) + events_b: Any = _events_by_node(mb["events"]) + if mode == "set": + events_a = sorted(json.dumps(e) for e in ma["events"]) + events_b = sorted(json.dumps(e) for e in mb["events"]) + if events_a != events_b: + problems.append("observer events differ") + for group in ("nodes", "stored"): + only = sorted(set(ma[group]) ^ set(mb[group])) + if only: + problems.append(f"{group}: only in one dump: {only}") + for name in sorted(set(ma["nodes"]) & set(mb["nodes"])): + ea, eb = ma["nodes"][name].get("error"), mb["nodes"][name].get("error") + if ea != eb: + problems.append(f"nodes:{name}: as_table error {ea!r} != {eb!r}") + for name in sorted(set(ma["stored"]) | set(mb["stored"])): + va = ma["stored"].get(name, {}).get("versions") + vb = mb["stored"].get(name, {}).get("versions") + if va != vb: + problems.append(f"stored:{name}: Delta versions {va} != {vb}") + ta, tb = _tables(a), _tables(b) + for key in sorted(set(ta) | set(tb)): + if key not in ta or key not in tb: + problems.append(f"{key}: only in one dump") + continue + x, y = ta[key], tb[key] + volatile = set(volatile_by_table.get(key, [])) | ENVIRONMENT_COLUMNS + if mode == "exact": + problems += _schema_differences(key, x, y) + else: + x, y = x.select(sorted(x.column_names)), y.select(sorted(y.column_names)) + problems += _schema_differences(key, x, y) + if x.num_rows != y.num_rows: + problems.append(f"{key}: {x.num_rows} rows != {y.num_rows} rows") + continue + for name in volatile & set(x.column_names) & set(y.column_names): + if mode == "exact" and not x.column(name).is_null().equals( + y.column(name).is_null() + ): + problems.append(f"{key}: null pattern of volatile {name!r} differs") + if mode == "set": + # Keep each volatile column's validity with its row, then drop its values. + for name in sorted(volatile & set(x.column_names) & set(y.column_names)): + x = x.append_column(f"__valid__{name}", x.column(name).is_valid()) + y = y.append_column(f"__valid__{name}", y.column(name).is_valid()) + xs, ys = _without(x, volatile), _without(y, volatile) + if mode == "exact": + if not _bitwise(xs).equals(_bitwise(ys)): + problems.append(f"{key}: values differ") + elif _rows_as_multiset(xs) != _rows_as_multiset(ys): + problems.append(f"{key}: rows differ as sets") + return problems + + +def calibrate(a: Path, b: Path) -> dict[str, list[str]]: + """The columns whose values differ between two dumps of the same checkout.""" + volatile: dict[str, list[str]] = {} + ta, tb = _tables(a), _tables(b) + for key in sorted(set(ta) & set(tb)): + x, y = ta[key], tb[key] + if x.num_rows != y.num_rows: + continue + names = [n for n in x.column_names if n in y.column_names] + differing = [ + n + for n in names + if not _bits(x.column(n).combine_chunks()).equals( + _bits(y.column(n).combine_chunks()) + ) + ] + if differing: + volatile[key] = differing + return volatile + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser() + parser.add_argument("a", type=Path) + parser.add_argument("b", type=Path) + parser.add_argument("--mode", choices=("exact", "set"), default="exact") + parser.add_argument("--volatile", type=Path) + parser.add_argument("--calibrate", type=Path) + args = parser.parse_args(argv) + if args.calibrate is not None: + found = calibrate(args.a, args.b) + args.calibrate.write_text(json.dumps(found, indent=1, sort_keys=True)) + print(json.dumps(found, indent=1, sort_keys=True)) + return 0 + volatile: dict[str, Any] = ( + json.loads(args.volatile.read_text()) if args.volatile is not None else {} + ) + problems = compare(args.a, args.b, args.mode, volatile) + for line in problems: + print(line) + print("EQUAL" if not problems else f"{len(problems)} DIFFERENCES") + return 0 if not problems else DIFFERENCES_FOUND + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/dev/scripts/itl_1347/differential.py b/docs/dev/scripts/itl_1347/differential.py new file mode 100644 index 000000000..947553156 --- /dev/null +++ b/docs/dev/scripts/itl_1347/differential.py @@ -0,0 +1,236 @@ +"""ITL-1347 differential driver: every fixture, mode, orchestrator and thread count, two Orcapods. + + python differential.py OUT --base --branch + [--fixtures tutorial,spikes] [--threads 1,default] + +``--base`` and ``--branch`` are the interpreters of two environments, each with one Orcapod +installed from a built wheel (pinned ``main`` and the stage branch). Every dump runs in its +own process, one after another. For each fixture: + +1. two ``cold`` sync dumps with the base interpreter calibrate the volatile columns + (``compare.py --calibrate``); +2. for each interpreter, orchestrator (``sync``, ``async``) and Polars thread count: a + ``cold`` dump, then ``warm`` and ``load_only`` dumps over the store it left, and a + ``held`` dump over a new store; +3. comparisons: + - branch sync against base sync, ``exact``; + - branch async against branch sync, ``set``; + - branch async against base async, ``set``. + +Writes ``OUT/report.json`` (every comparison with its differences; ``--compare-only`` +writes ``OUT/report_compare_only.json`` and leaves ``report.json`` as it is) and prints a +summary. The exit status is the gate: 1 if a dump process failed or a comparison could not +complete (its stderr is kept in the report), 2 if sync on the branch differs from sync on +base, else 0. Completed async differences are printed for review against the spec's +named differences and do not set the status. +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +HERE = Path(__file__).resolve().parent +MODES = ("cold", "warm", "load_only", "held") + + +def _dump( + python: str, + fixture: str, + mode: str, + orchestrator: str, + threads: str, + workdir: Path, + out: Path, +) -> dict[str, Any]: + env = dict(os.environ) + if threads == "default": + env.pop("POLARS_MAX_THREADS", None) + else: + env["POLARS_MAX_THREADS"] = threads + start = time.perf_counter() + done = subprocess.run( + [ + python, + str(HERE / "dump.py"), + fixture, + mode, + orchestrator, + str(workdir), + str(out), + ], + env=env, + capture_output=True, + text=True, + check=False, + ) + return { + "dump": str(out), + "returncode": done.returncode, + "stderr_tail": done.stderr[-2000:] if done.returncode else "", + "seconds": round(time.perf_counter() - start, 2), + } + + +def _compare(a: Path, b: Path, mode: str, volatile: Path) -> dict[str, Any]: + done = subprocess.run( + [ + sys.executable, + str(HERE / "compare.py"), + str(a), + str(b), + "--mode", + mode, + "--volatile", + str(volatile), + ], + capture_output=True, + text=True, + check=False, + ) + # compare.py exits 0 (equal) or 3 (completed, with differences); anything else means + # the comparison could not complete, and its stderr is kept. + completed = done.returncode in (0, 3) + return { + "a": str(a), + "b": str(b), + "mode": mode, + "completed": completed, + "stderr_tail": "" if completed else done.stderr[-2000:], + "equal": done.returncode == 0, + "output": done.stdout.splitlines()[-40:], + } + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser() + parser.add_argument("out", type=Path) + parser.add_argument("--base", required=True) + parser.add_argument("--branch", required=True) + parser.add_argument("--fixtures", default="tutorial,spikes") + parser.add_argument("--threads", default="1,default") + parser.add_argument( + "--compare-only", + action="store_true", + help="redo the comparisons on the dumps already in OUT; run nothing", + ) + args = parser.parse_args(argv) + out: Path = args.out + out.mkdir(parents=True, exist_ok=args.compare_only) + pythons = {"base": args.base, "branch": args.branch} + + def dump_fn(*dump_args: Any) -> dict[str, Any]: + if args.compare_only: + return {"dump": str(dump_args[-1]), "returncode": 0, "skipped": True} + return _dump(*dump_args) + + report: dict[str, Any] = {"runs": [], "comparisons": [], "load": []} + for fixture in args.fixtures.split(","): + calib = [out / fixture / f"calibrate_{i}" for i in (1, 2)] + for i, dump in enumerate(calib, start=1): + report["runs"].append( + dump_fn( + pythons["base"], + fixture, + "cold", + "sync", + "default", + out / fixture / f"calibrate_work_{i}", + dump, + ) + ) + volatile = out / fixture / "volatile.json" + subprocess.run( + [ + sys.executable, + str(HERE / "compare.py"), + str(calib[0]), + str(calib[1]), + "--calibrate", + str(volatile), + ], + capture_output=True, + check=True, + ) + for threads in args.threads.split(","): + for side, python in pythons.items(): + for orchestrator in ("sync", "async"): + tag = f"{side}_{orchestrator}_t{threads}" + work = out / fixture / f"work_{tag}" + held_work = out / fixture / f"work_{tag}_held" + for mode in MODES: + report["load"].append(os.getloadavg()[0]) + report["runs"].append( + dump_fn( + python, + fixture, + mode, + orchestrator, + threads, + held_work if mode == "held" else work, + out / fixture / f"{tag}_{mode}", + ) + ) + for mode in MODES: + + def d(side: str, orchestrator: str) -> Path: + return out / fixture / f"{side}_{orchestrator}_t{threads}_{mode}" + + report["comparisons"] += [ + { + "fixture": fixture, + "threads": threads, + "check": f"sync branch vs base, {mode}", + } + | _compare( + d("base", "sync"), d("branch", "sync"), "exact", volatile + ), + { + "fixture": fixture, + "threads": threads, + "check": f"async vs sync, branch, {mode}", + } + | _compare( + d("branch", "sync"), d("branch", "async"), "set", volatile + ), + { + "fixture": fixture, + "threads": threads, + "check": f"async branch vs base, {mode}", + } + | _compare( + d("base", "async"), d("branch", "async"), "set", volatile + ), + ] + report_name = "report_compare_only.json" if args.compare_only else "report.json" + (out / report_name).write_text(json.dumps(report, indent=1)) + failed_runs = [r for r in report["runs"] if r["returncode"] != 0] + incomplete = [c for c in report["comparisons"] if not c["completed"]] + for c in report["comparisons"]: + status = ( + "EQUAL" if c["equal"] else "DIFFERENT" if c["completed"] else "INCOMPLETE" + ) + print(f"{status:9} {c['fixture']:8} t={c['threads']:7} {c['check']}") + print(f"{len(failed_runs)} dump processes failed") + print(f"{len(incomplete)} comparisons could not complete") + # The exit status is the gate. A failed dump or a comparison that could not complete + # makes the run incomplete (1). A sync difference against main fails the governing + # rule (2). Completed async differences are printed for review against the spec's + # named differences, and do not set it. + if failed_runs or incomplete: + return 1 + if any( + not c["equal"] and c["check"].startswith("sync") for c in report["comparisons"] + ): + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/dev/scripts/itl_1347/dump.py b/docs/dev/scripts/itl_1347/dump.py new file mode 100644 index 000000000..e510310a0 --- /dev/null +++ b/docs/dev/scripts/itl_1347/dump.py @@ -0,0 +1,214 @@ +"""ITL-1347 differential, one side: run a fixture job and dump everything it shows. + +Run it with the interpreter of the checkout under test (pinned ``main`` or a stage branch); +the script uses only the public API: + + cd && uv run python + +- ``fixture``: a name in ``fixtures.FIXTURES``. +- ``mode``: ``cold`` (fresh store, one run), ``warm`` (a fresh process over the store a + ``cold`` run left in ``workdir``, one run), ``held`` (two runs in one process over a fresh + store; the second is dumped), ``load_only`` (a fresh process over the store a ``cold`` + run left, ``run(load_only=True)``). +- ``orchestrator``: ``sync`` or ``async``. +- ``workdir``: holds the dataset (``data/``) and the Delta store (``store/``). +- ``out``: an empty directory for the dump. + +The dump: ``manifest.json`` (the run summary, the warnings, the recording observer's events, +each node's table status, the stored tables with their Delta version counts, peak RSS and +wall time) and one Arrow IPC file per node table (``as_table(all_info=True)``) and per stored +table. ``compare.py`` compares two dumps. +""" + +from __future__ import annotations + +import dataclasses +import json +import os +import resource +import sys +import time +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tutorial")) + + +def _jsonable(given: object) -> Any: + """A JSON-ready form of ``given``: plain data kept, anything else as its repr.""" + value: Any = given + if value is None or isinstance(value, (bool, int, float, str)): + return value + if isinstance(value, (list, tuple)): + return [_jsonable(v) for v in value] + if isinstance(value, dict): + return {str(k): _jsonable(v) for k, v in value.items()} + items = getattr(value, "items", None) + if callable(items): + pairs: Any = items() + return {str(k): _jsonable(v) for k, v in pairs} + if dataclasses.is_dataclass(value) and not isinstance(value, type): + fields = dataclasses.fields(value) + return {f.name: _jsonable(getattr(given, f.name)) for f in fields} + if hasattr(value, "__dict__") and not isinstance(value, type): + return {k: _jsonable(v) for k, v in sorted(vars(value).items()) if k[:1] != "_"} + return repr(value) + + +class RecordingObserver: + """An observer that records every event, with the tag values it was given.""" + + def __init__(self) -> None: + self.events: list[list[Any]] = [] + + def contextualize(self, *identity_path: str) -> RecordingObserver: + return self + + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + self.events.append(["run_start"]) + + def on_run_end(self, run_id: str) -> None: + self.events.append(["run_end"]) + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + self.events.append(["node_start", node_label, node_hash]) + + def on_node_end(self, node_label: str, node_hash: str) -> None: + self.events.append(["node_end", node_label, node_hash]) + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + self.events.append(["data_start", node_label, _jsonable(tag.as_dict())]) + + def on_data_end( + self, + node_label: str, + tag: Any, + input_data: Any, + output_data: Any, + cached: bool, + ) -> None: + out = None if output_data is None else _jsonable(output_data.as_dict()) + self.events.append( + ["data_end", node_label, _jsonable(tag.as_dict()), out, cached] + ) + + def on_data_crash(self, node_label: str, tag: Any, data: Any, error: Any) -> None: + self.events.append( + ["data_crash", node_label, _jsonable(tag.as_dict()), type(error).__name__] + ) + + def create_data_logger(self, tag: Any, data: Any) -> Any: + from orcapod.pipeline.observer import NoOpObserver + + return NoOpObserver().create_data_logger(tag, data) + + +def _write_ipc(table: pa.Table, path: Path) -> None: + with ( + pa.OSFile(str(path), "wb") as sink, + pa.ipc.new_file(sink, table.schema) as writer, + ): + writer.write_table(table) + + +def _stored_tables(store: Path) -> dict[str, tuple[pa.Table, int]]: + """Every Delta table under ``store``: its rows and its number of versions.""" + from deltalake import DeltaTable + + found: dict[str, tuple[pa.Table, int]] = {} + for dirpath, dirnames, _ in os.walk(store): + if "_delta_log" in dirnames: + log = Path(dirpath) / "_delta_log" + versions = len([f for f in os.listdir(log) if f.endswith(".json")]) + table = DeltaTable(dirpath).to_pyarrow_table() + found[os.path.relpath(dirpath, store)] = (table, versions) + dirnames.clear() + return found + + +def main(argv: list[str]) -> int: + fixture, mode, orchestrator, workdir_arg, out_arg = argv + import importlib + + fixtures_module: Any = importlib.import_module("fixtures") + workshop_data: Any = importlib.import_module("workshop_data") + FIXTURES = fixtures_module.FIXTURES + make_dataset = workshop_data.make_dataset + + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import AsyncPipelineOrchestrator + + workdir = Path(workdir_arg) + out = Path(out_arg) + out.mkdir(parents=True, exist_ok=False) + data_dir = make_dataset(workdir / "data") + store = workdir / "store" + database = DeltaTableDatabase(store) + job = FIXTURES[fixture](data_dir, database) + run_kwargs: dict[str, Any] = {} + if orchestrator == "async": + run_kwargs["orchestrator"] = AsyncPipelineOrchestrator() + + observer = RecordingObserver() + error: str | None = None + summary: Any = None + started = time.perf_counter() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + try: + if mode == "held": + job.run(**run_kwargs) + observer.events.clear() + summary = job.run( + observer=observer, load_only=(mode == "load_only"), **run_kwargs + ) + except Exception as exc: # recorded: an error is a result too + error = f"{type(exc).__name__}: {exc}" + seconds = time.perf_counter() - started + + nodes: dict[str, Any] = {} + for label in sorted(job.nodes): + node = job.nodes[label] + try: + table = node.as_table(all_info=True) + except Exception as exc: + nodes[label] = {"error": f"{type(exc).__name__}: {exc}"} + continue + name = f"node_{len(nodes):03d}.arrow" + _write_ipc(table, out / name) + nodes[label] = {"file": name, "rows": table.num_rows} + + stored: dict[str, Any] = {} + for index, (path, (table, versions)) in enumerate( + sorted(_stored_tables(store).items()) + ): + name = f"stored_{index:03d}.arrow" + _write_ipc(table, out / name) + stored[path] = {"file": name, "rows": table.num_rows, "versions": versions} + + manifest = { + "fixture": fixture, + "mode": mode, + "orchestrator": orchestrator, + "polars_max_threads": os.environ.get("POLARS_MAX_THREADS", "default"), + "error": error, + "summary": _jsonable(summary), + "warnings": sorted({f"{w.category.__name__}: {w.message}" for w in caught}), + "events": observer.events, + "nodes": nodes, + "stored": stored, + "seconds": round(seconds, 3), + "peak_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + } + (out / "manifest.json").write_text(json.dumps(manifest, indent=1, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/dev/scripts/itl_1347/fixtures.py b/docs/dev/scripts/itl_1347/fixtures.py new file mode 100644 index 000000000..4af2601dd --- /dev/null +++ b/docs/dev/scripts/itl_1347/fixtures.py @@ -0,0 +1,172 @@ +"""ITL-1347 fixture pipelines, built on the tutorial dataset (``docs/tutorial/workshop_data.py``). + +Every fixture is a function ``build(data_dir, database) -> PipelineJob`` that records a job +over the dataset written by ``make_dataset(data_dir)``. The fixtures use only the public +API, so the same file builds the same job on pinned ``main`` and on a stage branch: the +differential (``dump.py``, ``compare.py``) runs it under both checkouts. + +- ``tutorial``: the pipeline of ``docs/tutorial/05-pipeline-job.md`` (two sources, a join, + a function pod per unit, a group-by, a function pod per session). +- ``spikes``: the workshop's shape at a larger scale. Every spike of the dataset is one row + (tens of thousands), joined to its unit, binned by a function pod per spike, grouped per + unit and counted by a second function pod, with ``Batch``, ``MergeJoin``, ``SemiJoin``, + ``PolarsFilter``, ``AddTags``, ``DropNulls``, ``MapData`` and ``Rejoin`` beside it, and a + side effect at the end. Every operator of the stage-5 classification appears once. +""" + +from __future__ import annotations + +import csv +import os +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pyarrow as pa + + +def _tutorial_sources(data_dir: Path) -> tuple[Any, Any]: + from orcapod.sources import CSVSource + + sessions = CSVSource( + str(data_dir / "sessions.csv"), + tag_columns=["subject_id", "session"], + tag_only_columns=True, + source_id="sessions", + ) + units = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], + tag_only_columns=True, + source_id="units", + ) + return sessions, units + + +def build_tutorial(data_dir: Path, database: Any) -> Any: + """The tutorial's pipeline job (``05-pipeline-job.md``).""" + from orcapod import PipelineJob, function_pod + + sessions, units = _tutorial_sources(data_dir) + + @function_pod(output_keys="rate_hz") + def firing_rate(n_spikes: int, duration_s: float) -> float: + return n_spikes / duration_s + + @function_pod(output_keys="mean_rate_hz") + def mean_rate(rate_hz: list[float]) -> float: + return sum(rate_hz) / len(rate_hz) + + job = PipelineJob(name="itl1347_tutorial", database=database) + with job: + rates: Any = firing_rate.pod( + units.select_data_columns(["n_spikes"]), + sessions.select_data_columns(["duration_s"]), + label="rates", + ) + mean_rate.pod( + rates.group_by(["subject_id", "session"]).select_data_columns(["rate_hz"]), + label="session_means", + ) + return job + + +def spikes_table(data_dir: Path) -> pa.Table: + """Every spike of the dataset as one row, in a fixed order (file name, then line). + + ``ITL1347_SPIKES_MAX`` keeps only the first rows, for a quick check of the harness. + """ + columns: dict[str, list[Any]] = { + "subject_id": [], + "session": [], + "probe": [], + "spike": [], + "unit": [], + "time_s": [], + } + for session_dir in sorted((data_dir / "sessions").iterdir()): + subject_id, session = session_dir.name.rsplit("_", 1) + for path in sorted(session_dir.glob("spikes_*.csv")): + probe = path.stem.removeprefix("spikes_") + with path.open(newline="", encoding="utf-8") as handle: + for index, row in enumerate(csv.DictReader(handle)): + columns["subject_id"].append(subject_id) + columns["session"].append(session) + columns["probe"].append(probe) + columns["spike"].append(index) + columns["unit"].append(int(row["unit"])) + columns["time_s"].append(float(row["time_s"])) + limit = os.environ.get("ITL1347_SPIKES_MAX") + if limit is not None: + columns = {name: values[: int(limit)] for name, values in columns.items()} + types = { + "subject_id": pa.large_string(), + "session": pa.large_string(), + "probe": pa.large_string(), + "spike": pa.int64(), + "unit": pa.int64(), + "time_s": pa.float64(), + } + schema = pa.schema([pa.field(name, t, nullable=False) for name, t in types.items()]) + return pa.Table.from_arrays( + [pa.array(columns[name], types[name]) for name in types], schema=schema + ) + + +def build_spikes(data_dir: Path, database: Any) -> Any: + """The workshop's shape at scale: one row per spike, every operator kind once.""" + from orcapod import InvocationContext, PipelineJob, function_pod, tap_pod + from orcapod.operators import MergeJoin, Rejoin + from orcapod.sources import ArrowTableSource + + sessions, units = _tutorial_sources(data_dir) + spikes = ArrowTableSource( + spikes_table(data_dir), + tag_columns=["subject_id", "session", "probe", "unit", "spike"], + tag_only_columns=True, + source_id="spikes", + ) + + @function_pod(output_keys="bin") + def time_bin(time_s: float) -> int: + return int(time_s // 10.0) + + @function_pod(output_keys="n_bins") + def bins_hit(bin: list[int]) -> int: + return len(set(bin)) + + @tap_pod + def report_fn(n_bins: int, ctx: InvocationContext) -> None: + return None + + job = PipelineJob(name="itl1347_spikes", database=database) + with job: + located = spikes.join(units.select_data_columns(["region"]), label="located") + binned: Any = time_bin.pod( + located.select_data_columns(["time_s"]), label="binned" + ) + per_unit = binned.group_by(["subject_id", "session", "probe", "unit"]) + counted: Any = bins_hit.pod( + per_unit.select_data_columns(["bin"]), label="counted" + ) + report: Any = report_fn + report(counted, label="report") + long_sessions = sessions.polars_filter(duration_s=120.0, label="long_sessions") + units.semi_join(long_sessions, label="units_in_long_sessions") + units.select_data_columns(["n_spikes"]).batch(batch_size=4, label="batched") + merged = MergeJoin()( + units.select_data_columns(["n_spikes"]), + counted.map_data({"n_bins": "n_spikes"}), + ) + merged.add_tags(study="itl1347", label="tagged").drop_nulls(label="no_nulls") + Rejoin()( + units.select_data_columns(["region"]), + units.select_data_columns(["depth_um"]), + ) + return job + + +FIXTURES: dict[str, Callable[[Path, Any], Any]] = { + "tutorial": build_tutorial, + "spikes": build_spikes, +} diff --git a/docs/dev/scripts/itl_1347/instrument.py b/docs/dev/scripts/itl_1347/instrument.py new file mode 100644 index 000000000..6d280961f --- /dev/null +++ b/docs/dev/scripts/itl_1347/instrument.py @@ -0,0 +1,199 @@ +"""ITL-1347 stage 0: count where a job run makes and unmakes rows. + +Wraps, for the duration of a ``with counting():`` block and nowhere else: + +- ``Datagram.__init__`` (every ``Tag`` and ``Data``), counted by class and by the node kind + whose ``execute`` / ``async_execute`` is running (``edge`` when none is: the orchestrator + rebuilding a successor's input, or the run plan); +- ``StaticOutputOperatorPod._rows_to_table`` (``R`` in the spec), counted and timed by its + caller (``_kept_output``/``_materialize_to_stream``, ``_materialize_upstream``, + ``_materialize_input_stream``); +- each node kind's ``execute`` and ``async_execute``, timed inclusively. + +Nothing in the library changes; the wrappers are removed when the block ends. The counts +are what the spec's stage table needs to replace its estimates (rows made per node kind, +rebuilds per caller, edges per node). +""" + +from __future__ import annotations + +import contextlib +import contextvars +import functools +import sys +import time +from collections import Counter, defaultdict +from collections.abc import Callable, Iterator +from typing import Any + +_NODE_KIND: contextvars.ContextVar[str] = contextvars.ContextVar( + "itl1347_node_kind", default="edge" +) + + +class Counts: + """What one counted block saw.""" + + def __init__(self) -> None: + self.datagrams: Counter[tuple[str, str]] = Counter() + self.rows_to_table_calls: Counter[str] = Counter() + self.rows_to_table_rows: Counter[str] = Counter() + self.rows_to_table_seconds: defaultdict[str, float] = defaultdict(float) + self.execute_calls: Counter[str] = Counter() + self.execute_seconds: defaultdict[str, float] = defaultdict(float) + + def as_dict(self) -> dict[str, Any]: + """The counts as plain JSON-ready data.""" + return { + "datagrams_by_node_kind_and_class": { + f"{kind}/{cls}": n for (kind, cls), n in sorted(self.datagrams.items()) + }, + "datagrams_total": sum(self.datagrams.values()), + "rows_to_table_by_caller": { + caller: { + "calls": self.rows_to_table_calls[caller], + "rows": self.rows_to_table_rows[caller], + "seconds": round(self.rows_to_table_seconds[caller], 4), + } + for caller in sorted(self.rows_to_table_calls) + }, + "execute_by_node_kind": { + kind: { + "calls": self.execute_calls[kind], + "seconds_inclusive": round(self.execute_seconds[kind], 4), + } + for kind in sorted(self.execute_calls) + }, + } + + +def _patch(owner: Any, name: str, make: Callable[[Any], Any]) -> Callable[[], None]: + """Replace ``owner.name`` with ``make(original)``; return the undo.""" + original = owner.__dict__[name] + setattr(owner, name, make(original)) + + def undo() -> None: + setattr(owner, name, original) + + return undo + + +@contextlib.contextmanager +def counting() -> Iterator[Counts]: + """Count datagrams, ``R`` calls and node executions inside the block.""" + from orcapod.core.datagrams.datagram import Datagram + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceNodeBase + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + from orcapod.side_effects import SideEffectJobNode + + counts = Counts() + undo: list[Callable[[], None]] = [] + + def wrap_init(original: Any) -> Any: + @functools.wraps(original) + def __init__(self: Any, *args: Any, **kwargs: Any) -> None: + counts.datagrams[(_NODE_KIND.get(), type(self).__name__)] += 1 + original(self, *args, **kwargs) + + return __init__ + + undo.append(_patch(Datagram, "__init__", wrap_init)) + + # ITL-1348 builds the rows of a table without ``__init__``: count those too. + if "_rows_of_table" in Datagram.__dict__: + + def wrap_rows_of_table(original: Any) -> Any: + func = original.__func__ + + @functools.wraps(func) + def _rows_of_table(cls: Any, *args: Any, **kwargs: Any) -> Iterator[Any]: + for item in func(cls, *args, **kwargs): + counts.datagrams[(_NODE_KIND.get(), cls.__name__)] += 1 + yield item + + return classmethod(_rows_of_table) + + undo.append(_patch(Datagram, "_rows_of_table", wrap_rows_of_table)) + + def wrap_rows_to_table(original: Any) -> Any: + func = original.__func__ + + @functools.wraps(func) + def _rows_to_table(rows: Any) -> Any: + caller = sys._getframe(1).f_code.co_name # pyright: ignore[reportPrivateUsage] # the caller's name is the measurement + start = time.perf_counter() + try: + return func(rows) + finally: + counts.rows_to_table_calls[caller] += 1 + counts.rows_to_table_rows[caller] += len(rows) + counts.rows_to_table_seconds[caller] += time.perf_counter() - start + + return staticmethod(_rows_to_table) + + undo.append(_patch(StaticOutputOperatorPod, "_rows_to_table", wrap_rows_to_table)) + + def wrap_execute(kind: str) -> Callable[[Any], Any]: + def make(original: Any) -> Any: + @functools.wraps(original) + def execute(self: Any, *args: Any, **kwargs: Any) -> Any: + token = _NODE_KIND.set(kind) + start = time.perf_counter() + try: + return original(self, *args, **kwargs) + finally: + counts.execute_calls[kind] += 1 + counts.execute_seconds[kind] += time.perf_counter() - start + _NODE_KIND.reset(token) + + return execute + + return make + + def wrap_async_execute(kind: str) -> Callable[[Any], Any]: + def make(original: Any) -> Any: + @functools.wraps(original) + async def async_execute(self: Any, *args: Any, **kwargs: Any) -> Any: + token = _NODE_KIND.set(kind) + start = time.perf_counter() + try: + return await original(self, *args, **kwargs) + finally: + counts.execute_calls[f"{kind} (async)"] += 1 + counts.execute_seconds[f"{kind} (async)"] += ( + time.perf_counter() - start + ) + _NODE_KIND.reset(token) + + return async_execute + + return make + + for cls, kind in ( + (SourceNodeBase, "source"), + (OperatorJobNode, "operator"), + (FunctionJobNode, "function"), + (SideEffectJobNode, "side_effect"), + ): + undo.append(_patch(cls, "execute", wrap_execute(kind))) + undo.append(_patch(cls, "async_execute", wrap_async_execute(kind))) + + try: + yield counts + finally: + for step in reversed(undo): + step() + + +def edges_per_node(job: Any) -> dict[str, dict[str, int]]: + """Each node's label with its number of predecessors and successors.""" + graph = job.dag + return { + str(getattr(node, "label", node)): { + "inputs": len(list(graph.predecessors(node))), + "successors": len(list(graph.successors(node))), + } + for node in graph.topological_sort() + } diff --git a/docs/dev/scripts/itl_1347/join_order_plugin.py b/docs/dev/scripts/itl_1347/join_order_plugin.py new file mode 100644 index 000000000..5713ff638 --- /dev/null +++ b/docs/dev/scripts/itl_1347/join_order_plugin.py @@ -0,0 +1,71 @@ +"""ITL-1357 measurement (ITL-1347 stage 0, a report only): Polars' inner-join row order. + +A pytest plugin. Loaded with ``-p join_order_plugin`` (``docs/dev/scripts/itl_1347`` on +``PYTHONPATH``), it wraps ``polars.DataFrame.join`` for the test session. Every inner join +called without ``maintain_order`` (the key-frame joins of ``Join``, ``MergeJoin`` and +``Rejoin``) is computed a second time with ``maintain_order="left_right"``, and the two +results are compared row for row. The join's own result is returned unchanged, so the tests +run as they do without the plugin. + +At the end of the session it writes ``ITL1357_REPORT`` (a JSON path) with the number of +such joins, how many gave the same row order, and, for each one that did not, the test, the +calling function and both row counts. Run it once with ``POLARS_MAX_THREADS=1`` and once at +the default. +""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import pytest + +_state: dict[str, Any] = {"joins": 0, "same": 0, "different": [], "test": None} + + +def pytest_configure(config: Any) -> None: + import polars as pl + + original = pl.DataFrame.join + + def join(self: Any, other: Any, *args: Any, **kwargs: Any) -> Any: + result = original(self, other, *args, **kwargs) + how = kwargs.get("how", args[2] if len(args) > 2 else "inner") + if how != "inner" or "maintain_order" in kwargs: + return result + ordered = original(self, other, *args, maintain_order="left_right", **kwargs) + _state["joins"] += 1 + if result.equals(ordered): + _state["same"] += 1 + else: + caller = sys._getframe(1).f_code # pyright: ignore[reportPrivateUsage] # the caller is the measurement + _state["different"].append( + { + "test": _state["test"], + "caller": f"{caller.co_filename}:{caller.co_name}", + "rows": [result.height, ordered.height], + } + ) + return result + + pl.DataFrame.join = join # pyright: ignore[reportAttributeAccessIssue] # the measurement wraps it for this session + + +@pytest.hookimpl(tryfirst=True) +def pytest_runtest_setup(item: Any) -> None: + _state["test"] = item.nodeid + + +def pytest_sessionfinish(session: Any, exitstatus: int) -> None: + path = os.environ.get("ITL1357_REPORT") + report = { + "polars_max_threads": os.environ.get("POLARS_MAX_THREADS", "default"), + "inner_joins_without_maintain_order": _state["joins"], + "same_order_as_left_right": _state["same"], + "different": _state["different"], + } + if path: + with open(path, "w", encoding="utf-8") as handle: + json.dump(report, handle, indent=1) diff --git a/docs/dev/specs/itl-1347/stage-0.md b/docs/dev/specs/itl-1347/stage-0.md new file mode 100644 index 000000000..d4ba53b47 --- /dev/null +++ b/docs/dev/specs/itl-1347/stage-0.md @@ -0,0 +1,127 @@ +# ITL-1347 stage 0: measurements (2026-11-22) + +Stage 0 of `docs/dev/specs/itl-1347-job-table-transport.md`: measurement only, no library +change. The scripts are in `docs/dev/scripts/itl_1347/` (`README.md` there). The raw +records stay outside the repository. + +## Setup + +- **The two Orcapods**: + - *base*: `main` 8c6fc4f5 (0.4.0rc1, what ITL-1345 profiled); + - *job-speed*: `eywalker/job-speed` 0e15d0db, which already holds ITL-1348 (rows of a + table built without normalizing each again), ITL-1349 (modules loaded directly, not + through `LazyModule`) and ITL-1351 (a held node's rows counted without building them). +- **Environments**: each Orcapod was built as a wheel and installed into its own + environment. Before measuring, the installed `pipeline/node_run.py` was checked to match + its source (sha256). +- **Machine**: Python 3.14 on an Apple silicon Mac. One heavy process at a time; the + 1-minute load average is given with each number. +- **Workload**: a workshop-shaped pipeline on a local Delta copy. It has two sources + (63,349 and 28,780 rows), eight operator nodes (`GroupBy` ×2, `DropNulls`, `MapData` ×2, + `SelectDataColumns` ×2, `Join`) and two function nodes. Every edge has one successor. + +## Workshop-shaped job: time + +`job.run()` seconds; best of 3 for the warm runs. + +| | cold | warm 1 / 2 / 3 | **warm best** | async `job.run()` with every node held | load (warm runs) | +|---|---:|---:|---:|---:|---| +| base 8c6fc4f5 | 46.39 | 44.96 / 45.97 / 44.59 | **44.59** | 5.73–5.75 | 2.19 / 1.91 / 3.22 | +| job-speed 0e15d0db | 31.45 | 29.00 / 29.70 / 30.68 | **29.00** | 0.004–0.005 | 1.76 / 2.39 / 2.05 | + +Peak RSS of the whole notebook process: 5.67–5.78 GB (base), 6.19–6.28 GB (job-speed). + +## Workshop-shaped job: where rows are made and unmade (warm run) + +Counted by `instrument.counting()` around the `job.run()` cell. + +| | base | job-speed | +|---|---:|---:| +| datagrams made in source nodes (`Tag` + `Data`) | 184,258 | 184,258 | +| datagrams made in operator nodes | 57,822 | 57,822 | +| datagrams made in function nodes | 165 | 165 | +| `_rows_to_table` on edges (`_materialize_upstream`): calls / rows / seconds | 11 / 121,041 / 11.93 | 11 / 121,041 / 11.59 | +| `_rows_to_table` for operator nodes' kept output (`_materialize_to_stream`): calls / rows / seconds | 8 / 28,911 / 3.84 | 8 / 28,911 / 3.80 | +| source node `execute`, inclusive seconds | 14.74 | 3.54 | +| operator node `execute`, inclusive seconds | 15.62 | 12.50 | +| function node `execute`, inclusive seconds | 0.25 | 0.19 | + +job-speed makes the same datagrams as base: ITL-1348 made each one cheaper, not fewer. (A +first count on job-speed missed them, because ITL-1348 builds rows without +`Datagram.__init__`; `instrument.py` now counts `Datagram._rows_of_table` too.) + +The 121,041 edge rows split by producer as follows: +- the two sources: 92,129 rows; +- the operator nodes: 28,911 rows, of which 28,780 come from one node (`DropNulls`); +- the function node feeding the join: 1 row. + +On job-speed, `_rows_to_table` still costs about 15.4 s of the 29 s warm run: 11.6 s on +edges, 3.8 s for kept outputs. + +## What this means for the staged plan + +These numbers replace the spec's estimates, which came from the profile's shares: + +| Stage | Estimate in the spec | From these measurements, on job-speed (29.0 s warm) | +|---|---|---| +| 1: reuse an operator node's kept table on its edges | 4–8 s | **about 2.8 s**: operator outputs are 28,911 of the 121,041 edge rows, so about 24% of the 11.6 s edge rebuild | +| 2a: sources hand on their Arrow table | (with 2b) 14–20 s | about 8.8 s of edge rebuild (92,129 source rows) plus most of the 3.5 s source `execute` | +| 2b: operators keep and hand on `F(result)` | (with 2a) | the 3.8 s kept-output rebuild plus the operators' row iteration inside their 12.5 s `execute` | +| 3: function nodes | 8–14 s | small on this workload: two function nodes, 0.2 s in `execute`, 33 rows | + +Stage 1 alone is therefore worth about 10% of the warm run here. Most of the remaining gain +is in stage 2. ITL-1348's trusted row path has already removed most of the datagram cost +that the spec's estimates included. + +## Same results: base against job-speed + +- **Workshop-shaped job (warm run)**: every node's `as_table(all_info=True)` and every + stored table are equal byte for byte, except columns that each run makes afresh: + - `__record_id`, `__pod_ts` and `__data_id`; + - the `_source_*` tokens of function outputs, which embed a result's record id. + + Floats are compared by their bits. Arrow's `equals` holds NaN unequal to itself, and the + job has 539 NaN values per float column. +- **Fixture differential**: equal; see "Fixture differential" below. + +## ITL-1357: Polars' inner-join order (report only) + +- **Method**: `join_order_plugin.py` over `tests/test_core/operators/` (6,208 passed, 285 + xfailed). Every Polars inner join without `maintain_order` was recomputed with + `maintain_order="left_right"`, and the two row orders were compared. + +| Polars threads | inner joins without `maintain_order` | same order as `left_right` | different | +|---|---:|---:|---:| +| 1 | 2,912 | 2,265 | 647 | +| default | 2,912 | 2,265 | 647 | + +- **Callers of the differing joins**: `join._inner_join` (shared by `Join` and `MergeJoin`) + 628, and a test's own join 19. +- **Result**: `maintain_order="left_right"` does not reproduce today's order, so setting it + would be a result change, for its own decision (spec, decision 10). The counts are the + same at one thread and at the default. + +## Fixture differential + +- **Run**: `differential.py`, base 8c6fc4f5 against job-speed 0e15d0db. +- **Fixtures**: `tutorial` (the tutorial's pipeline), and `spikes` (36,616 spike rows, + every operator kind and a side effect). +- **Modes**: cold, warm, load-only and held, on both orchestrators, at one Polars thread and + at the default: 8 sync and 8 async cases per fixture. + +| Comparison | Result | +|---|---| +| sync job-speed against sync base, byte for byte | **equal in all 16 cases** (8 per fixture) | +| async job-speed against async base, as multisets | **equal in all 16 cases** | +| async against sync, on job-speed, as multisets | differs only by known `main` behaviours, the same on base: e3 (ITL-1062: duplicate inputs computed and stored again, with the summary's counts) and e8 (the async side-effect node's `__computed` column) | + +The run found two properties of the harness's inputs that are not results, and the +comparison now accounts for both. They were applied by re-comparing the same dumps +(`--compare-only`), with no new run: + +- `__pf_var_git_hash` (a function's git state) depends on the checkout, which changed + (`-dirty` to `-dirty-untracked`) when a file was added during the run. It is now an + environment column, left out like the volatile ones. +- `main` starts independent nodes (two sources, say) in an order that varies between two + runs of the same code. So observer events are compared node by node, each node's own + sequence in order, not as one global sequence.