From 5b8443b297e0bd020da84e77621ef3c53b934361 Mon Sep 17 00:00:00 2001 From: Matias Date: Tue, 4 Aug 2026 02:26:17 -0300 Subject: [PATCH] perf(search): the prefilter was matching JSON field names, not commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The raw-line prefilter scanned the whole encoded record, and every record contains the field *names* `command`, `dir`, `exit_code`, `duration_ms`, `session` and `imported`. So searching for `exit` — or `dir`, `command`, `port`, `code`, `ms`, `ts` — matched **every line in the store**, the filter admitted all of them, and the queries most likely to be slow were the ones that got no speedup at all. Measured over 20,000 records before the fix: exit -> 20000/20000 lines matched (no filtering whatsoever) dir -> 20000/20000 command -> 20000/20000 git -> 2000/20000 Never a correctness bug — `_matches` re-checks the parsed command, and the command field is the only thing it looks at — which is exactly why nobody noticed. Narrowing the scan to the same field the real filter uses makes the two agree. Found while building the concept map, where `port` queries hit it through `"imported":false`. The first attempt was worse than the bug. Walking the line character by character in Python to find the field cost **165ms per 100k records against 137ms for simply parsing all of them** — a filter slower than the work it skips. The version here is `str.find` in C, with a fast path for the shape mem itself writes and a Python loop only for the rare escaped quote: exit -> 0 parsed 62ms (was: 100000 parsed, 137ms) git -> 10096 parsed 76ms no filter -> 100000 parsed 140ms A record it cannot recognise — hand-edited, truncated, written by another tool — is scanned whole. Admitting too much is the safe direction; excluding a real match is not. Both failure modes are now pinned: a test that a field name no longer matches every record, and a `perf` test that a field-name query is not slower than no filter at all. --- src/mem/storage.py | 82 ++++++++++++++++++++++++++++- tests/test_storage.py | 120 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+), 1 deletion(-) diff --git a/src/mem/storage.py b/src/mem/storage.py index 0717c8c..77b09a0 100644 --- a/src/mem/storage.py +++ b/src/mem/storage.py @@ -418,6 +418,86 @@ def prefilter_needles(terms: Iterable[str]) -> list[str]: return needles +_COMMAND_KEY = '"command"' +_COMMAND_PREFIX = '{"command":"' + + +def command_span(line: str) -> str: + """The command text inside a raw JSONL line, without decoding the line. + + The prefilter used to scan the whole line, which includes the field + *names*. Every record contains ``"command"``, ``"dir"``, ``"exit_code"``, + ``"duration_ms"``, ``"session"`` and ``"imported"``, so searching for any + of `command`, `dir`, `exit`, `code`, `port`, `ms`, `ts` or `session` + matched **every line in the store** and the filter admitted all of them. + Measured over 20,000 records: `exit` matched 20,000 and `git` matched + 2,000 — so the queries most likely to be slow were exactly the ones that + got no speedup at all. + + It was never a correctness bug — ``_matches`` re-checks the parsed + command, and the command field is the only thing it looks at — which is + why it went unnoticed. Narrowing the scan to the same field the real + filter uses makes the two agree. + + Falls back to the whole line for anything it cannot locate: a + hand-written or truncated record must still be considered, and admitting + too much is the safe direction. + """ + # Fast path: this is how mem itself writes every record, so it is the + # shape of essentially every line, and it skips the search entirely. + if line.startswith(_COMMAND_PREFIX): + index = len(_COMMAND_PREFIX) + else: + index = _locate_value(line) + if index < 0: + return line + + # Everything below is `str.find`, which runs in C. An earlier version + # walked the line character by character in Python and cost more than the + # `json.loads` it was there to avoid — 165ms per 100k records against + # 137ms for simply parsing everything. A filter slower than the work it + # skips is worse than no filter. + cursor = index + while True: + end = line.find('"', cursor) + if end == -1: + return line # unterminated: scan the whole line rather than none + # A quote inside a JSON string is escaped, so the closing one is the + # first preceded by an even number of backslashes. + backslashes = 0 + position = end - 1 + while position >= index and line[position] == "\\": + backslashes += 1 + position -= 1 + if backslashes % 2 == 0: + return line[index:end] + cursor = end + 1 + + +def _locate_value(line: str) -> int: + """Index just past the opening quote of the ``command`` value, or -1. + + Only reached for records mem did not write — a hand-edited file, or one + produced by another tool — so it tolerates whitespace the compact + encoder never emits. + """ + start = line.find(_COMMAND_KEY) + if start == -1: + return -1 + index = start + len(_COMMAND_KEY) + length = len(line) + while index < length and line[index] in " \t": + index += 1 + if index >= length or line[index] != ":": + return -1 + index += 1 + while index < length and line[index] in " \t": + index += 1 + if index >= length or line[index] != '"': + return -1 + return index + 1 + + def read_commands( repo: str, needles: Sequence[str] | None = None ) -> Iterator[CapturedCommand]: @@ -439,7 +519,7 @@ def read_commands( if not line: continue if needles: - lowered = line.lower() + lowered = command_span(line).lower() if not all(needle in lowered for needle in needles): continue try: diff --git a/tests/test_storage.py b/tests/test_storage.py index af05bdb..70f26ef 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -811,3 +811,123 @@ def test_a_selective_query_is_much_faster_than_a_full_parse(self, tmp_mem_dir): assert prefiltered * 3 < full, ( f"prefilter gave no real speedup: {prefiltered:.3f}s vs {full:.3f}s" ) + + def test_a_field_name_query_is_not_slower_than_no_filter(self, tmp_mem_dir): + """The prefilter must never cost more than the work it skips. + + Two ways to get this wrong, and both happened. Scanning the whole raw + line made `exit` match every record via `exit_code`, so the filter + admitted everything and saved nothing. Narrowing the scan with a + character-by-character Python loop then cost *more* than the + `json.loads` it existed to avoid — 165ms per 100k records against + 137ms for simply parsing them all. + """ + now = int(time.time()) + storage.ensure_dirs() + storage.repo_file("_global").write_text( + "\n".join( + make_command(command=f"tool-{i} run", ts=now, repo=None).to_jsonl() + for i in range(20_000) + ) + + "\n", + encoding="utf-8", + ) + + start = time.perf_counter() + everything = len(list(storage.read_commands("_global"))) + full = time.perf_counter() - start + + # "exit" appears in the `exit_code` field name of every single record. + needles = storage.prefilter_needles(["exit"]) + start = time.perf_counter() + matched = len(list(storage.read_commands("_global", needles))) + filtered = time.perf_counter() - start + + assert everything == 20_000 + assert matched == 0, "a field name still matches every record" + assert filtered < full, ( + f"the prefilter cost more than parsing: {filtered:.3f}s vs {full:.3f}s" + ) + + +class TestCommandSpan: + """The prefilter must scan the command, not the whole encoded record. + + Every record contains the field *names* `command`, `dir`, `exit_code`, + `duration_ms`, `session` and `imported`, so scanning the raw line made a + search for `exit` — or `dir`, or `port` — match every line in the store. + The filter admitted everything and saved nothing, precisely for the + queries most likely to be slow. + """ + + def test_it_returns_only_the_command(self): + line = make_command(command="git push", repo="/r").to_jsonl() + + assert storage.command_span(line) == "git push" + + @pytest.mark.parametrize( + "command", + [ + 'echo "hi"', # escaped quotes must not end the span early + r"grep \d+ log", + r'sed "s/\\/x/g"', + "echo café", + "printf 'a\tb'", + "curl -H 'X: {\"k\":1}'", + "", + ], + ) + def test_it_survives_anything_a_command_can_contain(self, command: str): + """The span is the *encoded* text, which is what the needles match. + + Deliberately not the decoded command: decoding is the expensive step + this whole path exists to skip, and the needles are built from + characters that survive JSON encoding unchanged precisely so they can + be matched against encoded text. `json.dumps(x)[1:-1]` is that + encoding with the surrounding quotes removed. + """ + line = json.dumps({"command": command, "ts": 1, "dir": "/x"}) + + assert storage.command_span(line) == json.dumps(command)[1:-1] + + @pytest.mark.parametrize( + "line", + [ + "not json at all", + "{}", + '{"ts": 1}', # no command field + '{"command": 42}', # not a string + '{"command": "unterminated', + "", + ], + ) + def test_an_unrecognisable_line_is_scanned_whole(self, line: str): + """Admitting too much is the safe direction; excluding a match is not.""" + assert storage.command_span(line) == line + + def test_whitespace_after_the_colon_is_tolerated(self): + """These files are documented as hand-editable, so formatting varies.""" + assert storage.command_span('{"command" : "ls -la", "ts": 1}') == "ls -la" + + def test_a_field_name_no_longer_matches_every_record(self, tmp_mem_dir): + """The bug itself: `exit` matched every line because of `exit_code`.""" + storage.append_command(make_command(command="git push", repo=None)) + storage.append_command(make_command(command="exit", repo=None)) + + found = [c.command for c in storage.read_commands("_global", ["exit"])] + + assert found == ["exit"] + + def test_a_directory_name_no_longer_matches_the_command(self, tmp_mem_dir): + """`repo` and `dir` are stored on every record and are not the command.""" + storage.append_command( + make_command(command="ls", repo="/Users/me/projects/kubernetes") + ) + + matched = list( + storage.read_commands( + storage.repo_key("/Users/me/projects/kubernetes"), ["kubernetes"] + ) + ) + + assert matched == [], "the prefilter matched the repo path, not the command"