syntext 1.0.0

Hybrid code search index for agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
#!/usr/bin/env python3
"""Benchmark syntext against rg and grep on an external Git repository.

This script is intentionally simple:
- It measures syntext index build time separately.
- It then reuses one built index to benchmark repeated searches.
- It compares against ripgrep and grep over the same repository.

Default grep mode uses `git ls-files` to avoid benchmarking recursive grep over
ignored/build output, which is usually a misleading baseline.
"""

from __future__ import annotations

import argparse
import json
import os
import shlex
import statistics
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable


SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent
DEFAULT_SYNTEXT_BIN = REPO_ROOT / "target" / "release" / "st"
DEFAULT_PRESET_FILE = REPO_ROOT / "benchmarks" / "repo_presets.json"
DEFAULT_BUILD_ITERATIONS = 3
DEFAULT_SEARCH_ITERATIONS = 5
DEFAULT_WARMUPS = 1


@dataclass(frozen=True)
class QuerySpec:
    mode: str
    pattern: str

    @property
    def name(self) -> str:
        cleaned = self.pattern.replace("\n", " ").strip()
        if len(cleaned) > 48:
            cleaned = f"{cleaned[:45]}..."
        return f"{self.mode}:{cleaned}"


@dataclass(frozen=True)
class PresetSpec:
    name: str
    display_name: str
    repo_url: str
    suggested_local_path: str
    language_focus: str
    scale: str
    build_iterations: int
    search_iterations: int
    warmups: int
    tools: tuple[str, ...]
    queries: tuple[QuerySpec, ...]
    notes: tuple[str, ...]


def parse_query(value: str) -> QuerySpec:
    try:
        mode, pattern = value.split(":", 1)
    except ValueError as exc:
        raise argparse.ArgumentTypeError(
            f"invalid query {value!r}, expected literal:<pattern> or regex:<pattern>"
        ) from exc
    if mode not in {"literal", "regex"}:
        raise argparse.ArgumentTypeError(
            f"invalid query mode {mode!r}, expected literal or regex"
        )
    if not pattern:
        raise argparse.ArgumentTypeError("query pattern must not be empty")
    return QuerySpec(mode=mode, pattern=pattern)


def load_presets(path: Path) -> dict[str, PresetSpec]:
    raw = json.loads(path.read_text())
    presets: dict[str, PresetSpec] = {}
    for item in raw.get("presets", []):
        preset = PresetSpec(
            name=item["name"],
            display_name=item["display_name"],
            repo_url=item["repo_url"],
            suggested_local_path=item["suggested_local_path"],
            language_focus=item["language_focus"],
            scale=item["scale"],
            build_iterations=int(item["build_iterations"]),
            search_iterations=int(item["search_iterations"]),
            warmups=int(item["warmups"]),
            tools=tuple(item.get("tools", ["syntext", "rg", "grep"])),
            queries=tuple(parse_query(query) for query in item["queries"]),
            notes=tuple(item.get("notes", [])),
        )
        presets[preset.name] = preset
    return presets


def print_presets(presets: dict[str, PresetSpec]) -> None:
    print("# Benchmark Presets\n")
    for preset in sorted(presets.values(), key=lambda item: item.name):
        print(f"- `{preset.name}`: {preset.display_name}")
        print(f"  repo: `{preset.repo_url}`")
        print(f"  suggested local path: `{preset.suggested_local_path}`")
        print(f"  focus: `{preset.language_focus}`, scale: `{preset.scale}`")
        print(
            "  default settings: "
            f"build_iterations={preset.build_iterations}, "
            f"search_iterations={preset.search_iterations}, warmups={preset.warmups}"
        )
        print("  tools: " + ", ".join(f"`{tool}`" for tool in preset.tools))
        print(
            "  queries: "
            + ", ".join(f"`{query.name}`" for query in preset.queries)
        )
        if preset.notes:
            print("  notes: " + " ".join(preset.notes))
        print()


def tracked_files(repo_root: Path) -> bytes:
    result = subprocess.run(
        ["git", "-C", str(repo_root), "ls-files", "-z"],
        check=True,
        capture_output=True,
    )
    return result.stdout


