From 159616ea4a5d37b66084a38fa22684f783d850a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Thu, 15 Oct 2026 21:01:39 +0800 Subject: [PATCH] perf(logs): reuse event sequence for unchanged log files --- .../trial_task_center/logging_setup.py | 24 +++++++++++++- tests/v1_1/test_event_append_cache.py | 33 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 tests/v1_1/test_event_append_cache.py diff --git a/src/dx_productivity/trial_task_center/logging_setup.py b/src/dx_productivity/trial_task_center/logging_setup.py index 86d2bf0..dc3c732 100644 --- a/src/dx_productivity/trial_task_center/logging_setup.py +++ b/src/dx_productivity/trial_task_center/logging_setup.py @@ -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, *, diff --git a/tests/v1_1/test_event_append_cache.py b/tests/v1_1/test_event_append_cache.py new file mode 100644 index 0000000..8e32f1a --- /dev/null +++ b/tests/v1_1/test_event_append_cache.py @@ -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