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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 81 additions & 1 deletion src/mem/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict extraction to the top-level command key

For hand-edited records or records produced by another tool, _locate_value selects the first "command" key at any nesting level rather than the top-level field that Pydantic will deserialize. For example, {"metadata":{"command":"git"},"command":"docker ps","ts":1,"dir":"/x"} yields a span of git while CapturedCommand.from_jsonl yields docker ps, so a search for docker silently skips the valid record. Locate the top-level key or fall back to scanning the entire line when that cannot be guaranteed.

Useful? React with 👍 / 👎.

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]:
Expand All @@ -439,7 +519,7 @@ def read_commands(
if not line:
continue
if needles:
lowered = line.lower()
lowered = command_span(line).lower()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply command-only filtering to the interactive finder

This changes only storage.read_commands, but the inspected Ctrl+R path calls tui.rank, whose candidate_lines still executes lowered = line.lower() over the complete JSON record (src/mem/tui.py:187-202). Consequently queries such as exit, command, or port still admit and parse every history entry on every keystroke in the latency-sensitive interactive finder, leaving that user-facing search path unaffected by the optimization.

Useful? React with 👍 / 👎.

if not all(needle in lowered for needle in needles):
continue
try:
Expand Down
120 changes: 120 additions & 0 deletions tests/test_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"