def tracked_file_count(repo_root: Path) -> int:
    output = tracked_files(repo_root)
    if not output:
        return 0
    return sum(1 for part in output.split(b"\0") if part)


def ensure_syntext_binary(syntext_bin: Path) -> None:
    if syntext_bin.exists():
        return
    subprocess.run(
        ["cargo", "build", "--release", "--bin", "st"],
        cwd=REPO_ROOT,
        check=True,
    )


def run_timed(
    cmd: list[str] | str,
    *,
    cwd: Path,
    env: dict[str, str],
    shell: bool = False,
    allowed_codes: Iterable[int] = (0,),
) -> float:
    start = time.perf_counter()
    completed = subprocess.run(
        cmd,
        cwd=cwd,
        env=env,
        shell=shell,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        text=False,
    )
    elapsed_ms = (time.perf_counter() - start) * 1000.0
    if completed.returncode not in set(allowed_codes):
        raise RuntimeError(f"command failed with exit {completed.returncode}: {cmd!r}")
    return elapsed_ms


def output_line_count(
    cmd: list[str] | str,
    *,
    cwd: Path,
    env: dict[str, str],
    shell: bool = False,
    allowed_codes: Iterable[int] = (0,),
) -> int:
    completed = subprocess.run(
        cmd,
        cwd=cwd,
        env=env,
        shell=shell,
        capture_output=True,
        text=False,
    )
    if completed.returncode not in set(allowed_codes):
        raise RuntimeError(f"command failed with exit {completed.returncode}: {cmd!r}")
    stdout = completed.stdout
    if not stdout:
        return 0
    count = stdout.count(b"\n")
    if not stdout.endswith(b"\n"):
        count += 1
    return count


def summarize(samples_ms: list[float]) -> dict[str, float]:
    ordered = sorted(samples_ms)
    return {
        "median_ms": round(statistics.median(ordered), 3),
        "min_ms": round(ordered[0], 3),
        "max_ms": round(ordered[-1], 3),
    }


def summarize_int(samples: list[int], unit: str) -> dict[str, int]:
    ordered = sorted(samples)
    return {
        f"median_{unit}": statistics.median_low(ordered),
        f"min_{unit}": ordered[0],
        f"max_{unit}": ordered[-1],
    }


def dir_size_bytes(root: Path) -> int:
    total = 0
    for path in root.rglob("*"):
        if path.is_file():
            total += path.stat().st_size
    return total


def syntext_search_cmd(
    syntext_bin: Path, repo_root: Path, index_dir: Path, query: QuerySpec
) -> list[str]:
    cmd = [
        str(syntext_bin),
        "--repo-root",
        str(repo_root),
        "--index-dir",
        str(index_dir),
    ]
    if query.mode == "literal":
        cmd.append("-F")
    cmd.append(query.pattern)
    return cmd


def syntext_bench_search_cmd(
    syntext_bin: Path,
    repo_root: Path,
    index_dir: Path,
    queries: list[QuerySpec],
    iterations: int,
    warmups: int,
) -> list[str]:
    cmd = [
        str(syntext_bin),
        "--repo-root",
        str(repo_root),
        "--index-dir",
        str(index_dir),
        "bench-search",
        "--iterations",
        str(iterations),
        "--warmups",
        str(warmups),
    ]
    for query in queries:
        cmd.extend(["--query", query.name])
    return cmd


def rg_search_cmd(repo_root: Path, query: QuerySpec) -> list[str]:
    cmd = ["rg", "-n", "--no-heading", "--color", "never", "--hidden"]
    if query.mode == "literal":
        cmd.append("-F")
    cmd.extend([query.pattern, str(repo_root)])
    return cmd


def grep_search_cmd(
    repo_root: Path, tracked_list: Path, query: QuerySpec, grep_mode: str
) -> str:
    grep_flag = "-F" if query.mode == "literal" else "-E"
    pattern = shlex.quote(query.pattern)
    if grep_mode == "tracked":
        return (
            f"xargs -0 grep -nIH {grep_flag} -e {pattern} "
            f"< {shlex.quote(str(tracked_list))}"
        )
    return (
        f"grep -RInH --exclude-dir=.git {grep_flag} -e {pattern} "
        f"{shlex.quote(str(repo_root))}"
    )


