From 85314f1f8b224c16b326a0326bc6bc5181bc29c6 Mon Sep 17 00:00:00 2001 From: Marat K Date: Tue, 27 Oct 2026 16:10:44 +0100 Subject: [PATCH 1/5] bench: measure Python source mutations Measure native and pure source edits in GitHub CI with exact output and independent semantic oracles. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/bench-edit.yml | 73 ++++++++++ examples/bench_edit.py | 238 +++++++++++++++++++++++++++++++ 2 files changed, 311 insertions(+) create mode 100644 .github/workflows/bench-edit.yml create mode 100644 examples/bench_edit.py diff --git a/.github/workflows/bench-edit.yml b/.github/workflows/bench-edit.yml new file mode 100644 index 0000000..0d7fd07 --- /dev/null +++ b/.github/workflows/bench-edit.yml @@ -0,0 +1,73 @@ +name: Edit benchmark + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + benchmark: + name: Python 3.9 / Ubuntu + runs-on: ubuntu-latest + env: + CARGO_TERM_COLOR: always + steps: + - uses: actions/checkout@v6 + with: + submodules: recursive + - uses: actions/setup-python@v6 + with: + python-version: "3.9" + cache: pip + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Create venv + run: python -m venv .venv + - name: Export venv to PATH and VIRTUAL_ENV + shell: python + run: | + import os + venv = os.path.abspath(".venv") + with open(os.environ["GITHUB_PATH"], "a") as f: + f.write(os.path.join(venv, "bin") + "\n") + with open(os.environ["GITHUB_ENV"], "a") as f: + f.write(f"VIRTUAL_ENV={venv}\n") + - name: Install build tooling + run: python -m pip install --upgrade pip maturin "tomli>=2.5.0; python_version < '3.11'" + - name: Generate Cargo.lock + run: cargo generate-lockfile + - name: Verify ktav core pin + shell: python + run: | + import re, sys + from pathlib import Path + + pin = "8b6b45ffbd9e50e1588e8ab6b1ae5d422bbe8910" + cargo = Path("Cargo.toml").read_text(encoding="utf-8") + match = re.search(r'rev\s*=\s*"([0-9a-f]{40})"', cargo) + if match is None or match.group(1) != pin: + sys.exit(f"Cargo.toml ktav pin mismatch: expected {pin}") + packages = Path("Cargo.lock").read_text(encoding="utf-8").split("[[package]]") + core = [p for p in packages if re.search(r'^name = "ktav"$', p, re.M)] + if len(core) != 1: + sys.exit("Cargo.lock: expected exactly one ktav package") + entry = core[0] + source = re.search(r'^source = "git\+https://github\.com/ktav-lang/rust\?rev=' + pin + r'#([0-9a-f]{40})"$', entry, re.M) + version = re.search(r'^version = "([^"]+)"', entry, re.M) + if source is None or source.group(1) != pin or version is None or version.group(1) != "0.9.0": + sys.exit("Cargo.lock ktav source/version does not match the pinned core") + - name: Build native extension (release) + run: maturin develop --release --locked + - name: Run edit benchmark + run: python examples/bench_edit.py > benchmark-edit.jsonl + - name: Upload benchmark results + uses: actions/upload-artifact@v7 + with: + name: benchmark-edit-${{ github.sha }}-${{ github.run_id }} + path: | + benchmark-edit.jsonl + Cargo.lock + if-no-files-found: error diff --git a/examples/bench_edit.py b/examples/bench_edit.py new file mode 100644 index 0000000..a401555 --- /dev/null +++ b/examples/bench_edit.py @@ -0,0 +1,238 @@ +"""Compare source-edit operations in native ktav and standalone ktav.pure. + +Run from the repository root after building/installing the native extension: +``python examples/bench_edit.py``. Results are JSON Lines; timings are +observations only and are not performance claims or thresholds. +""" + +from __future__ import annotations + +import argparse +import json +import platform +import time +from typing import Any + +import ktav +from ktav import pure + + +CASES = ( + { + "name": "insert-root", + "operation": "insert_value", + "source": "a: 1\n", + "path": "b", + "value": 2, + "expected": "a: 1\nb: 2\n", + "semantic": {"a": 1, "b": 2}, + }, + { + "name": "insert-nested-object-array", + "operation": "insert_value", + "source": "items: [{name: one}]\n", + "path": "items.0.value", + "value": 2, + "expected": "items: [{name: one, value: 2}]\n", + "semantic": {"items": [{"name": "one", "value": 2}]}, + }, + { + "name": "remove-array-element", + "operation": "remove_value", + "source": "## keep\na: [1, 2, 3]\nb: 4\n", + "path": "a.1", + "expected": "## keep\na: [1, 3]\nb: 4\n", + "semantic": {"a": [1, 3], "b": 4}, + }, + { + "name": "rename-crlf-dotted", + "operation": "rename_key", + "source": '"a.b": {child: {leaf: 1}, keep: 2}\r\n', + "path": r"a\.b.child.leaf", + "new_key": "changed", + "expected": '"a.b": {child: {changed: 1}, keep: 2}\r\n', + "semantic": {"a.b": {"child": {"changed": 1}, "keep": 2}}, + }, + { + "name": "rename-unicode-key-crlf", + "operation": "rename_key", + "source": "k:: 042\r\n", + "path": "k", + "new_key": "ключ", + "expected": "ключ:: 042\r\n", + "semantic": {"ключ": "042"}, + }, + { + "name": "remove-root", + "operation": "remove_value", + "source": "a: 1\nb: 2\n", + "path": "a", + "expected": "b: 2\n", + "semantic": {"b": 2}, + }, +) +NATIVE_EDIT_NAMES = ("_insert_value", "_remove_value", "_rename_key") + + +def wide_root_cases() -> tuple[dict[str, Any], ...]: + """Build broad-root fixtures and oracles from known ordered entries.""" + cases = [] + for size in (16, 128, 512): + entries = [(f"key{index:03d}", index) for index in range(size)] + source = "".join(f"{key}: {value}\n" for key, value in entries) + semantic = dict(entries) + for operation, position in ( + ("insert_value", size), + ("remove_value", size // 2), + ("remove_value", size - 1), + ("rename_key", size // 2), + ("rename_key", size - 1), + ): + key = f"key{position:03d}" + updated_entries = list(entries) + updated_semantic = dict(semantic) + if operation == "insert_value": + updated_entries.append(("added", -1)) + updated_semantic["added"] = -1 + path = "added" + value = -1 + elif operation == "remove_value": + updated_entries.pop(position) + del updated_semantic[key] + path = key + value = None + else: + updated_entries[position] = ("renamed", position) + del updated_semantic[key] + updated_semantic["renamed"] = position + path = key + value = None + expected = "".join( + f"{entry_key}: {entry_value}\n" for entry_key, entry_value in updated_entries + ) + case = { + "name": f"wide-root-{size}-{operation}-{position}", + "operation": operation, + "source": source, + "path": path, + "expected": expected, + "semantic": updated_semantic, + } + if operation == "insert_value": + case["value"] = value + if operation == "rename_key": + case["new_key"] = "renamed" + cases.append(case) + return tuple(cases) + + +def all_cases() -> tuple[dict[str, Any], ...]: + return CASES + wide_root_cases() + + +def invoke(api: Any, case: dict[str, Any]) -> str: + operation = case["operation"] + if operation == "rename_key": + return api.rename_key(case["source"], case["path"], case["new_key"]) + if operation == "insert_value": + return api.insert_value(case["source"], case["path"], case["value"]) + return api.remove_value(case["source"], case["path"]) + + +def validate(api: Any, backend: str) -> None: + for case in all_cases(): + result = invoke(api, case) + expected_bytes = case["expected"].encode("utf-8") + if result.encode("utf-8") != expected_bytes: + raise AssertionError(f"{backend} {case['name']}: byte output mismatch: {result!r}") + actual = api.loads(result) + if actual != case["semantic"]: + raise AssertionError(f"{backend} {case['name']}: semantic mismatch: {actual!r}") + + +def benchmark( + api: Any, + backend: str, + case: dict[str, Any], + warmup: int, + repeats: int, + iterations: int, +) -> dict[str, Any]: + def run_edit() -> str: + return invoke(api, case) + + for _ in range(warmup): + run_edit() + samples = [] + for _ in range(repeats): + start = time.perf_counter() + for _ in range(iterations): + run_edit() + samples.append((time.perf_counter() - start) / iterations) + return { + "type": "result", + "backend": backend, + "scenario": case["name"], + "operation": case["operation"], + "source_bytes": len(case["source"].encode("utf-8")), + "iterations": iterations, + "warmup": warmup, + "samples_seconds_per_operation": samples, + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--warmup", type=int, default=100) + parser.add_argument("--repeats", type=int, default=5) + parser.add_argument("--iterations", type=int, default=100) + args = parser.parse_args() + if min(args.warmup, args.repeats, args.iterations) < 1: + parser.error("warmup, repeats, and iterations must be positive") + + if not ktav._HAS_CORE: + raise RuntimeError("A real native ktav source-edit extension is required") + for name in NATIVE_EDIT_NAMES: + function = getattr(ktav, name, None) + if function is None or getattr(function, "_ktav_stub", False): + raise RuntimeError(f"A real native source-edit function is required: {name}") + validate(ktav, "native") + validate(pure, "pure") + metadata = { + "type": "metadata", + "python": platform.python_version(), + "platform": platform.platform(), + "machine": platform.machine(), + "processor": platform.processor(), + "ktav_version": ktav.__version__, + "pure_version": pure.__version__, + "warmup": args.warmup, + "repeats": args.repeats, + "iterations": args.iterations, + } + print(json.dumps(metadata, ensure_ascii=False)) + for case in all_cases(): + samples_by_backend = {"native": [], "pure": []} + backends = (("native", ktav), ("pure", pure)) + for repeat in range(args.repeats): + order = backends if repeat % 2 == 0 else tuple(reversed(backends)) + for backend, api in order: + result = benchmark(api, backend, case, args.warmup, 1, args.iterations) + samples_by_backend[backend].extend(result["samples_seconds_per_operation"]) + for backend, _api in backends: + result = { + "type": "result", + "backend": backend, + "scenario": case["name"], + "operation": case["operation"], + "source_bytes": len(case["source"].encode("utf-8")), + "iterations": args.iterations, + "warmup": args.warmup, + "samples_seconds_per_operation": samples_by_backend[backend], + "order": "alternating native/pure by repeat", + } + print(json.dumps(result, ensure_ascii=False)) + + +if __name__ == "__main__": + main() From ea2d0bca495f2b71663290212addd77e8166a296 Mon Sep 17 00:00:00 2001 From: Marat K Date: Tue, 27 Oct 2026 16:18:39 +0100 Subject: [PATCH 2/5] style: fix benchmark import spacing Co-Authored-By: Claude Sonnet 5.5 --- examples/bench_edit.py | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/bench_edit.py b/examples/bench_edit.py index a401555..a4dc7df 100644 --- a/examples/bench_edit.py +++ b/examples/bench_edit.py @@ -16,7 +16,6 @@ import ktav from ktav import pure - CASES = ( { "name": "insert-root", From 5fba8b6931fdb1e0a87ec27e0dd77b1410c9c41f Mon Sep 17 00:00:00 2001 From: Marat K Date: Tue, 27 Oct 2026 16:43:59 +0100 Subject: [PATCH 3/5] perf(pure): avoid cloning unchanged root values Copy the expected root mapping without recursively cloning unchanged siblings; retain independent verification and benchmark both implementations on the same runner. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/bench-compare-edit.yml | 51 ++++ examples/bench_compare_edit.py | 224 ++++++++++++++++++ examples/bench_edit.py | 13 +- python/ktav/_pure/_edit_splice.py | 6 +- .../edit/test_insert_remaining_regressions.py | 51 ++++ 5 files changed, 343 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/bench-compare-edit.yml create mode 100644 examples/bench_compare_edit.py diff --git a/.github/workflows/bench-compare-edit.yml b/.github/workflows/bench-compare-edit.yml new file mode 100644 index 0000000..c30e8fc --- /dev/null +++ b/.github/workflows/bench-compare-edit.yml @@ -0,0 +1,51 @@ +name: Compare pure edit benchmark + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + compare: + name: Python 3.9 / Ubuntu + runs-on: ubuntu-latest + steps: + - name: Checkout baseline + uses: actions/checkout@v6 + with: + ref: ea2d0bca495f2b71663290212addd77e8166a296 + path: base + submodules: recursive + - name: Checkout candidate + uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + path: candidate + submodules: recursive + - uses: actions/setup-python@v6 + with: + python-version: "3.9" + - name: Record runner information + shell: bash + run: | + { + echo "baseline_sha=ea2d0bca495f2b71663290212addd77e8166a296" + echo "candidate_sha=${{ github.event.pull_request.head.sha || github.sha }}" + echo "runner_os=$RUNNER_OS" + echo "runner_arch=$RUNNER_ARCH" + echo "runner_name=$RUNNER_NAME" + python --version + uname -a + } > runner-info.txt + - name: Run pure edit benchmark comparison + run: python candidate/examples/bench_compare_edit.py --base-python python --candidate-python python --base-source base --candidate-source candidate > compare.jsonl + - name: Upload raw benchmark outputs and metadata + uses: actions/upload-artifact@v7 + with: + name: bench-compare-edit-${{ github.run_id }} + path: | + compare.jsonl + runner-info.txt + if-no-files-found: error diff --git a/examples/bench_compare_edit.py b/examples/bench_compare_edit.py new file mode 100644 index 0000000..71d083e --- /dev/null +++ b/examples/bench_compare_edit.py @@ -0,0 +1,224 @@ +"""Same-runner pure source-edit comparison for isolated base/candidate checkouts. + +Candidate ``examples/bench_edit.py`` is the sole workload and oracle source. +Only the standard library is used; this harness never builds or installs code. +""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import platform +import subprocess +import sys +from pathlib import Path +from typing import Any + +WORKER = r""" +import importlib.util, json, sys, time +from pathlib import Path +# -I ignores PYTHONPATH; explicitly allow only this checkout's Python source. +source_root = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(source_root / "python")) +bench_path = Path(sys.argv[2]).resolve() +spec = importlib.util.spec_from_file_location("worker_bench_edit", bench_path) +bench = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bench) +import ktav +from ktav import pure +if getattr(ktav, "_HAS_CORE", False): + raise RuntimeError("pure worker unexpectedly loaded native ktav") +for line in sys.stdin: + req = json.loads(line) + case = req["case"] + try: + if req["action"] == "validate": + result = bench.invoke(pure, case) + if result.encode("utf-8") != case["expected"].encode("utf-8"): + raise AssertionError("byte output mismatch") + actual = pure.loads(result) + if actual != case["semantic"]: + raise AssertionError("semantic output mismatch: {!r}".format(actual)) + response = {"ok": True} + else: + for _ in range(req["warmup"]): + bench.invoke(pure, case) + start = time.perf_counter() + for _ in range(req["iterations"]): + bench.invoke(pure, case) + response = {"seconds_per_operation": (time.perf_counter() - start) / req["iterations"]} + except Exception as exc: + response = {"error": "{}: {}".format(type(exc).__name__, exc)} + print(json.dumps(response, ensure_ascii=False), flush=True) +""" + + +def sha(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def request(proc: subprocess.Popen[str], payload: dict[str, Any]) -> dict[str, Any]: + if proc.poll() is not None: + raise RuntimeError(f"worker exited with status {proc.returncode}") + if proc.stdin is None or proc.stdout is None: + raise RuntimeError("worker pipes are unavailable") + proc.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n") + proc.stdin.flush() + line = proc.stdout.readline() + if not line: + raise RuntimeError(f"worker exited without a response (status {proc.poll()})") + response = json.loads(line) + if "error" in response: + raise RuntimeError(response["error"]) + return response + + +def load_candidate_bench(path: Path, candidate_root: Path) -> Any: + sys.path.insert(0, str(candidate_root / "python")) + try: + spec = importlib.util.spec_from_file_location("candidate_bench_edit", str(path)) + if spec is None or spec.loader is None: + raise RuntimeError("cannot load candidate examples/bench_edit.py") + bench = importlib.util.module_from_spec(spec) + spec.loader.exec_module(bench) + return bench + finally: + sys.path.pop(0) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--base-python", required=True, help="base isolated environment interpreter" + ) + parser.add_argument( + "--base-source", + "--base-root", + dest="base_source", + required=True, + type=Path, + help="base checkout root", + ) + parser.add_argument( + "--candidate-python", required=True, help="candidate isolated environment interpreter" + ) + parser.add_argument( + "--candidate-source", + "--candidate-root", + dest="candidate_source", + required=True, + type=Path, + help="candidate checkout root; workloads/oracles", + ) + parser.add_argument("--warmup", type=int, default=100) + parser.add_argument("--repeats", type=int, default=5) + parser.add_argument("--iterations", type=int, default=100) + args = parser.parse_args() + if min(args.warmup, args.repeats, args.iterations) < 1: + parser.error("warmup, repeats, and iterations must be positive") + + roots = {"base": args.base_source.resolve(), "candidate": args.candidate_source.resolve()} + scripts = {name: roots[name] / "examples" / "bench_edit.py" for name in roots} + for script in scripts.values(): + if not script.is_file(): + parser.error(f"missing benchmark script: {script}") + candidate_script = scripts["candidate"] + candidate_bench = load_candidate_bench(candidate_script, roots["candidate"]) + cases = candidate_bench.all_cases() + interpreters = {"base": args.base_python, "candidate": args.candidate_python} + workers: dict[str, subprocess.Popen[str]] = {} + try: + for label in ("base", "candidate"): + workers[label] = subprocess.Popen( + [ + interpreters[label], + "-I", + "-u", + "-c", + WORKER, + str(roots[label]), + str(candidate_script), + ], + cwd=str(roots[label]), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=None, + text=True, + encoding="utf-8", + ) + # Each identical candidate case is checked by both implementations before timing. + for case in cases: + for label in ("base", "candidate"): + request(workers[label], {"action": "validate", "case": case}) + + metadata = { + "type": "metadata", + "mode": "pure", + "python_runner": sys.version, + "platform": platform.platform(), + "machine": platform.machine(), + "warmup": args.warmup, + "repeats": args.repeats, + "iterations": args.iterations, + "scenario_count": len(cases), + "source_sha256": {key: sha(path) for key, path in scripts.items()}, + "candidate_bench_edit_sha256": sha(scripts["candidate"]), + "interpreters": interpreters, + "source_roots": {key: str(value) for key, value in roots.items()}, + } + print(json.dumps(metadata, ensure_ascii=False), flush=True) + for case in cases: + for repeat in range(args.repeats): + order = ("base", "candidate") if repeat % 2 == 0 else ("candidate", "base") + for label in order: + sample = request( + workers[label], + { + "action": "time", + "case": case, + "warmup": args.warmup, + "iterations": args.iterations, + }, + ) + print( + json.dumps( + { + "type": "result", + "backend": label, + "scenario": case["name"], + "operation": case["operation"], + "source_bytes": len(case["source"].encode("utf-8")), + "repeat": repeat, + "order": list(order), + "iterations": args.iterations, + "warmup": args.warmup, + "seconds_per_operation": sample["seconds_per_operation"], + }, + ensure_ascii=False, + ), + flush=True, + ) + finally: + for proc in workers.values(): + if proc.stdin is not None and not proc.stdin.closed: + proc.stdin.close() + if proc.poll() is None: + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + + +if __name__ == "__main__": + main() diff --git a/examples/bench_edit.py b/examples/bench_edit.py index a4dc7df..9ecd420 100644 --- a/examples/bench_edit.py +++ b/examples/bench_edit.py @@ -126,7 +126,18 @@ def wide_root_cases() -> tuple[dict[str, Any], ...]: def all_cases() -> tuple[dict[str, Any], ...]: - return CASES + wide_root_cases() + values = list(range(512)) + source = "payload: [" + ", ".join(map(str, values)) + "]\n" + nested_sibling = { + "name": "root-insert-large-unchanged-array", + "operation": "insert_value", + "source": source, + "path": "added", + "value": 7, + "expected": source + "added: 7\n", + "semantic": {"payload": values, "added": 7}, + } + return (*CASES, *wide_root_cases(), nested_sibling) def invoke(api: Any, case: dict[str, Any]) -> str: diff --git a/python/ktav/_pure/_edit_splice.py b/python/ktav/_pure/_edit_splice.py index 1f9339c..d96b002 100644 --- a/python/ktav/_pure/_edit_splice.py +++ b/python/ktav/_pure/_edit_splice.py @@ -465,7 +465,11 @@ def _verify_insert_result( except KtavDecodeError as exc: raise _unsupported(f"patch produced an invalid document: {exc}") from None try: - expected = _clone_value(original) + expected = ( + dict(original) + if not segments[:-1] and isinstance(original, dict) + else _clone_value(original) + ) parent = expected for seg in segments[:-1]: if isinstance(parent, dict): diff --git a/tests/edit/test_insert_remaining_regressions.py b/tests/edit/test_insert_remaining_regressions.py index c316b1b..f8f9754 100644 --- a/tests/edit/test_insert_remaining_regressions.py +++ b/tests/edit/test_insert_remaining_regressions.py @@ -6,6 +6,7 @@ import pytest +from ktav import _pure from tests.edit._backends import edit_apis APIS = edit_apis() @@ -72,6 +73,56 @@ def test_insert_empty_explicit_and_nested_multiline_blocks(api: Any) -> None: assert api.loads(actual) == {"outer": {"inner": {"y": 2}}} +@pytest.mark.parametrize("api", APIS) +def test_insert_root_preserves_deep_unchanged_siblings_exactly(api: Any) -> None: + source = ( + "## café 根\r\n" + 'profile: {name: "Zoë", data: [{label: "雪だるま☃", values: [1, {keep: true}]}, ' + '["naïve", {deep: {leaf: "終"}}]]}\r\n' + 'other: [{preserved: "🙂"}, [3, 4]]\r\n' + 'settings: {flags: [false, null], nested: {enabled: true}}\r\n' + ) + expected = ( + "## café 根\r\n" + 'profile: {name: "Zoë", data: [{label: "雪だるま☃", values: [1, {keep: true}]}, ' + '["naïve", {deep: {leaf: "終"}}]]}\r\n' + 'other: [{preserved: "🙂"}, [3, 4]]\r\n' + 'settings: {flags: [false, null], nested: {enabled: true}}\r\n' + "added: 7\r\n" + ) + actual = api.insert_value(source, "added", 7) + assert actual.encode("utf-8") == expected.encode("utf-8") + assert api.loads(actual) == { + "profile": { + "name": "Zoë", + "data": [ + {"label": "雪だるま☃", "values": [1, {"keep": True}]}, + ["naïve", {"deep": {"leaf": "終"}}], + ], + }, + "other": [{"preserved": "🙂"}, [3, 4]], + "settings": {"flags": [False, None], "nested": {"enabled": True}}, + "added": 7, + } + + +def test_insert_root_fast_path_does_not_clone_nested_sibling(monkeypatch: pytest.MonkeyPatch) -> None: + from ktav._pure import _edit_splice + + def fail_clone(value: Any) -> Any: + raise AssertionError("root insert must not recursively clone unchanged values") + + monkeypatch.setattr(_edit_splice, "_clone_value", fail_clone) + source = 'profile: {name: "Zoë", data: [{deep: [1, {keep: true}]}]}\r\n' + expected = source + "added: 7\r\n" + actual = _pure.insert_value(source, "added", 7) + assert actual.encode("utf-8") == expected.encode("utf-8") + assert _pure.loads(actual) == { + "profile": {"name": "Zoë", "data": [{"deep": [1, {"keep": True}]}]}, + "added": 7, + } + + @pytest.mark.parametrize("api", APIS) def test_insert_array_parent_reports_unsupported(api: Any) -> None: with pytest.raises(api.KtavEditError) as caught: From e261a5aeab43ec246446d4765fec12c01cc54d5a Mon Sep 17 00:00:00 2001 From: Marat K Date: Tue, 27 Oct 2026 16:57:49 +0100 Subject: [PATCH 4/5] test: correct inline value semantics Preserve exact-source assertions while expecting literal quote characters from Ktav inline values; fix Ruff import and line formatting. Co-Authored-By: Claude Sonnet 5.5 --- tests/edit/test_insert_remaining_regressions.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/tests/edit/test_insert_remaining_regressions.py b/tests/edit/test_insert_remaining_regressions.py index f8f9754..c89c600 100644 --- a/tests/edit/test_insert_remaining_regressions.py +++ b/tests/edit/test_insert_remaining_regressions.py @@ -5,8 +5,8 @@ from typing import Any import pytest - from ktav import _pure + from tests.edit._backends import edit_apis APIS = edit_apis() @@ -94,19 +94,21 @@ def test_insert_root_preserves_deep_unchanged_siblings_exactly(api: Any) -> None assert actual.encode("utf-8") == expected.encode("utf-8") assert api.loads(actual) == { "profile": { - "name": "Zoë", + "name": '"Zoë"', "data": [ - {"label": "雪だるま☃", "values": [1, {"keep": True}]}, - ["naïve", {"deep": {"leaf": "終"}}], + {"label": '"雪だるま☃"', "values": [1, {"keep": True}]}, + ['"naïve"', {"deep": {"leaf": '"終"'}}], ], }, - "other": [{"preserved": "🙂"}, [3, 4]], + "other": [{"preserved": '"🙂"'}, [3, 4]], "settings": {"flags": [False, None], "nested": {"enabled": True}}, "added": 7, } -def test_insert_root_fast_path_does_not_clone_nested_sibling(monkeypatch: pytest.MonkeyPatch) -> None: +def test_insert_root_fast_path_does_not_clone_nested_sibling( + monkeypatch: pytest.MonkeyPatch, +) -> None: from ktav._pure import _edit_splice def fail_clone(value: Any) -> Any: @@ -118,7 +120,7 @@ def fail_clone(value: Any) -> Any: actual = _pure.insert_value(source, "added", 7) assert actual.encode("utf-8") == expected.encode("utf-8") assert _pure.loads(actual) == { - "profile": {"name": "Zoë", "data": [{"deep": [1, {"keep": True}]}]}, + "profile": {"name": '"Zoë"', "data": [{"deep": [1, {"keep": True}]}]}, "added": 7, } From a6ac70bcf568fe2527c4ab7018a9df36ae6daf7a Mon Sep 17 00:00:00 2001 From: Marat K Date: Tue, 27 Oct 2026 17:06:05 +0100 Subject: [PATCH 5/5] style: format mutation regression strings Co-Authored-By: Claude Sonnet 5.5 --- tests/edit/test_insert_remaining_regressions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/edit/test_insert_remaining_regressions.py b/tests/edit/test_insert_remaining_regressions.py index c89c600..92f7776 100644 --- a/tests/edit/test_insert_remaining_regressions.py +++ b/tests/edit/test_insert_remaining_regressions.py @@ -80,14 +80,14 @@ def test_insert_root_preserves_deep_unchanged_siblings_exactly(api: Any) -> None 'profile: {name: "Zoë", data: [{label: "雪だるま☃", values: [1, {keep: true}]}, ' '["naïve", {deep: {leaf: "終"}}]]}\r\n' 'other: [{preserved: "🙂"}, [3, 4]]\r\n' - 'settings: {flags: [false, null], nested: {enabled: true}}\r\n' + "settings: {flags: [false, null], nested: {enabled: true}}\r\n" ) expected = ( "## café 根\r\n" 'profile: {name: "Zoë", data: [{label: "雪だるま☃", values: [1, {keep: true}]}, ' '["naïve", {deep: {leaf: "終"}}]]}\r\n' 'other: [{preserved: "🙂"}, [3, 4]]\r\n' - 'settings: {flags: [false, null], nested: {enabled: true}}\r\n' + "settings: {flags: [false, null], nested: {enabled: true}}\r\n" "added: 7\r\n" ) actual = api.insert_value(source, "added", 7)