perf(healing): scan heal history from file tail instead of full read
- add tail-based HEAL line lookup to avoid O(file-size) reads in should_heal() - keep a safe fallback full scan when no HEAL marker is found in tail window - add regression test for large history files with recent HEAL marker
This commit is contained in:
1 parent
55cc29071e
commit
9edce6b31d
2 files changed
+55
-5
No files matched your search
+43
-5
@@ -4,6 +4,47 @@ import time
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
def _read_last_heal_line(history_file, chunk_size=4096, max_scan_bytes=262144):
|
||||
"""
|
||||
Returns the most recent line containing 'HEAL:' by scanning from file tail.
|
||||
Falls back to a full forward scan if no marker is found in the tail window.
|
||||
"""
|
||||
file_size = os.path.getsize(history_file)
|
||||
if file_size <= 0:
|
||||
return None
|
||||
|
||||
with open(history_file, "rb") as f:
|
||||
pos = file_size
|
||||
scanned = 0
|
||||
buffer = b""
|
||||
|
||||
while pos > 0 and scanned < max_scan_bytes:
|
||||
to_read = min(chunk_size, pos, max_scan_bytes - scanned)
|
||||
pos -= to_read
|
||||
f.seek(pos)
|
||||
chunk = f.read(to_read)
|
||||
buffer = chunk + buffer
|
||||
scanned += to_read
|
||||
|
||||
lines = buffer.splitlines()
|
||||
if pos > 0 and lines:
|
||||
# Drop potential partial line at the chunk boundary.
|
||||
lines = lines[1:]
|
||||
|
||||
for raw_line in reversed(lines):
|
||||
line = raw_line.decode("utf-8", errors="replace").strip()
|
||||
if "HEAL:" in line:
|
||||
return line
|
||||
|
||||
# Fallback for unusual files where recent tail has no HEAL marker.
|
||||
last_heal_line = None
|
||||
with open(history_file) as f:
|
||||
for line in f:
|
||||
if "HEAL:" in line:
|
||||
last_heal_line = line.strip()
|
||||
return last_heal_line
|
||||
|
||||
|
||||
def should_heal(history_file, drift_fingerprint, min_interval=900):
|
||||
"""
|
||||
Prevents heal flapping by suppressing repeated no-op heals.
|
||||
@@ -12,13 +53,10 @@ def should_heal(history_file, drift_fingerprint, min_interval=900):
|
||||
if not os.path.exists(history_file):
|
||||
return True
|
||||
|
||||
with open(history_file) as f:
|
||||
lines = [l.strip() for l in f.readlines() if "HEAL:" in l]
|
||||
|
||||
if not lines:
|
||||
last = _read_last_heal_line(history_file)
|
||||
if not last:
|
||||
return True
|
||||
|
||||
last = lines[-1]
|
||||
ts_str, msg = last.split(" - ", 1)
|
||||
last_time = datetime.fromisoformat(ts_str)
|
||||
last_fingerprint = ""
|
||||
|
||||
Reference in new issue
Block a user