def benchmark_command(
    cmd: list[str] | str,
    *,
    cwd: Path,
    env: dict[str, str],
    warmups: int,
    iterations: int,
    shell: bool = False,
    allowed_codes: Iterable[int] = (0, 1),
) -> dict[str, float]:
    for _ in range(warmups):
        run_timed(cmd, cwd=cwd, env=env, shell=shell, allowed_codes=allowed_codes)
    samples = [
        run_timed(cmd, cwd=cwd, env=env, shell=shell, allowed_codes=allowed_codes)
        for _ in range(iterations)
    ]
    return summarize(samples)


def parse_tools(value: str) -> tuple[str, ...]:
    allowed = {"syntext", "rg", "grep"}
    tools = tuple(part.strip() for part in value.split(",") if part.strip())
    if not tools:
        raise argparse.ArgumentTypeError("tool list must not be empty")
    unknown = [tool for tool in tools if tool not in allowed]
    if unknown:
        raise argparse.ArgumentTypeError(
            f"unknown tool(s): {', '.join(unknown)}; expected one of syntext, rg, grep"
        )
    return tools


def syntext_batch_results(
    cmd: list[str],
    *,
    cwd: Path,
    env: dict[str, str],
) -> dict[str, dict[str, object]]:
    completed = subprocess.run(
        cmd,
        cwd=cwd,
        env=env,
        capture_output=True,
        text=True,
        check=False,
    )
    if completed.returncode != 0:
        raise RuntimeError(
            f"command failed with exit {completed.returncode}: {cmd!r}\n{completed.stderr}"
        )
    payload = json.loads(completed.stdout)
    return {
        item["query"]: {
            "count": item["count"],
            "timings_ms": item["timings_ms"],
        }
        for item in payload.get("queries", [])
    }


def report_tools(tools: tuple[str, ...], syntext_search_mode: str) -> list[str]:
    expanded: list[str] = []
    for tool in tools:
        if tool == "syntext" and syntext_search_mode == "both":
            expanded.extend(["syntext-fork", "syntext-persistent"])
        else:
            expanded.append(tool)
    return expanded


def render_markdown_report(report: dict[str, object]) -> str:
    lines: list[str] = []
    lines.append("# External Benchmark")
    lines.append("")
    lines.append(f"- Repo: `{report['repo']}`")
    if report["preset"]:
        lines.append(f"- Preset: `{report['preset']}`")
    lines.append(f"- Tracked files: `{report['tracked_files']}`")
    lines.append(f"- Grep mode: `{report['grep_mode']}`")
    lines.append(f"- Tools: `{', '.join(report['tools'])}`")
    lines.append(f"- Syntext build iterations: `{report['build_iterations']}`")
    lines.append(
        f"- Search iterations per tool/query: `{report['search_iterations']}`"
    )
    lines.append(f"- Syntext search mode: `{report['syntext_search_mode']}`")
    if report["build_only"]:
        lines.append("- Mode: `build-only`")
    lines.append("")

    build_summary = report["syntext_index_build_ms"]
    size_summary = report["syntext_index_bytes"]
    lines.append("## Syntext index build")
    lines.append("")
    lines.append(
        f"- median: `{build_summary['median_ms']}` ms"
        f", min: `{build_summary['min_ms']}` ms"
        f", max: `{build_summary['max_ms']}` ms"
    )
    lines.append(
        f"- index bytes: median `{size_summary['median_bytes']}`"
        f", min `{size_summary['min_bytes']}`"
        f", max `{size_summary['max_bytes']}`"
    )
    lines.append("")

    if report["queries"]:
        lines.extend(render_markdown_tables(report))
        lines.append("")
    lines.append("## Notes")
    lines.append("")
    lines.append(
        "- `syntext` search latency excludes index build time, which is reported separately."
    )
    lines.append(
        "- `syntext` index byte totals measure the full on-disk index directory for each build iteration."
    )
    if report["syntext_search_mode"] == "both":
        lines.append(
            "- `syntext-fork` measures one process per query. `syntext-persistent` reuses one opened index for all queries in the run."
        )
    if report["grep_mode"] == "tracked" and "grep" in report["tools"]:
        lines.append(
            "- `grep` uses `git ls-files` as its file list. That is a better baseline than raw recursive grep, but it is still not ignore-aware in the same way as `rg`."
        )
    elif "grep" in report["tools"]:
        lines.append(
            "- `grep` uses recursive traversal and may include files that `rg` or `syntext` skip."
        )

    mismatched = [
        result
        for result in report["queries"]
        if len(set(result["counts"].values())) != 1
    ]
    if mismatched:
        lines.append(
            "- Match counts differ for at least one query. Treat timing comparisons cautiously."
        )
        literal_mismatches = [
            result
            for result in mismatched
            if str(result["query"]).startswith("literal:")
        ]
        if literal_mismatches:
            lines.append(
                "- For literal queries, a lower `syntext` count often means the pattern is being matched as a mid-token substring inside larger identifiers. Current `syntext` coverage guarantees are strongest for token-aligned queries."
            )
    return "\n".join(lines)


