fix(lossless): never grep-fold Go, nginx, klog or access-log timestamps (#4901)

## Description

The lossless search fold splits each line as `path:line:content` and
factors a repeated `path` into a header. `_TIMESTAMP_ROW_RE` (#3419)
keeps timestamped log lines out of it, because a log line has the same
colon shape: folding it hoists the date and hour into a fake file header
and every row starts mid-clock. The fold round-trips byte-exactly, so
the inverse check in `compact_lossless` cannot catch it.

The guard knew ISO, `MM/DD/YYYY`, syslog and bare-clock prefixes, but
not these four common formats:

| Format | Line | Split as |
|---|---|---|
| Go `log` package | `2026/09/02 14:30:00 ERROR ...` | `2026/09/02 14` /
`30` / `00 ERROR ...` |
| nginx error log | `2026/09/02 14:30:00 [error] ...` | same |
| klog (Kubernetes components) | `E0902 14:30:00.000000 1
reflector.go:100] ...` | `E0902 14` / `30` / `00.000000 ...` |
| common/combined access log | `10.0.0.7 - - [02/Sep/2026:14:30:00
+0000] ...` | `10.0.0.7 - - [02/Sep/2026` / `14` / `30:00 ...` |

They reach the fold two ways: the bash-search fold (`grep ERROR
api.log`) and the router's lossless-first stage, which tries the search
fold on any tool output (`cat`, `tail`, `kubectl logs`).

This adds those three prefix shapes to `_TIMESTAMP_ROW_RE`, the same
place #3419 put the guard. The content detector (#3748) and the
mixed-content splitter (#4463) share the regex; neither claimed these
lines before, so for them only false positives could change, and there
are none on real grep output (below).

The access-log alternative differs from the one I suggested in #4900.
That one (`\S+ \S+ \S+ \[...`) also matched a real `grep -n` row over an
access log (`/var/log/nginx/access.log:12:10.0.0.7 - - [02/Sep/...`),
because `\S+` swallows `path:12:10.0.0.7`. The fields now exclude `:`,
which a mis-split line cannot contain before its first colon anyway. The
host field takes name/IPv4 characters only (`[\w.-]`), capped at 255 (a
DNS name is at most 253). With `[^\s:]` the check scanned every grep
row's whole path, and fold + detection on 10k grep rows took 10% and 32%
longer than main in two interleaved runs; with this class and cap it
stops early on a path and on a long unbroken line such as a base64 blob.

Closes #4900

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/transforms/lossless_compaction.py`: three alternatives in
`_TIMESTAMP_ROW_RE`: `YYYY/MM/DD hh:mm` (Go log, nginx error log),
`[IWEF]MMDD hh:mm` (klog/glog), and the access-log prefix `host ident
user [dd/Mon/yyyy:hh:mm` with a `[\w.-]{1,255}` host.
- `tests/test_lossless_timestamp_guard.py`: the four formats, plus an
access log with a 253-character host, join
`test_timestamped_logs_are_never_folded`. New
`test_grep_rows_over_those_logs_still_fold`: real `grep -n` rows over
the same logs (including a dated `2026/09/02/api.log` path) still fold
under their file header.
- `tests/test_bash_search_lossless_fold.py`:
`test_go_log_keeps_its_timestamps` runs a Go log through `ContentRouter`
as the output of `grep ERROR /var/log/api.log` (bash-search fold) and of
`cat /var/log/api.log` (lossless-first stage).

## Testing

- [ ] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
# this branch's tests against main's lossless_compaction.py (main 66e00869):
$ pytest -q -rf tests/test_lossless_timestamp_guard.py "tests/test_bash_search_lossless_fold.py::test_go_log_keeps_its_timestamps"
FAILED tests/test_lossless_timestamp_guard.py::test_timestamped_logs_are_never_folded[go-log]
FAILED tests/test_lossless_timestamp_guard.py::test_timestamped_logs_are_never_folded[nginx-error]
FAILED tests/test_lossless_timestamp_guard.py::test_timestamped_logs_are_never_folded[klog]
FAILED tests/test_lossless_timestamp_guard.py::test_timestamped_logs_are_never_folded[access-log]
FAILED tests/test_lossless_timestamp_guard.py::test_timestamped_logs_are_never_folded[access-log-longest-host]
FAILED tests/test_bash_search_lossless_fold.py::test_go_log_keeps_its_timestamps[grep ERROR /var/log/api.log]
FAILED tests/test_bash_search_lossless_fold.py::test_go_log_keeps_its_timestamps[cat /var/log/api.log]
======================== 7 failed, 12 passed in 19.98s ========================
# same command on this branch:
============================= 19 passed in 20.52s =============================

# mutations of the fix, each run against the same tests:
== M1 drop Go/nginx alt: ======================== 4 failed, 15 passed in 21.51s ========================
== M2 drop klog alt: ======================== 1 failed, 18 passed in 15.91s ========================
== M3 drop access-log alt: ======================== 2 failed, 17 passed in 13.28s ========================
== M4 access-log alt as proposed in issue (\S+): ======================== 1 failed, 18 passed in 14.13s ========================
    FAILED tests/test_lossless_timestamp_guard.py::test_grep_rows_over_those_logs_still_fold[access-log]
== M5 host cap too small {1,15}: ======================== 1 failed, 18 passed in 13.45s ========================
== M6 host cap removed: ============================= 19 passed in 12.49s =============================
== M7 host class widened to [^\s:]: ============================= 19 passed in 12.55s =============================

# false positives, the measure used on #3419: every line of every tracked text file in
# this repo as a real grep row (git grep -n -I -e ''), old guard vs this branch:
lines=977737 grep_rows=977737 rejected_by_old_guard=0 rejected_by_new_guard=0 newly_rejected=0

# cost (M6/M7 survive because the cap and class only bound the scan):
main   fold+detect+split, 10k real grep rows: median 37.4 ms (min 34.7)
final  fold+detect+split, 10k real grep rows: median 38.7 ms (min 37.1)
1MB word-char line main   0.000 ms per match
1MB word-char line final  0.001 ms per match
1MB base64 line    main   0.000 ms per match
1MB base64 line    final  0.000 ms per match
# an earlier run with the host as unbounded [^\s:]+ (not used):
1MB word-char line   unbounded        5.571 ms per match
1MB base64 line      unbounded        6.566 ms per match

# full suite on this machine: pytest tests scripts/tests -n 8 --continue-on-collection-errors
# main 5023c84e:
= 459 failed, 18027 passed, 1154 skipped, 42 warnings, 417 errors in 9256.57s (2:34:16) =
# this branch on 66e00869:
= 454 failed, 18085 passed, 1154 skipped, 39 warnings, 417 errors in 2921.98s (0:48:41) =
# 8 failures appear only in the branch run. Each rerun 3x serially on main 66e00869 and on the branch:
[wtmain] ppp  tests/test_fastembed_pinned_snapshot.py::test_token_fixture_matches_huggingface_hub[HF_TOKEN wins over the login file]
[wtmain] ppp  tests/test_image_compression_isolation.py::test_one_timeout_does_not_destroy_a_concurrent_request
[wtmain] ppp  tests/test_offline_egress_chokepoint.py::TestLiteLLMCostMapOffline::test_import_with_offline_set_after_package_load_opens_no_socket[headroom.backends.litellm]
[wtmain] ppp  tests/test_openai_chat_buffered_ccr.py::test_a_200_with_no_usable_choice_is_not_replayed_as_an_empty_stream[payload7]
[wtmain] ppp  tests/test_openai_chat_buffered_ccr.py::test_failed_continuation_fails_closed_with_its_status[429-rate_limit_error]
[wtmain] ppp  tests/test_read_maturation_handler_nobust.py::test_quiesce_turns_config_is_honored
[wtmain] FFF  tests/test_stage_timer.py::test_concurrent_measure_calls_are_independent
[wtmain] ppp  tests/test_stateless_no_disk.py::test_cli_stateless_flag_exports_env_for_children
[wt4900] ppp  tests/test_fastembed_pinned_snapshot.py::test_token_fixture_matches_huggingface_hub[HF_TOKEN wins over the login file]
[wt4900] ppp  tests/test_image_compression_isolation.py::test_one_timeout_does_not_destroy_a_concurrent_request
[wt4900] ppp  tests/test_offline_egress_chokepoint.py::TestLiteLLMCostMapOffline::test_import_with_offline_set_after_package_load_opens_no_socket[headroom.backends.litellm]
[wt4900] ppp  tests/test_openai_chat_buffered_ccr.py::test_a_200_with_no_usable_choice_is_not_replayed_as_an_empty_stream[payload7]
[wt4900] ppp  tests/test_openai_chat_buffered_ccr.py::test_failed_continuation_fails_closed_with_its_status[429-rate_limit_error]
[wt4900] ppp  tests/test_read_maturation_handler_nobust.py::test_quiesce_turns_config_is_honored
[wt4900] FFF  tests/test_stage_timer.py::test_concurrent_measure_calls_are_independent
[wt4900] ppp  tests/test_stateless_no_disk.py::test_cli_stateless_flag_exports_env_for_children

$ ruff check .   (0.17.4)
All checks passed!
$ ruff format --check .   (0.17.4)
1954 files already formatted
$ mypy headroom/transforms/lossless_compaction.py headroom/transforms/content_detector.py headroom/transforms/mixed_content.py --ignore-missing-imports --platform linux --follow-imports=silent   (1.20.2)
Success: no issues found in 3 source files
```

`mypy headroom` is unchecked because it is not clean on this machine for
main either. With mypy 1.20.2 from the pre-commit hook and `--platform
linux`, main and this branch both report the same single error,
`upstream_guard.py:162` (`no-any-return`), which comes from that
environment having no `httpx` installed. Without `--platform linux`,
both also report the Windows-only `os` attribute errors from #4520.

## Real Behavior Proof

- Environment: Windows 11, Python 3.11.9, this repo at 5023c84e (main)
and this branch on the same base via `PYTHONPATH=.` (the branch was then
rebased onto 66e00869, whose three new commits touch only OpenCode
files), Rust core taken from the released headroom-ai 0.44.0 wheel (main
is 0.44.0), `HEADROOM_OFFLINE=1`, pure-Python content detection (the
default on Windows).
- Exact command / steps: the reproduction script from #4900
(`compact_lossless(text, "search")` on 30 lines of each format), then an
Anthropic `Bash` `tool_use` plus a 40-line `tool_result` through
`ContentRouter(ContentRouterConfig()).apply(...)` for `kubectl logs ...`
(klog), `tail -n 200 /var/log/nginx/access.log`, `cat /var/log/api.log`
and `grep ERROR /var/log/api.log` (Go log).
- Observed result: on main each format folds into a fake header
(`2026/09/02 14`, `E0902 14`, `10.0.0.7 - - [02/Sep/2026`) and each
router case applies `lossless_search`; on this branch every case comes
back byte-identical with its timestamps, and the router reports
`router:noop`.
- Not tested: a live proxy session with a real client and model
(in-process `ContentRouter` only); Linux and macOS (the change is a
pure-Python regex; CI covers ubuntu); the Rust core has no copy of this
fold, so there is nothing to port.

```text
main (5023c84e):
--- go log: 1489 -> 1083 chars
2026/09/02 14
30:00 ERROR upstream timeout req=0
--- klog: 2359 -> 2098 chars
E0902 14
30:00.000000       1 reflector.go:0] failed to list *v1.Pod: timeout
--- access log: 2359 -> 1605 chars
10.0.0.7 - - [02/Sep/2026
14:30:00 +0000] "GET /api/items/0 HTTP/1.1" 500 512
klog     N=40 5399->5048 fake_header=True first='E0902 14'
          transforms: ['router:tool_result:lossless_search']
access   N=40 3829->2815 fake_header=True first='10.0.0.7 - - [02/Sep/2026'
          transforms: ['router:tool_result:lossless_search']
go       N=40 3079->2533 fake_header=True first='2026/09/02 14'
          transforms: ['router:tool_result:lossless_search']
go-grep  N=40 3079->2533 fake_header=True first='2026/09/02 14'
          transforms: ['router:bash:lossless_search']

this branch:
--- go log: 1489 -> 1489 chars
2026/09/02 14:30:00 ERROR upstream timeout req=0
--- klog: 2359 -> 2359 chars
E0902 14:30:00.000000       1 reflector.go:0] failed to list *v1.Pod: timeout
--- access log: 2359 -> 2359 chars
10.0.0.7 - - [02/Sep/2026:14:30:00 +0000] "GET /api/items/0 HTTP/1.1" 500 512
klog     N=40 5399->5399 fake_header=False first='E0902 14:30:00.000000       1 reflector.go:100] failed to li'
          transforms: ['router:noop']
access   N=40 3829->3829 fake_header=False first='10.0.0.7 - - [02/Sep/2026:14:30:00 +0000] "GET /api/items/0 '
          transforms: ['router:noop']
go       N=40 3079->3079 fake_header=False first='2026/09/02 14:30:00 ERROR handler: upstream timeout after 90'
          transforms: ['router:noop']
go-grep  N=40 3079->3079 fake_header=False first='2026/09/02 14:30:00 ERROR handler: upstream timeout after 90'
          transforms: ['router:noop']
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A (no feature flag involved).
- Stable/default behavior changed: Yes, narrowly. Lines that start with
a Go/nginx, klog or access-log timestamp no longer take the grep fold;
real grep output folds as before (0 of 977,737 real grep rows newly
rejected).
- Kill switch / disable path: `HEADROOM_LOSSLESS_COMPACTION=0` disables
every lossless fold, as before.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this PR.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

- Documentation: N/A, the guard is internal and no docs describe its
formats.
- `Unit tests pass` and `New and existing unit tests pass locally` are
unchecked because the full suite is not clean on this Windows machine
for main either. Across the 28 test files that reference the fold, the
guard, the detector or the mixed-content splitter, the branch run fails
the same 8 tests as main (7 in `test_image_compressor.py`, 1 in
`test_garbled_compression_fixes.py`) and nothing else; the full-suite
comparison is in Test Output.
- Ruby's default `Logger` format (`E, [2026-09-02T14:30:00.123456 #4321]
ERROR -- : ...`) folds the same way (`I, [2026-09-02T14` header). It is
not in #4900, so I left it out; it is one more alternative if you want
it here.
- Logs with ANSI color codes before the timestamp still fold under the
`search` kind, for every format including ISO. That predates this
change.
- An access log whose client is an IPv6 address with an all-digit second
group (`2001:4860:4860::8888 - - [...]`) splits on the address itself,
not the timestamp, and folds under a `2001` header on main and on this
branch. Left for a separate change.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4901"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Ayush Kumar Jha
2026-11-16 23:20:01 -06:00
committed by GitHub
co-authored by JD Davis
parent 0d203db6b8
commit cf3284675e
3 changed files with 75 additions and 1 deletions
@@ -75,8 +75,16 @@ _HEADING_ROW_RE = re.compile(r"^(?P<line>\d+):(?P<content>.*)$")
_TIMESTAMP_ROW_RE = re.compile(
r"^\s*\[?(?:"
r"\d{4}-\d{2}-\d{2}[ T]\d{1,2}:\d{2}" # 2026-09-02 14:30 / ISO 8601 'T'
r"|\d{4}/\d{2}/\d{2}[ T]\d{1,2}:\d{2}" # Go log, nginx error log: 2026/09/02 14:30
r"|\d{2}/\d{2}/\d{2,4}[ T]\d{1,2}:\d{2}" # 09/02/2026 14:30
r"|[A-Z][a-z]{2}\s+\d{1,2}\s+\d{1,2}:\d{2}" # syslog: Aug 16 11:02
r"|[IWEF]\d{4}\s+\d{1,2}:\d{2}" # klog/glog: E0902 14:30
# Common/combined access log: 10.0.0.7 - - [02/Sep/2026:14:30:00. The
# fields hold no ':', so a `grep -n` row (`path:12:10.0.0.7 - - [...`) is
# not claimed. The host takes name/IPv4 characters only, capped at 255
# (DNS names are at most 253), so a grep row's path or a long unbroken
# line is not scanned to its end.
r"|[\w.-]{1,255} [^\s:]+ [^\s:]+ \[\d{2}/[A-Z][a-z]{2}/\d{4}:\d{2}:\d{2}"
r"|\d{1,2}:\d{2}:\d{2}(?:[.,]\d+)?(?:\s|\]|$)" # bare 15:03:53 / [15:03:53]
r")"
)
+18
View File
@@ -151,6 +151,24 @@ def test_source_output_from_search_command_untouched(tokenizer):
assert out == CODE
GO_LOG = "".join(
f"2026/09/02 14:{30 + i // 60:02d}:{i % 60:02d} ERROR handler: upstream timeout req={i}\n"
for i in range(40)
)
@pytest.mark.parametrize("command", ["grep ERROR /var/log/api.log", "cat /var/log/api.log"])
def test_go_log_keeps_its_timestamps(command, tokenizer):
# Split as path:line:content, `2026/09/02 14:30:00 ...` would fold into a
# `2026/09/02 14` header over `30:00 ...` rows. `cat` reaches the search
# fold through the router's lossless-first stage, `grep` through the
# bash-search fold.
out, transforms = _anthropic(command, GO_LOG, tokenizer)
assert "router:bash:lossless_search" not in transforms
assert "router:tool_result:lossless_search" not in transforms
assert "2026/09/02 14" not in out.split("\n")
# ---- path-listing fold (find/ls -1/rg -l): fold repeated parent dirs ----
from headroom.transforms.lossless_compaction import (
compact_lossless as _cl,
+49 -1
View File
@@ -24,6 +24,9 @@ def _multi_hour_log() -> str:
return "\n".join(lines)
_LONGEST_HOST = ".".join(["h" * 63] * 3 + ["h" * 61]) # 253 chars, the DNS maximum
@pytest.mark.parametrize(
"sample",
[
@@ -34,13 +37,58 @@ def _multi_hour_log() -> str:
),
"\n".join(f"[15:{m:02d}:53] tool: Bash(cmd {m})" for m in range(60)),
"\n".join(f"2026-09-02T14:{m:02d}:10 [WARN] latency high {m}" for m in range(60)),
"\n".join(f"2026/09/02 14:{m:02d}:10 ERROR upstream timeout req={m}" for m in range(60)),
"\n".join(
f"2026/09/02 14:{m:02d}:10 [error] 31#31: *{m} connect() failed (111: refused)"
for m in range(60)
),
"\n".join(
f"E0902 14:{m:02d}:10.000000 1 reflector.go:{m}] failed to list *v1.Pod"
for m in range(60)
),
"\n".join(
f'10.0.0.7 - - [02/Sep/2026:14:{m:02d}:10 +0000] "GET /items/{m} HTTP/1.1" 500 512'
for m in range(60)
),
"\n".join(
f'{_LONGEST_HOST} - - [02/Sep/2026:14:{m:02d}:10 +0000] "GET /" 200 5'
for m in range(60)
),
],
ids=[
"iso-datetime",
"syslog",
"bracketed-time",
"iso-T",
"go-log",
"nginx-error",
"klog",
"access-log",
"access-log-longest-host",
],
ids=["iso-datetime", "syslog", "bracketed-time", "iso-T"],
)
def test_timestamped_logs_are_never_folded(sample: str) -> None:
assert compact_lossless(sample, "search") == sample
@pytest.mark.parametrize(
("path", "row"),
[
("2026/09/02/api.log", "2026/09/02 14:30:{s:02d} ERROR upstream timeout"),
("logs/nginx/error.log", "2026/09/02 14:30:{s:02d} [error] 31#31: connect() failed"),
("logs/controller.log", "E0902 14:30:{s:02d}.000000 1 reflector.go:100] list failed"),
("/var/log/nginx/access.log", '10.0.0.7 - - [02/Sep/2026:14:30:{s:02d} +0000] "GET /" 500'),
],
ids=["go-log", "nginx-error", "klog", "access-log"],
)
def test_grep_rows_over_those_logs_still_fold(path: str, row: str) -> None:
"""``grep -n`` output starts with the file path, so it is not a log row."""
grep = "\n".join(f"{path}:{i}:{row.format(s=i % 60)}" for i in range(1, 41))
out = compact_lossless(grep, "search")
assert len(out) < len(grep)
assert out.split("\n")[0] == path
def test_fatal_line_keeps_its_full_timestamp() -> None:
out = compact_lossless(_multi_hour_log(), "search")
fatal = [line for line in out.split("\n") if "FATAL" in line]