fix(logging): a closed profile router never reopens a per-home log
Dropping the router's handler lock from handle() fixed T23's lock order, but nothing ordered close()/release_profile() against a record in flight any more. logging.shutdown (uvicorn's dictConfig) could close the router and a per-home handler between the record's pick and its write, and the append-mode RotatingFileHandler reopened the file on emit (on Windows its lock then held the profile's logs/ until exit). A record that built a new home's handler could also setdefault it into the closed router, leaking its fd. The router now records close() under _profile_handlers_lock and never publishes into a closed router or a released home (the built handler is closed instead). Its per-home handlers drop a record once closed; the check runs under the handler's own lock, which close() also takes. Putting the outer router lock back would bring T23 back, so this adds no lock. Review finding by @dokterdok on #140967 Review finding by @kshitijk4poor on #140967 Refs #134889 (T23) Refs #140719
This commit is contained in:
@@ -476,6 +476,9 @@ class _ManagedRotatingFileHandler(RotatingFileHandler):
|
||||
# so skip the write (the router re-routes the record) instead of a FileNotFoundError traceback.
|
||||
self._skip_write_when_dir_missing = False
|
||||
self.skipped_missing_dir = False
|
||||
# Set by _ProfileRoutingFileHandler: once closed (router close, logging.shutdown, a released
|
||||
# profile) never reopen. The stdlib reopens an append-mode file on emit after close.
|
||||
self._never_reopen_after_close = False
|
||||
super().__init__(*args, **kwargs)
|
||||
self._record_stream_stat()
|
||||
|
||||
@@ -530,6 +533,11 @@ class _ManagedRotatingFileHandler(RotatingFileHandler):
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
self.skipped_missing_dir = False
|
||||
# Under this handler's own lock (Handler.handle), which close() also takes: a record that
|
||||
# picked this handler before its router retired it is dropped, never written to a reopened
|
||||
# file (on Windows that reopened file keeps the profile's logs/ locked until exit).
|
||||
if self._never_reopen_after_close and getattr(self, "_closed", False):
|
||||
return
|
||||
had_stream = self.stream is not None
|
||||
# The kernel caches inode metadata, so this stat is sub-microsecond on a hot file.
|
||||
file_exists = had_stream or os.path.exists(self.baseFilename)
|
||||
@@ -649,6 +657,7 @@ class _ProfileRoutingFileHandler(logging.Handler):
|
||||
self._backup_count = getattr(existing, "backupCount", 0)
|
||||
self._profile_handlers: dict[Path, _ManagedRotatingFileHandler] = {}
|
||||
self._profile_handlers_lock = threading.RLock()
|
||||
self._router_closed = False # under _profile_handlers_lock; close() is final
|
||||
# Home -> monotonic time of its last liveness check (see _PROFILE_LIVENESS_RECHECK_S).
|
||||
self._liveness_checked_at: dict[Path, float] = {}
|
||||
self.setFormatter(existing.formatter)
|
||||
@@ -687,7 +696,8 @@ class _ProfileRoutingFileHandler(logging.Handler):
|
||||
self.release_profile(home)
|
||||
return True
|
||||
|
||||
def _handler_for_home(self, home: Path) -> _ManagedRotatingFileHandler:
|
||||
def _handler_for_home(self, home: Path) -> Optional[_ManagedRotatingFileHandler]:
|
||||
"""The open handler for *home*; ``None`` once the router or that home is retired."""
|
||||
with self._profile_handlers_lock:
|
||||
handler = self._profile_handlers.get(home)
|
||||
if handler is not None:
|
||||
@@ -701,9 +711,13 @@ class _ProfileRoutingFileHandler(logging.Handler):
|
||||
backup_count=self._backup_count, formatter=self.formatter,
|
||||
)
|
||||
built._skip_write_when_dir_missing = home != self._default_home
|
||||
built._never_reopen_after_close = True
|
||||
with self._profile_handlers_lock:
|
||||
handler = self._profile_handlers.setdefault(home, built)
|
||||
if handler is not built: # another thread opened it first
|
||||
# Closed (logging.shutdown) or released while this was built: publishing now would leak
|
||||
# the new handler's fd into a router nothing will close again.
|
||||
retired = self._router_closed or (home != self._default_home and home not in self._profile_homes)
|
||||
handler = None if retired else self._profile_handlers.setdefault(home, built)
|
||||
if handler is not built: # retired, or another thread opened it first
|
||||
_quietly(built.close)
|
||||
return handler
|
||||
|
||||
@@ -723,6 +737,10 @@ class _ProfileRoutingFileHandler(logging.Handler):
|
||||
try:
|
||||
home = self._home_for_record(record)
|
||||
handler = self._handler_for_home(home)
|
||||
if handler is None and home != self._default_home: # released in flight
|
||||
home, handler = self._default_home, self._handler_for_home(self._default_home)
|
||||
if handler is None: # the router is closed
|
||||
return
|
||||
if home == self._default_home:
|
||||
handler.handle(record)
|
||||
return
|
||||
@@ -739,12 +757,14 @@ class _ProfileRoutingFileHandler(logging.Handler):
|
||||
# default log either way (a live profile whose logs/ was removed by hand included).
|
||||
if handler.skipped_missing_dir:
|
||||
self._release_if_deleted(home)
|
||||
self._handler_for_home(self._default_home).handle(record)
|
||||
if (fallback := self._handler_for_home(self._default_home)) is not None:
|
||||
fallback.handle(record)
|
||||
except Exception:
|
||||
self.handleError(record)
|
||||
|
||||
def close(self) -> None:
|
||||
with self._profile_handlers_lock:
|
||||
self._router_closed = True
|
||||
handlers = list(self._profile_handlers.values())
|
||||
self._profile_handlers.clear()
|
||||
for handler in handlers:
|
||||
|
||||
@@ -1072,3 +1072,51 @@ def test_profile_router_never_holds_its_lock_while_taking_the_logging_module_loc
|
||||
assert "routed" in (profile / "logs" / "agent.log").read_text(encoding="utf-8")
|
||||
finally:
|
||||
router.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("closed_at", ["after_pick", "before_publish"])
|
||||
def test_profile_router_close_is_never_undone_by_a_record_in_flight(hermes_home, monkeypatch, closed_at):
|
||||
"""T23 follow-up: with no router lock across ``emit``, ``logging.shutdown`` (uvicorn's
|
||||
``dictConfig``) can close the router and its per-home handler while a routed record is in
|
||||
flight. ``after_pick``: the record picked the per-home handler, then it was closed; a
|
||||
``RotatingFileHandler`` in append mode reopens on emit, so the closed file came back (on
|
||||
Windows its lock then stays held and the profile's logs/ cannot be removed). ``before_publish``:
|
||||
the record built a new home's handler, and its ``setdefault`` landed in the closed router (a
|
||||
leaked fd). Real handlers; only the interleaving is forced."""
|
||||
profile = hermes_home / "profiles" / "t23b"
|
||||
(profile / "logs").mkdir(parents=True)
|
||||
hermes_home.joinpath("logs").mkdir(exist_ok=True)
|
||||
existing = RotatingFileHandler(str(hermes_home / "logs" / "agent.log"), encoding="utf-8")
|
||||
router = hermes_logging._ProfileRoutingFileHandler(existing, [profile])
|
||||
existing.close()
|
||||
profile_log = profile / "logs" / "agent.log"
|
||||
built = []
|
||||
if closed_at == "after_pick":
|
||||
router._handler_for_home(profile) # the home's handler is open before the record arrives
|
||||
real_pick = router._handler_for_home
|
||||
|
||||
def pick_then_shutdown(home):
|
||||
handler = real_pick(home)
|
||||
router.close() # logging.shutdown runs between the pick and the write
|
||||
profile_log.unlink()
|
||||
return handler
|
||||
|
||||
monkeypatch.setattr(router, "_handler_for_home", pick_then_shutdown)
|
||||
else:
|
||||
real_new = hermes_logging._new_file_handler
|
||||
|
||||
def build_then_shutdown(*args, **kwargs):
|
||||
handler = real_new(*args, **kwargs)
|
||||
built.append(handler)
|
||||
if len(built) == 1: # the routed home's build; a later default-home build is not raced
|
||||
router.close() # logging.shutdown runs between the build and the publish
|
||||
profile_log.unlink()
|
||||
return handler
|
||||
|
||||
monkeypatch.setattr(hermes_logging, "_new_file_handler", build_then_shutdown)
|
||||
record = logging.LogRecord("t23", logging.ERROR, __file__, 1, "in flight", None, None)
|
||||
record.hermes_home = str(profile)
|
||||
router.handle(record)
|
||||
assert not profile_log.exists(), "a closed per-home log file was reopened"
|
||||
assert router._profile_handlers == {}
|
||||
assert all(handler.stream is None for handler in built), "a handler built after close leaked its fd"
|
||||
|
||||
Reference in New Issue
Block a user