def render_markdown_tables(report: dict[str, object]) -> list[str]:
    lines: list[str] = []
    lines.append("## Search latency")
    lines.append("")
    lines.append("| Query | Tool | Matches | Median ms | Min ms | Max ms |")
    lines.append("|---|---:|---:|---:|---:|---:|")
    for result in report["queries"]:
        query_name = result["query"]
        counts = result["counts"]
        timings = result["timings_ms"]
        for tool in report["tools"]:
            summary = timings[tool]
            lines.append(
                f"| `{query_name}` | `{tool}` | `{counts[tool]}` | "
                f"`{summary['median_ms']}` | `{summary['min_ms']}` | `{summary['max_ms']}` |"
            )
    return lines


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--repo", help="Git repository to benchmark")
    parser.add_argument(
        "--preset",
        help="Named benchmark preset from the preset catalog",
    )
    parser.add_argument(
        "--preset-file",
        default=str(DEFAULT_PRESET_FILE),
        help="JSON preset catalog to load, default: benchmarks/repo_presets.json",
    )
    parser.add_argument(
        "--list-presets",
        action="store_true",
        help="List available presets and exit",
    )
    parser.add_argument(
        "--syntext-bin",
        default=str(DEFAULT_SYNTEXT_BIN),
        help="Path to syntext binary, default: target/release/st",
    )
    parser.add_argument(
        "--query",
        action="append",
        type=parse_query,
        default=[],
        help="Query spec, for example literal:workspace or regex:LanguageServer(Id|Status)",
    )
    parser.add_argument(
        "--build-iterations",
        type=int,
        default=None,
        help="Number of syntext index builds to time",
    )
    parser.add_argument(
        "--search-iterations",
        type=int,
        default=None,
        help="Number of search iterations per tool and query",
    )
    parser.add_argument(
        "--warmups",
        type=int,
        default=None,
        help="Warmup runs before timed search iterations",
    )
    parser.add_argument(
        "--grep-mode",
        choices=("tracked", "recursive"),
        default="tracked",
        help="tracked uses git ls-files, recursive uses grep -R over the repo root",
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Emit machine-readable JSON instead of Markdown",
    )
    parser.add_argument(
        "--markdown-table-only",
        action="store_true",
        help="Emit only the Markdown search-latency table section for easy paste into docs",
    )
    parser.add_argument(
        "--output",
        help="Write the rendered output to a file instead of stdout",
    )
    parser.add_argument(
        "--build-only",
        action="store_true",
        help="Measure repeated syntext index builds and index bytes, skip search benchmarking",
    )
    parser.add_argument(
        "--tools",
        type=parse_tools,
        help="Comma-separated tool set, for example syntext,rg or syntext,rg,grep",
    )
    parser.add_argument(
        "--syntext-search-mode",
        choices=("fork", "persistent", "both"),
        default="fork",
        help="fork runs one syntext process per search; persistent reuses one opened index per benchmark run; both reports both syntext modes side by side",
    )
    args = parser.parse_args()

    preset_file = Path(args.preset_file).resolve()
    presets = load_presets(preset_file) if preset_file.exists() else {}
    if args.list_presets:
        if not presets:
            raise SystemExit(f"no preset catalog found at {preset_file}")
        print_presets(presets)
        return 0

    selected_preset = None
    if args.preset:
        if args.preset not in presets:
            known = ", ".join(sorted(presets))
            raise SystemExit(f"unknown preset {args.preset!r}. Known presets: {known}")
        selected_preset = presets[args.preset]

    repo_arg = args.repo
    if selected_preset and repo_arg is None:
        suggested_path = Path(selected_preset.suggested_local_path)
        if suggested_path.joinpath(".git").exists():
            repo_arg = str(suggested_path)
        else:
            raise SystemExit(
                f"preset {selected_preset.name!r} suggests {suggested_path}, "
                "but that repository is not present locally. Pass --repo explicitly."
            )

    if repo_arg is None:
        raise SystemExit("either --repo or --preset is required")

    repo_root = Path(repo_arg).resolve()
    syntext_bin = Path(args.syntext_bin).resolve()

    if not repo_root.joinpath(".git").exists():
        raise SystemExit(f"{repo_root} is not a Git repository")
    queries = list(args.query)
    if selected_preset and not queries:
        queries = list(selected_preset.queries)
    if not args.build_only and not queries:
        raise SystemExit("at least one --query is required")

    build_iterations = args.build_iterations
    if build_iterations is None:
        build_iterations = (
            selected_preset.build_iterations
            if selected_preset
            else DEFAULT_BUILD_ITERATIONS
        )

    search_iterations = args.search_iterations
    if search_iterations is None:
        search_iterations = (
            selected_preset.search_iterations
            if selected_preset
            else DEFAULT_SEARCH_ITERATIONS
        )

    warmups = args.warmups
    if warmups is None:
        warmups = selected_preset.warmups if selected_preset else DEFAULT_WARMUPS

    tools = args.tools
    if selected_preset and tools is None:
        tools = selected_preset.tools
    if tools is None:
        tools = ("syntext", "rg", "grep")
    display_tools = report_tools(tools, args.syntext_search_mode)

    ensure_syntext_binary(syntext_bin)

    env = dict(os.environ)
    env.setdefault("LC_ALL", "C")

    tracked = tracked_files(repo_root)
    tracked_count = sum(1 for part in tracked.split(b"\0") if part) if tracked else 0

    build_samples: list[float] = []
    build_size_samples: list[int] = []
    for _ in range(build_iterations):
        with tempfile.TemporaryDirectory(prefix="syntext-bench-index-") as index_dir:
            cmd = [
                str(syntext_bin),
                "--repo-root",
                str(repo_root),
                "--index-dir",
                index_dir,
                "index",
                "--quiet",
            ]
            build_samples.append(
                run_timed(cmd, cwd=repo_root, env=env, allowed_codes=(0,))
            )
            build_size_samples.append(dir_size_bytes(Path(index_dir)))

    query_results: list[dict[str, object]] = []
    if not args.build_only:
        with tempfile.TemporaryDirectory(prefix="syntext-bench-search-") as index_dir:
            index_path = Path(index_dir)
            subprocess.run(
                [
                    str(syntext_bin),
                    "--repo-root",
                    str(repo_root),
                    "--index-dir",
                    str(index_path),
                    "index",
                    "--quiet",
                ],
                cwd=repo_root,
                env=env,
                check=True,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )

            with tempfile.NamedTemporaryFile(
                prefix="syntext-bench-files-", delete=False
            ) as filelist:
                filelist.write(tracked)
                tracked_list_path = Path(filelist.name)

            try:
                syntext_batch: dict[str, dict[str, object]] | None = None
                if "syntext" in tools and args.syntext_search_mode in (
                    "persistent",
                    "both",
                ):
                    syntext_batch = syntext_batch_results(
                        syntext_bench_search_cmd(
                            syntext_bin,
                            repo_root,
                            index_path,
                            queries,
                            search_iterations,
                            warmups,
                        ),
                        cwd=repo_root,
                        env=env,
                    )
                for query in queries:
                    syntext_cmd = syntext_search_cmd(
                        syntext_bin, repo_root, index_path, query
                    )
                    rg_cmd = rg_search_cmd(repo_root, query)
                    grep_cmd = grep_search_cmd(
                        repo_root, tracked_list_path, query, args.grep_mode
                    )

                    counts: dict[str, int] = {}
                    timings: dict[str, dict[str, float]] = {}
                    if "syntext" in tools:
                        if args.syntext_search_mode == "both":
                            batch_entry = syntext_batch[query.name]
                            counts["syntext-persistent"] = int(batch_entry["count"])
                            timings["syntext-persistent"] = batch_entry["timings_ms"]
                            counts["syntext-fork"] = output_line_count(
                                syntext_cmd,
                                cwd=repo_root,
                                env=env,
                                allowed_codes=(0, 1),
                            )
                            timings["syntext-fork"] = benchmark_command(
                                syntext_cmd,
                                cwd=repo_root,
                                env=env,
                                warmups=warmups,
                                iterations=search_iterations,
                                allowed_codes=(0, 1),
                            )
                        elif syntext_batch is not None:
                            batch_entry = syntext_batch[query.name]
                            counts["syntext"] = int(batch_entry["count"])
                            timings["syntext"] = batch_entry["timings_ms"]
                        else:
                            counts["syntext"] = output_line_count(
                                syntext_cmd,
                                cwd=repo_root,
                                env=env,
                                allowed_codes=(0, 1),
                            )
                            timings["syntext"] = benchmark_command(
                                syntext_cmd,
                                cwd=repo_root,
                                env=env,
                                warmups=warmups,
                                iterations=search_iterations,
                                allowed_codes=(0, 1),
                            )
                    if "rg" in tools:
                        counts["rg"] = output_line_count(
                            rg_cmd, cwd=repo_root, env=env, allowed_codes=(0, 1)
                        )
                        timings["rg"] = benchmark_command(
                            rg_cmd,
                            cwd=repo_root,
                            env=env,
                            warmups=warmups,
                            iterations=search_iterations,
                            allowed_codes=(0, 1),
                        )
                    if "grep" in tools:
                        counts["grep"] = output_line_count(
                            grep_cmd,
                            cwd=repo_root,
                            env=env,
                            shell=True,
                            allowed_codes=(0, 1, 123),
                        )
                        timings["grep"] = benchmark_command(
                            grep_cmd,
                            cwd=repo_root,
                            env=env,
                            warmups=warmups,
                            iterations=search_iterations,
                            shell=True,
                            allowed_codes=(0, 1, 123),
                        )

                    query_results.append(
                        {
                            "query": query.name,
                            "counts": counts,
                            "timings_ms": timings,
                        }
                    )
            finally:
                tracked_list_path.unlink(missing_ok=True)

    report = {
        "repo": str(repo_root),
        "preset": selected_preset.name if selected_preset else None,
        "tracked_files": tracked_count,
        "grep_mode": args.grep_mode,
        "tools": display_tools,
        "syntext_search_mode": args.syntext_search_mode,
        "build_only": args.build_only,
        "build_iterations": build_iterations,
        "search_iterations": search_iterations,
        "warmups": warmups,
        "syntext_index_build_ms": summarize(build_samples),
        "syntext_index_bytes": summarize_int(build_size_samples, "bytes"),
        "queries": query_results,
    }

    if args.json and args.markdown_table_only:
        raise SystemExit("choose either --json or --markdown-table-only, not both")
    if args.build_only and args.markdown_table_only:
        raise SystemExit("--build-only cannot be combined with --markdown-table-only")

    if args.json:
        rendered = json.dumps(report, indent=2)
    elif args.markdown_table_only:
        rendered = "\n".join(render_markdown_tables(report))
    else:
        rendered = render_markdown_report(report)

    if args.output:
        Path(args.output).write_text(rendered + ("\n" if not rendered.endswith("\n") else ""))
    else:
        print(rendered)

    return 0


if __name__ == "__main__":
    sys.exit(main())