mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(lossless): never grep-fold Ruby Logger timestamps (#4907)
## Description Follow-up to #4901, same class as #4900. Ruby's default `Logger::Formatter` writes ```text I, [2026-09-02T14:30:00.123456 #4321] INFO -- : message ``` (`Format = "%.1s, [%s #%d] %5s -- %s: %s\n"` and `DatetimeFormat = "%Y-%m-%dT%H:%M:%S.%6N"`, read from the logger gem 1.6.0 in Ruby 3.3.13). The search fold splits that line as `path:line:content` at its first colon, so `I, [2026-09-02T14` becomes a header and every row starts mid-clock (`30:00.123456 #4321] INFO -- : ...`). `_TIMESTAMP_ROW_RE` accepts a bare or bracketed ISO timestamp, but not one behind Ruby's `I, [` prefix, so these logs still fold, both from `grep` and from a plain `tail` through the lossless-first stage. This adds that prefix shape for the six letters Ruby prints: D, I, W, E, F, and A (`UNKNOWN` prints as `ANY`), followed by Ruby's default `T`-separated date. Custom `datetime_format` values are not covered. Refs #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`: one alternative in `_TIMESTAMP_ROW_RE`, `[DIWEFA], \[YYYY-MM-DDThh:mm`. - `tests/test_lossless_timestamp_guard.py`: a Ruby log with a 10-line block per severity joins `test_timestamped_logs_are_never_folded` (each block would fold on its own if its letter were missing from the guard), and `test_grep_rows_over_those_logs_still_fold` gains real `grep -n` rows over `log/production.log`, which still fold under the file header. ## 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 guard (acebf20b): $ pytest -q -rf tests/test_lossless_timestamp_guard.py FAILED tests/test_lossless_timestamp_guard.py::test_timestamped_logs_are_never_folded[ruby-logger] ======================== 1 failed, 18 passed in 1.62s ========================= # same command on this branch: ============================= 19 passed in 2.32s ============================== # mutations of the fix, each run against the same file: == R1 drop the Ruby alternative: ======================== 1 failed, 18 passed in 2.71s ========================= == R2 severities narrowed to [IWEF] (klog's set): ======================== 1 failed, 18 passed in 1.38s ========================= == R3 severities narrowed to [DIWEF] (no ANY): ======================== 1 failed, 18 passed in 1.27s ========================= == R4 bracket dropped from the prefix: ======================== 1 failed, 18 passed in 1.38s ========================= # false positives, as measured for #3419 and #4901: every line of every tracked text file # in this repo as a real grep row (git grep -n -I -e ''), main's guard vs this branch: lines=985907 grep_rows=985907 rejected_by_old_guard=0 rejected_by_new_guard=0 newly_rejected=0 # cost: fold + detector + mixed-content splitter on 10k real grep rows, 11 interleaved runs # ("#4901" is the guard as merged, identical to main's) #4901 fold+detect+split, 10k real grep rows: median 41.3 ms (min 39.4) ruby fold+detect+split, 10k real grep rows: median 42.3 ms (min 40.4) 1MB word-char line #4901 0.001 ms per match 1MB word-char line ruby 0.002 ms per match 1MB base64 line #4901 0.000 ms per match 1MB base64 line ruby 0.000 ms per match # full suite on this machine, this branch onacebf20b: # pytest tests scripts/tests -n 8 --continue-on-collection-errors = 465 failed, 18285 passed, 1147 skipped, 39 warnings, 432 errors in 643.74s (0:10:43) = # 37 failures/errors were not in my earlier full runs of main (5023c84e) and #4901 (66e00869). # Each rerun serially, 2x, on clean mainacebf20band on this branch: same result on both # (all FF in test_proxy_loopback_gating, test_memory_embedding_validation, # test_memory_sync_full_store, test_compaction_codec; the rest pass), except two timing tests, # rerun 5x more each: [wtmain] ppFpF tests/test_savings_ledger_offload.py::test_concurrent_requests_all_land_their_events [wtmain] ppppp tests/test_transforms_tabular.py::test_parse_csv_trims_a_large_blank_prefix_in_linear_time [wtruby] ppFpF tests/test_savings_ledger_offload.py::test_concurrent_requests_all_land_their_events [wtruby] Fpppp tests/test_transforms_tabular.py::test_parse_csv_trims_a_large_blank_prefix_in_linear_time # (the tabular one also failed 1 of the 2 earlier runs on main; parse_csv does not use the guard) $ ruff check . (0.17.4) All checks passed! $ ruff format --check . (0.17.4) 1973 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 ``` `Unit tests pass` and `Type checking passes` are unchecked for the same reason as on #4901: neither the full suite nor `mypy headroom` is clean for main on this Windows machine. The comparison is above. ## Real Behavior Proof - Environment: Windows 11, Python 3.11.9, main atacebf20band this branch on top of it via `PYTHONPATH=.`, Rust core from the released headroom-ai 0.44.0 wheel, `HEADROOM_OFFLINE=1`. The log was written by real Ruby: `docker run ruby:3.3-slim` (Ruby 3.3.13, logger gem 1.6.0), `Logger.new($stdout)` with the default formatter, 60 lines (50 INFO, 5 WARN, 5 ERROR). - Exact command / steps: `compact_lossless(log, "search")`, then an Anthropic `Bash` `tool_use` plus the log as its `tool_result` through `ContentRouter(ContentRouterConfig()).apply(...)` for `tail -n 60 log/production.log` and for `grep ERROR log/production.log` (the five ERROR lines), on main and on this branch. - Observed result: on main the log folds under `I, [2026-11-17T00` and both router cases apply `lossless_search`; on this branch the fold leaves it byte-identical, the 60-line `tail` takes the router's regular log strategy, and the `grep` result passes through verbatim. - Not tested: a live proxy session; Rails or other frameworks that wrap Ruby's Logger; custom `datetime_format` values; Linux and macOS (pure-Python regex, CI covers ubuntu). ```text # docker run --rm -i ruby:3.3-slim ruby, script on stdin: Logger.new($stdout), default formatter RUBY 3.3.13 logger gem 1.6.0 Format="%.1s, [%s #%d] %5s -- %s: %s\n" DatetimeFormat="%Y-%m-%dT%H:%M:%S.%6N" D, [2026-11-17T00:58:58.052713 #1] DEBUG -- : cache miss key=user:42 I, [2026-11-17T00:58:58.052754 #1] INFO -- : Started GET "/api/items/7" for 10.0.0.7 A, [2026-11-17T00:58:58.052772 #1] ANY -- : unclassified event main: --- compact_lossless(ruby log, 'search'): 6571 -> 5851 chars I, [2026-11-17T00 59:22.027565 #1] INFO -- : Completed 200 OK in 10ms (Views: 0ms | ActiveRecord: 0ms) req_id=r0 59:22.027646 #1] INFO -- : Completed 200 OK in 11ms (Views: 1ms | ActiveRecord: 1ms) req_id=r1 --- router, Bash `tail -n 60 log/production.log`: 6571 -> 5851 chars, transforms=['router:tool_result:lossless_search'] --- router, Bash `grep ERROR log/production.log`: 440 -> 368 chars, transforms=['router:bash:lossless_search'] E, [2026-11-17T00 59:22.027678 #1] ERROR -- : upstream timeout after 30000ms req_id=r11 this branch: --- compact_lossless(ruby log, 'search'): 6571 -> 6571 chars I, [2026-11-17T00:59:22.027565 #1] INFO -- : Completed 200 OK in 10ms (Views: 0ms | ActiveRecord: 0ms) req_id=r0 --- router, Bash `tail -n 60 log/production.log`: 6571 -> 4227 chars, transforms=['router:tool_result:log'] --- router, Bash `grep ERROR log/production.log`: 440 -> 440 chars, transforms=['router:shell_small_result_verbatim'] E, [2026-11-17T00:59:22.027678 #1] ERROR -- : upstream timeout after 30000ms req_id=r11 ``` ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A (no feature flag involved). - Stable/default behavior changed: Yes, narrowly. Lines in Ruby's default Logger format no longer take the grep fold; real grep output folds as before (0 of 985,907 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. - What happens after the fold is refused is unchanged by this PR: the 60-line log above takes the router's regular log strategy (all 5 ERROR lines kept, `[22 lines omitted: 4 WARN, 18 INFO]`, no retrieval marker at that 0.64 ratio), the same path the #4901 formats take. The same lines with a plain ISO prefix come back unchanged on main for an unrelated reason: `mixed_content_indicators` sets `has_search_results` from the raw `^\S+:\d+:` pattern, which matches `2026-11-17T00:59:`, so that content routes as mixed. I left both alone. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4907" 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 -->
This commit is contained in:
@@ -79,6 +79,7 @@ _TIMESTAMP_ROW_RE = re.compile(
|
||||
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
|
||||
r"|[DIWEFA], \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}" # Ruby Logger: I, [2026-09-02T14: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
|
||||
|
||||
@@ -24,6 +24,15 @@ def _multi_hour_log() -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _ruby_logger_log() -> str:
|
||||
"""Ruby's default ``Logger::Formatter`` at every severity (UNKNOWN prints as ANY)."""
|
||||
return "\n".join(
|
||||
f"{sev[0]}, [2026-09-02T14:{m:02d}:10.{m:06d} #4321] {sev:>5} -- : request {m} handled"
|
||||
for sev in ("DEBUG", "INFO", "WARN", "ERROR", "FATAL", "ANY")
|
||||
for m in range(10)
|
||||
)
|
||||
|
||||
|
||||
_LONGEST_HOST = ".".join(["h" * 63] * 3 + ["h" * 61]) # 253 chars, the DNS maximum
|
||||
|
||||
|
||||
@@ -54,6 +63,7 @@ _LONGEST_HOST = ".".join(["h" * 63] * 3 + ["h" * 61]) # 253 chars, the DNS maxi
|
||||
f'{_LONGEST_HOST} - - [02/Sep/2026:14:{m:02d}:10 +0000] "GET /" 200 5'
|
||||
for m in range(60)
|
||||
),
|
||||
_ruby_logger_log(),
|
||||
],
|
||||
ids=[
|
||||
"iso-datetime",
|
||||
@@ -65,6 +75,7 @@ _LONGEST_HOST = ".".join(["h" * 63] * 3 + ["h" * 61]) # 253 chars, the DNS maxi
|
||||
"klog",
|
||||
"access-log",
|
||||
"access-log-longest-host",
|
||||
"ruby-logger",
|
||||
],
|
||||
)
|
||||
def test_timestamped_logs_are_never_folded(sample: str) -> None:
|
||||
@@ -78,8 +89,9 @@ def test_timestamped_logs_are_never_folded(sample: str) -> None:
|
||||
("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'),
|
||||
("log/production.log", "I, [2026-09-02T14:30:{s:02d}.000000 #1] INFO -- : 200 OK"),
|
||||
],
|
||||
ids=["go-log", "nginx-error", "klog", "access-log"],
|
||||
ids=["go-log", "nginx-error", "klog", "access-log", "ruby-logger"],
|
||||
)
|
||||
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."""
|
||||
|
||||
Reference in New Issue
Block a user