perf(logs): reuse event sequence for unchanged log files

This commit is contained in:
阿白叔 committed 2026-10-15 21:01:39 +08:00
1 parent d0125f8f59
commit 159616ea4a
2 files changed
+56 -1

No files matched your search

@@ -3,6 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
from collections import OrderedDict
from datetime import datetime, timezone
import hashlib
import json
@@ -47,6 +48,7 @@ class LoggingContext:
application_log_path: Path
logger: logging.Logger
_event_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
_event_sequences: OrderedDict = field(default_factory=OrderedDict, repr=False)
def report_exception(
self,
@@ -128,7 +130,11 @@ def append_task_event(
raise TaskCenterError("event_details", "task event details must be JSON-compatible") from error
path = task_directory / "events.jsonl"
with context._event_lock:
sequence = _next_event_sequence(path)
# Reuse only a sequence belonging to this exact, unchanged file. External
# appends, rotation, truncation and replacement fall back to the disk tail.
cached = context._event_sequences.pop(path, None)
stamp = _event_file_stamp(path)
sequence = cached[1] if cached is not None and stamp is not None and cached[0] == stamp else _next_event_sequence(path)
event = {
"sequence": sequence,
"timestamp_utc": _utc_now_text(),
@@ -153,6 +159,14 @@ def append_task_event(
handle.write(encoded)
handle.flush()
os.fsync(handle.fileno())
written = os.fstat(handle.fileno())
final = _event_file_stamp(path)
# Windows fstat/Path.stat differ in ctime semantics; retain the full
# Path stamp only after handle identity, size and mtime agree.
if final is not None and final[:4] == (written.st_dev, written.st_ino, written.st_size, written.st_mtime_ns):
context._event_sequences[path] = (final, sequence + 1)
while len(context._event_sequences) > 64:
context._event_sequences.popitem(last=False)
except OSError as error:
raise TaskCenterError("event_write_failed", "cannot append task event") from error
context.logger.log(
@@ -167,6 +181,14 @@ def append_task_event(
return event
def _event_file_stamp(path):
try:
info = path.stat()
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
except OSError:
return None
def capture_subprocess_output(
context: LoggingContext,
*,
+33
View File
@@ -0,0 +1,33 @@
import json
from dx_productivity.trial_task_center import logging_setup as logs
def test_unchanged_event_log_does_not_reread_tail_each_append(tmp_path, monkeypatch):
context = logs.configure_logging(tmp_path)
reads = []
original = logs._tail_utf8_lines
def read(path, limit):
reads.append(path)
return original(path, limit)
monkeypatch.setattr(logs, '_tail_utf8_lines', read)
for _ in range(4):
logs.append_task_event(context, level='INFO', task_id='a', operation='step')
path = tmp_path / 'tasks/a/events.jsonl'
assert [json.loads(s)['sequence'] for s in path.read_text().splitlines()] == [1, 2, 3, 4]
assert len(reads) <= 1
def test_replaced_or_external_appended_log_invalidates_cached_sequence(tmp_path):
context = logs.configure_logging(tmp_path)
logs.append_task_event(context, level='INFO', task_id='a', operation='step')
path = tmp_path / 'tasks/a/events.jsonl'
with path.open('a') as stream:
stream.write(json.dumps({'sequence': 50}) + '\n')
event = logs.append_task_event(context, level='INFO', task_id='a', operation='step')
assert event['sequence'] == 51
replacement = path.with_suffix('.new')
replacement.write_text(json.dumps({'sequence': 80}) + '\n')
replacement.replace(path)
event = logs.append_task_event(context, level='INFO', task_id='a', operation='step')
assert event['sequence'] == 81