From 2b8729a4594b9ca109ae7e9216e897acb270b0a5 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Fri, 4 Dec 2026 00:43:22 -0700 Subject: [PATCH 1/2] Keep PDF CPU work off the worker event loop Page-screen tiling and PNG encoding ran on the gevent hub and stalled every greenlet for 40-50 s on an 804-page PDF, starving lease renewal and the heartbeat. Tiling now runs in the PyMuPDF child process. - Skip the table search and drawing clustering in the asset probe once a page already has an asset; only has_asset reads that geometry. - Run PyMuPDF children at nice +10 so the event loop is scheduled first when the task's two CPUs are saturated. - Log event-loop stalls over 2 s with the blocking stack, keep the worst gevent delay between rate-limited pressure warnings, and report child CPU time. All observations are WARNING logs; no alerts. Co-Authored-By: Claude Opus 5.5 --- apps/worker/app/core/event_loop_monitor.py | 115 +++++++++++++ apps/worker/app/core/worker_bootstrap.py | 10 ++ .../page_screen/contact_sheet.py | 151 ++++++++++++------ .../tools/probe_page_features.py | 23 +-- .../formats/pdf/pymupdf_subprocess.py | 48 +++++- .../test_event_loop_monitor_contract.py | 42 +++++ .../contract/test_page_screen_contract.py | 17 ++ .../test_parse_runtime_observation.py | 26 +++ .../contract/test_worker_health_contract.py | 37 +++++ .../unit/test_probe_dense_visual_assets.py | 43 ++++- .../unit/test_pymupdf_subprocess_queue.py | 20 ++- .../shared/services/worker_health.py | 17 +- 12 files changed, 476 insertions(+), 73 deletions(-) create mode 100644 apps/worker/app/core/event_loop_monitor.py create mode 100644 apps/worker/tests/contract/test_event_loop_monitor_contract.py diff --git a/apps/worker/app/core/event_loop_monitor.py b/apps/worker/app/core/event_loop_monitor.py new file mode 100644 index 000000000..95abfcbda --- /dev/null +++ b/apps/worker/app/core/event_loop_monitor.py @@ -0,0 +1,115 @@ +"""Log gevent loop stalls in the worker process together with the blocking stack. + +A stall on the hub thread stops every greenlet in the process: parse lease +renewal, heartbeats and all concurrent tasks. The heartbeat already measures +how late the loop is; this module also records *what* blocked it. + +gevent's monitor thread checks the main hub every ``max_blocking_time`` +seconds and emits ``EventLoopBlocked`` on each check that saw no greenlet +switch, so one long stall emits many events, and the event's +``blocking_time`` is the threshold rather than the stall's length. The +monitor thread therefore only keeps the stack from the first event of a +stall. A reporter greenlet on the hub measures how late it woke, the stall's +real length, and logs one warning with that stack. Logging stays on the hub +thread: the monitor thread never touches the process's gevent-patched locks. +""" + +from __future__ import annotations + +import os +import sys +import time +import traceback +from dataclasses import dataclass +from typing import ClassVar + +import gevent +from gevent.events import EventLoopBlocked, subscribers +from gevent.hub import Hub +from loguru import logger + +# The monitor thread checks the hub this often (seconds). +_DETECTION_INTERVAL_SECONDS = 1.0 +# Stalls shorter than this are not logged; it matches the heartbeat's +# runtime-pressure threshold. +_REPORT_THRESHOLD_SECONDS = 2.0 +# How often the reporter greenlet wakes to measure its own delay. +_REPORTER_INTERVAL_SECONDS = 1.0 +# Innermost frames kept from the blocked stack. +_STACK_FRAMES = 30 + + +@dataclass(frozen=True) +class _BlockedStack: + greenlet: str + stack: str + + +class EventLoopMonitor: + """Install once per worker process, from the hub thread, after monkey patching.""" + + _hub: ClassVar[Hub | None] = None + _captured: ClassVar[_BlockedStack | None] = None + _reporter: ClassVar[gevent.Greenlet | None] = None + + @classmethod + def install(cls) -> None: + if cls._reporter is not None and not cls._reporter.dead: + return + gevent.config.monitor_thread = True + gevent.config.max_blocking_time = _DETECTION_INTERVAL_SECONDS + # The default report prints every greenlet to stderr on every check. + gevent.config.print_blocking_reports = False + cls._hub = gevent.get_hub() + if cls._record_first_stack not in subscribers: + subscribers.append(cls._record_first_stack) + cls._hub.start_periodic_monitoring_thread() + cls._reporter = gevent.spawn(cls._report_stalls) + logger.info( + "Event loop monitor started: detection={}s report_threshold={}s", + _DETECTION_INTERVAL_SECONDS, + _REPORT_THRESHOLD_SECONDS, + ) + + @classmethod + def stop(cls) -> None: + reporter, cls._reporter = cls._reporter, None + if reporter is not None and not reporter.dead: + reporter.kill(block=True, timeout=1) + + @classmethod + def _record_first_stack(cls, event: object) -> None: + """Runs in gevent's monitor thread: no gevent API, no logging.""" + hub = cls._hub + if not isinstance(event, EventLoopBlocked) or hub is None or event.hub is not hub: + # Thread-pool hubs block natively by design; only the main hub matters. + return + if cls._captured is not None: + return + frame = sys._current_frames().get(hub.thread_ident) + stack = ( + "".join(traceback.format_stack(frame)[-_STACK_FRAMES:]) + if frame is not None + else "unavailable" + ) + cls._captured = _BlockedStack(greenlet=str(event.greenlet), stack=stack) + + @classmethod + def _report_stalls(cls) -> None: + while True: + expected = time.monotonic() + _REPORTER_INTERVAL_SECONDS + gevent.sleep(_REPORTER_INTERVAL_SECONDS) + blocked_seconds = max(0.0, time.monotonic() - expected) + captured, cls._captured = cls._captured, None + if blocked_seconds < _REPORT_THRESHOLD_SECONDS: + continue + logger.bind( + event="worker.event_loop_blocked", + worker_pid=os.getpid(), + blocked_ms=round(blocked_seconds * 1000), + blocking_greenlet=captured.greenlet if captured else None, + blocked_stack=captured.stack if captured else None, + ).warning( + "Worker event loop blocked for {} ms", + round(blocked_seconds * 1000), + ) diff --git a/apps/worker/app/core/worker_bootstrap.py b/apps/worker/app/core/worker_bootstrap.py index 201ac1cc4..410f89937 100644 --- a/apps/worker/app/core/worker_bootstrap.py +++ b/apps/worker/app/core/worker_bootstrap.py @@ -72,6 +72,9 @@ def init_worker(**kwargs: object) -> None: from shared.services.retrieval.lexical.preparation import LexicalPreparation LexicalPreparation.warmCompiler() start_worker_heartbeat() + from app.core.event_loop_monitor import EventLoopMonitor + + EventLoopMonitor.install() # Do not cancel gevent tasks from Celery's reconnect or shutdown lifecycle. # Staging proved that forced greenlet cancellation races with parser child @@ -141,6 +144,13 @@ def shutdown_worker(**kwargs: object) -> None: except Exception as exc: logger.warning(f"Worker OCR runner cleanup failed: {exc}") + try: + from app.core.event_loop_monitor import EventLoopMonitor + + EventLoopMonitor.stop() + except Exception as exc: + logger.warning(f"Event loop monitor cleanup failed: {exc}") + try: stop_worker_heartbeat() logger.info("Worker heartbeat stopped") diff --git a/apps/worker/app/services/document_agent/page_screen/contact_sheet.py b/apps/worker/app/services/document_agent/page_screen/contact_sheet.py index 1b074d877..18a2bc05c 100644 --- a/apps/worker/app/services/document_agent/page_screen/contact_sheet.py +++ b/apps/worker/app/services/document_agent/page_screen/contact_sheet.py @@ -1,17 +1,26 @@ -"""Render pages and tile them into grids, each cell tagged with its page number.""" +"""Render pages and tile them into grids, each cell tagged with its page number. + +Tiling and PNG encoding run in a spawned child, as page rendering does. On a +long document they cost tens of CPU seconds; run on the gevent worker thread, +that time blocks every greenlet in the process, parse lease renewal included. +""" from __future__ import annotations import base64 -import io import math import os +from pathlib import Path from typing import Any from PIL import Image, ImageDraw, ImageFont from app.services.document_agent.page_screen.config import GridLayout from app.services.document_agent.visual import render_pages, visual_output_dir +from app.services.document_parser.formats.pdf.pymupdf_subprocess import ( + run_in_child_process, + worker, +) # Grid drawing. The prompts refer to the red number tag at each cell's top-left. _CELL_GAP_PX = 8 @@ -20,6 +29,12 @@ _TAG_PADDING_PX = (4, 2) _TAG_FILL = "#d00" _CELL_OUTLINE = "#888" +# Child budget: 90 grids of an 804-page PDF took about 31 CPU seconds locally. +_TILE_TIMEOUT_MIN_SECONDS = 120 +_TILE_TIMEOUT_PER_GRID_SECONDS = 2 + +# One grid: the pages it shows, each with its rendered thumbnail source path. +GridCells = list[tuple[int, str]] class ContactSheets: @@ -41,13 +56,28 @@ def __init__(self, ctx: Any, *, folder_name: str) -> None: def grids(self, pages: list[int], layout: GridLayout, *, name: str) -> list[str]: """Tile ``pages`` into as many grids as needed; return base64 PNGs.""" self._render(pages, layout.thumb_width) - images: list[str] = [] - for index, start in enumerate(range(0, len(pages), layout.cells), start=1): - chunk = pages[start : start + layout.cells] - grid = self._tile(chunk, layout) - grid.save(os.path.join(self._out_dir, f"{name}_{index:02d}.png")) - images.append(_png_base64(grid)) - return images + sheets: list[GridCells] = [ + [ + (page, self._paths[(layout.thumb_width, page)]) + for page in pages[start : start + layout.cells] + ] + for start in range(0, len(pages), layout.cells) + ] + if not sheets: + return [] + result = run_in_child_process( + _tile_grids_worker, + sheets, + layout.cols, + layout.thumb_width, + self._out_dir, + name, + timeout=max( + _TILE_TIMEOUT_MIN_SECONDS, + _TILE_TIMEOUT_PER_GRID_SECONDS * len(sheets), + ), + ) + return [_file_base64(path) for path in result["paths"]] def _render(self, pages: list[int], width: int) -> None: missing = [page for page in pages if (width, page) not in self._paths] @@ -64,48 +94,65 @@ def _render(self, pages: list[int], width: int) -> None: ): self._paths[(width, int(item["page"]))] = str(item["png_path"]) - def _thumb(self, page: int, width: int) -> Image.Image: - with Image.open(self._paths[(width, page)]) as image: - rgb = image.convert("RGB") - height = round(rgb.height * width / rgb.width) - return rgb.resize((width, height)) - - def _tile(self, pages: list[int], layout: GridLayout) -> Image.Image: - width = layout.thumb_width - thumbs = [self._thumb(page, width) for page in pages] - cell_height = max(thumb.height for thumb in thumbs) - cols = min(layout.cols, len(pages)) - rows = math.ceil(len(pages) / cols) - grid = Image.new( - "RGB", - ( - cols * (width + _CELL_GAP_PX) + _CELL_GAP_PX, - rows * (cell_height + _CELL_GAP_PX) + _CELL_GAP_PX, - ), - "white", + +@worker +def _tile_grids_worker( + queue, + sheets: list[GridCells], + cols: int, + width: int, + out_dir: str, + name: str, +) -> None: + """Tile and save each grid once; the parent reads the saved PNG bytes.""" + paths: list[str] = [] + for index, cells in enumerate(sheets, start=1): + path = os.path.join(out_dir, f"{name}_{index:02d}.png") + _tile(cells, cols, width).save(path) + paths.append(path) + queue.put({"ok": True, "paths": paths}) + + +def _thumb(path: str, width: int) -> Image.Image: + with Image.open(path) as image: + rgb = image.convert("RGB") + height = round(rgb.height * width / rgb.width) + return rgb.resize((width, height)) + + +def _tile(cells: GridCells, layout_cols: int, width: int) -> Image.Image: + thumbs = [_thumb(path, width) for _page, path in cells] + cell_height = max(thumb.height for thumb in thumbs) + cols = min(layout_cols, len(cells)) + rows = math.ceil(len(cells) / cols) + grid = Image.new( + "RGB", + ( + cols * (width + _CELL_GAP_PX) + _CELL_GAP_PX, + rows * (cell_height + _CELL_GAP_PX) + _CELL_GAP_PX, + ), + "white", + ) + draw = ImageDraw.Draw(grid) + font = ImageFont.load_default( + size=max(_TAG_FONT_MIN_PX, width // _TAG_FONT_WIDTH_DIVISOR) + ) + pad_x, pad_y = _TAG_PADDING_PX + for position, ((page, _path), thumb) in enumerate(zip(cells, thumbs)): + x = _CELL_GAP_PX + (position % cols) * (width + _CELL_GAP_PX) + y = _CELL_GAP_PX + (position // cols) * (cell_height + _CELL_GAP_PX) + grid.paste(thumb, (x, y)) + draw.rectangle( + [x, y, x + width - 1, y + thumb.height - 1], outline=_CELL_OUTLINE ) - draw = ImageDraw.Draw(grid) - font = ImageFont.load_default( - size=max(_TAG_FONT_MIN_PX, width // _TAG_FONT_WIDTH_DIVISOR) + label = str(page) + _left, _top, right, bottom = draw.textbbox((0, 0), label, font=font) + draw.rectangle( + [x, y, x + right + 2 * pad_x, y + bottom + 2 * pad_y], fill=_TAG_FILL ) - pad_x, pad_y = _TAG_PADDING_PX - for position, (page, thumb) in enumerate(zip(pages, thumbs)): - x = _CELL_GAP_PX + (position % cols) * (width + _CELL_GAP_PX) - y = _CELL_GAP_PX + (position // cols) * (cell_height + _CELL_GAP_PX) - grid.paste(thumb, (x, y)) - draw.rectangle( - [x, y, x + width - 1, y + thumb.height - 1], outline=_CELL_OUTLINE - ) - label = str(page) - _left, _top, right, bottom = draw.textbbox((0, 0), label, font=font) - draw.rectangle( - [x, y, x + right + 2 * pad_x, y + bottom + 2 * pad_y], fill=_TAG_FILL - ) - draw.text((x + pad_x, y + pad_y), label, fill="white", font=font) - return grid - - -def _png_base64(image: Image.Image) -> str: - buffer = io.BytesIO() - image.save(buffer, format="PNG") - return base64.b64encode(buffer.getvalue()).decode() + draw.text((x + pad_x, y + pad_y), label, fill="white", font=font) + return grid + + +def _file_base64(path: str) -> str: + return base64.b64encode(Path(path).read_bytes()).decode() diff --git a/apps/worker/app/services/document_agent/tools/probe_page_features.py b/apps/worker/app/services/document_agent/tools/probe_page_features.py index 01f54532f..604c95f41 100644 --- a/apps/worker/app/services/document_agent/tools/probe_page_features.py +++ b/apps/worker/app/services/document_agent/tools/probe_page_features.py @@ -313,8 +313,12 @@ def _probe_visual_assets( image_count=image_count, drawings_count=drawings_count ) + # Only the has_asset gate reads this geometry. Once one asset is found, the + # table search and drawing clustering (most of the probe's CPU) cannot + # change the result, so they are skipped and table_count stays 0, as on + # dense pages. table_count = 0 - if not dense_visual: + if not dense_visual and not bboxes: try: finder = page.find_tables() tables = getattr(finder, "tables", []) or [] @@ -334,15 +338,16 @@ def _probe_visual_assets( bboxes.append({"kind": "table", "bbox": box}) except Exception: table_count = 0 - bboxes.extend( - _figure_bboxes_from_drawings( - drawings, - page_rect=page_rect, - page_area=page_area, - header_y=header_y, - footer_y=footer_y, + if not bboxes: + bboxes.extend( + _figure_bboxes_from_drawings( + drawings, + page_rect=page_rect, + page_area=page_area, + header_y=header_y, + footer_y=footer_y, + ) ) - ) coverage = min(image_area / page_area, 1.0) if page_area > 0 else 0.0 return { diff --git a/apps/worker/app/services/document_parser/formats/pdf/pymupdf_subprocess.py b/apps/worker/app/services/document_parser/formats/pdf/pymupdf_subprocess.py index 64e280f8c..ce7c3e050 100644 --- a/apps/worker/app/services/document_parser/formats/pdf/pymupdf_subprocess.py +++ b/apps/worker/app/services/document_parser/formats/pdf/pymupdf_subprocess.py @@ -47,6 +47,12 @@ POST_RESULT_EXIT_GRACE_SECONDS = 5 # Child can exit 0 before multiprocessing.Queue's feeder flushes; retry once. EMPTY_QUEUE_EXIT_RETRIES = 1 +# Children run below the worker process's CPU priority. When the task's CPU is +# saturated the kernel schedules the gevent loop (lease renewal, heartbeats, +# VLM I/O) first; idle CPU still goes to the children at full speed. +CHILD_NICE_INCREMENT = 10 +# Payload key the child adds with its own CPU time; the parent logs and drops it. +_CHILD_CPU_KEY = "child_cpu_ms" PROCESS_POOL_SIZE = read_pymupdf_max_concurrent() PROCESS_POOL_CONTEXT = multiprocessing.get_context("spawn") @@ -279,9 +285,11 @@ def _run_worker_in_spawned_process_once( _close_result_queue(result_queue) - result = wait_result.result or {} + result = dict(wait_result.result or {}) + child_cpu_ms = result.pop(_CHILD_CPU_KEY, None) + child_log = child_log.bind(child_cpu_ms=child_cpu_ms) if not result.get("ok"): - logger.error( + child_log.error( f"[pymupdf-subprocess] FAILED pid={child_pid} fn={worker_fn.__name__} " f"elapsed={elapsed:.1f}s — {result.get('error_type')}: {result.get('error_msg')}" ) @@ -353,20 +361,23 @@ def worker(fn): The decorated function still receives (queue, *args). On unhandled exception, the error is serialized to the queue as a plain dict - so the parent can raise a clean RuntimeError. + so the parent can raise a clean RuntimeError. The child lowers its own + CPU priority first and reports the CPU time it spent with its payload. """ @functools.wraps(fn) def wrapped(queue, *args): + _lower_child_priority() + measured_queue = _CpuReportingQueue(queue) try: - fn(queue, *args) + fn(measured_queue, *args) except Exception as exc: # Log in child before serializing — child stderr may be the only # trace if the parent loses the queue result. import traceback traceback.print_exc() - queue.put( + measured_queue.put( { "ok": False, "error_type": type(exc).__name__, @@ -379,6 +390,33 @@ def wrapped(queue, *args): return wrapped +def _lower_child_priority() -> None: + # Only a spawned child: a direct in-process call must never slow the worker. + nice = getattr(os, "nice", None) + if nice is None or multiprocessing.parent_process() is None: + return + try: + nice(CHILD_NICE_INCREMENT) + except OSError as exc: + logger.debug(f"[pymupdf-subprocess] could not lower child priority: {exc}") + + +class _CpuReportingQueue: + """Adds the child's CPU time since it started work to each payload it puts.""" + + def __init__(self, queue: object) -> None: + self._queue = queue + self._cpu_started = time.process_time() + + def put(self, payload: object) -> None: + if isinstance(payload, dict): + payload = { + **payload, + _CHILD_CPU_KEY: round((time.process_time() - self._cpu_started) * 1_000), + } + self._queue.put(payload) # type: ignore[attr-defined] + + def run_in_child_process( worker_fn, *args, diff --git a/apps/worker/tests/contract/test_event_loop_monitor_contract.py b/apps/worker/tests/contract/test_event_loop_monitor_contract.py new file mode 100644 index 000000000..837ab1e23 --- /dev/null +++ b/apps/worker/tests/contract/test_event_loop_monitor_contract.py @@ -0,0 +1,42 @@ +"""A stall on the worker's hub thread is logged once, with what blocked it.""" + +from __future__ import annotations + +import time + +import gevent +from app.core.event_loop_monitor import EventLoopMonitor +from gevent.events import subscribers +from loguru import logger + + +def _hold_the_hub(seconds: float) -> None: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + pass + + +def test_a_long_stall_is_logged_once_with_the_blocking_stack() -> None: + captured: list[dict[str, object]] = [] + sink = logger.add(lambda message: captured.append(dict(message.record["extra"]))) + hub = gevent.get_hub() + try: + EventLoopMonitor.install() + gevent.sleep(1.2) # Let the reporter and the monitor thread settle. + _hold_the_hub(4.5) + gevent.sleep(2.5) # The reporter wakes late once, then on time. + finally: + EventLoopMonitor.stop() + monitor = hub.periodic_monitoring_thread + if monitor is not None: + monitor.kill() + hub.periodic_monitoring_thread = None + gevent.config.monitor_thread = False + if EventLoopMonitor._record_first_stack in subscribers: + subscribers.remove(EventLoopMonitor._record_first_stack) + logger.remove(sink) + + stalls = [record for record in captured if record.get("event") == "worker.event_loop_blocked"] + assert len(stalls) == 1 + assert 3_000 <= int(stalls[0]["blocked_ms"]) <= 5_000 # type: ignore[arg-type] + assert "_hold_the_hub" in str(stalls[0]["blocked_stack"]) diff --git a/apps/worker/tests/contract/test_page_screen_contract.py b/apps/worker/tests/contract/test_page_screen_contract.py index dde337ef8..fd2b02e6d 100644 --- a/apps/worker/tests/contract/test_page_screen_contract.py +++ b/apps/worker/tests/contract/test_page_screen_contract.py @@ -2,6 +2,7 @@ from __future__ import annotations +import base64 import os from pathlib import Path from types import SimpleNamespace @@ -9,6 +10,7 @@ import pymupdf import pytest +from PIL import Image os.environ.setdefault("DATABASE_URL", "postgresql+asyncpg://test:test@localhost/test") os.environ.setdefault("TMP_PATH", "/tmp/knowhere-test") @@ -145,6 +147,14 @@ def render_in_process( return items monkeypatch.setattr(sheet_module, "render_pages", render_in_process) + children: list[str] = [] + run_child = sheet_module.run_in_child_process + + def record_child(worker_fn: Any, *args: Any, **kwargs: Any) -> dict[str, Any]: + children.append(worker_fn.__name__) + return run_child(worker_fn, *args, **kwargs) + + monkeypatch.setattr(sheet_module, "run_in_child_process", record_child) blackboard = ProfileBlackboard(page_count=5) # The sheets only read each page's number and width. blackboard.page_features = cast( @@ -171,3 +181,10 @@ def render_in_process( assert rendered == [([1, 2, 3, 4, 5], 12, "sheets_dir")] saved = sorted(path.name for path in (tmp_path / "sheets_dir").glob("screen_*.png")) assert saved == ["screen_01.png", "screen_02.png"] + # Tiling and encoding stay off the gevent worker thread, and the VLM + # receives exactly the PNG that was encoded once and saved. + assert children == ["_tile_grids_worker", "_tile_grids_worker"] + assert base64.b64decode(images[0]) == (tmp_path / "sheets_dir" / "screen_01.png").read_bytes() + with Image.open(tmp_path / "sheets_dir" / "screen_02.png") as grid: + # One thumbnail cell 120 px wide plus the gaps on both sides. + assert grid.width == 120 + 2 * 8 diff --git a/apps/worker/tests/contract/test_parse_runtime_observation.py b/apps/worker/tests/contract/test_parse_runtime_observation.py index 6a765e446..44384b56f 100644 --- a/apps/worker/tests/contract/test_parse_runtime_observation.py +++ b/apps/worker/tests/contract/test_parse_runtime_observation.py @@ -1,5 +1,6 @@ """Exercise bounded Worker diagnostics and the production indexing limit.""" +import os import time from pathlib import Path @@ -60,3 +61,28 @@ def test_pymupdf_timeout_keeps_job_context_after_pool_handoff() -> None: assert matching[0]["child_timeout_seconds"] == 2 assert "pymupdf_queue_wait_ms" in matching[0] assert "child_cpu_ms" in matching[0] + + +@pymupdf_subprocess.worker +def _report_niceness_in_child(queue: object) -> None: + deadline = time.process_time() + 0.2 + while time.process_time() < deadline: + pass + queue.put({"ok": True, "niceness": os.nice(0)}) # type: ignore[attr-defined] + + +def test_pymupdf_child_runs_below_worker_priority_and_reports_its_cpu() -> None: + captured: list[dict[str, object]] = [] + sink = logger.add(lambda message: captured.append(dict(message.record["extra"]))) + try: + result = pymupdf_subprocess.run_in_child_process(_report_niceness_in_child, timeout=30) + finally: + logger.remove(sink) + + assert result == { + "ok": True, + "niceness": os.nice(0) + pymupdf_subprocess.CHILD_NICE_INCREMENT, + } + done = [record for record in captured if "child_elapsed_ms" in record] + assert len(done) == 1 + assert int(done[0]["child_cpu_ms"]) >= 200 # type: ignore[arg-type] diff --git a/apps/worker/tests/contract/test_worker_health_contract.py b/apps/worker/tests/contract/test_worker_health_contract.py index 635347128..ba20e675a 100644 --- a/apps/worker/tests/contract/test_worker_health_contract.py +++ b/apps/worker/tests/contract/test_worker_health_contract.py @@ -81,3 +81,40 @@ def test_should_reject_a_stale_visibility_recovery_heartbeat( with pytest.raises(SystemExit, match="Visibility recovery heartbeat stale"): worker_health.assert_worker_healthy() + + +def test_runtime_pressure_reports_the_worst_delay_since_the_last_warning( + monkeypatch: MonkeyPatch, +) -> None: + from loguru import logger + + from shared.services import worker_health + + # Seconds the loop wakes late on each heartbeat: one warning at once, then a + # 20 s stall inside the rate-limit window that the next warning must carry. + delays = [3.0, 20.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + clock = {"now": 0.0, "beat": 0} + + def sleep(seconds: float) -> None: + beat = clock["beat"] + clock["now"] += seconds + delays[beat] + clock["beat"] = beat + 1 + if clock["beat"] == len(delays): + worker_health._heartbeat_stop_event.set() + + monkeypatch.setattr(worker_health, "write_worker_heartbeat", lambda: None) + monkeypatch.setattr(worker_health.WorkerCpuSample, "read", classmethod(lambda cls: None)) + monkeypatch.setattr(worker_health.time, "monotonic", lambda: clock["now"]) + monkeypatch.setattr(worker_health.gevent, "sleep", sleep) + captured: list[dict[str, object]] = [] + sink = logger.add(lambda message: captured.append(dict(message.record["extra"]))) + worker_health._heartbeat_stop_event.clear() + try: + worker_health._heartbeat_loop() + finally: + logger.remove(sink) + worker_health._heartbeat_stop_event.clear() + + warnings = [record for record in captured if record.get("event") == "worker.runtime_pressure"] + assert [record["max_gevent_delay_ms"] for record in warnings] == [3000, 20000] + assert warnings[1]["gevent_delay_ms"] == 0 diff --git a/apps/worker/tests/unit/test_probe_dense_visual_assets.py b/apps/worker/tests/unit/test_probe_dense_visual_assets.py index d02deef86..7bd7f5b39 100644 --- a/apps/worker/tests/unit/test_probe_dense_visual_assets.py +++ b/apps/worker/tests/unit/test_probe_dense_visual_assets.py @@ -4,6 +4,8 @@ from types import SimpleNamespace +import pytest +from app.services.document_agent.tools import probe_page_features from app.services.document_agent.tools.probe_page_features import ( _DENSE_DRAWING_LIMIT, _DENSE_IMAGE_LIMIT, @@ -28,8 +30,12 @@ def __init__( *, image_count: int = 0, drawings_count: int = 0, + image_rects: list[_FakeRect] | None = None, + table_boxes: list[tuple[float, float, float, float]] | None = None, ) -> None: self.rect = _FakeRect(0, 0, 600, 800) + self._image_rects = image_rects or [] + self._tables = [SimpleNamespace(bbox=box) for box in table_boxes or []] self._images = [(index, 0, 0, 0, 0, 0, 0, 0) for index in range(image_count)] self._drawings = [ {"rect": _FakeRect(10, 10, 20, 20)} for _ in range(drawings_count) @@ -41,11 +47,11 @@ def get_images(self, full: bool = True) -> list[tuple[int, ...]]: return self._images def get_image_rects(self, _xref: int) -> list[_FakeRect]: - return [] + return self._image_rects def find_tables(self) -> SimpleNamespace: self.find_tables_calls += 1 - return SimpleNamespace(tables=[]) + return SimpleNamespace(tables=self._tables) def get_drawings(self) -> list[dict[str, _FakeRect]]: self.get_drawings_calls += 1 @@ -86,3 +92,36 @@ def test_normal_page_still_runs_table_finder() -> None: assert result["image_count"] == 2 assert result["drawings_count"] == 8 assert result["has_asset"] is False + + +def _fail_clustering(*_args: object, **_kwargs: object) -> list[object]: + raise AssertionError("drawing clustering must not run once an asset is found") + + +def test_page_with_an_image_skips_table_search_and_clustering( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(probe_page_features, "_figure_bboxes_from_drawings", _fail_clustering) + page = _FakePage( + image_count=1, drawings_count=8, image_rects=[_FakeRect(50, 50, 300, 300)] + ) + result = _probe_visual_assets( + page, _rect_area(page.rect), header_y=None, footer_y=None + ) + + assert page.find_tables_calls == 0 + assert result["drawings_count"] == 8 + assert result["table_count"] == 0 + assert result["has_asset"] is True + + +def test_page_with_a_table_skips_clustering(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(probe_page_features, "_figure_bboxes_from_drawings", _fail_clustering) + page = _FakePage(drawings_count=8, table_boxes=[(40, 100, 500, 400)]) + result = _probe_visual_assets( + page, _rect_area(page.rect), header_y=None, footer_y=None + ) + + assert page.find_tables_calls == 1 + assert result["table_count"] == 1 + assert result["has_asset"] is True diff --git a/apps/worker/tests/unit/test_pymupdf_subprocess_queue.py b/apps/worker/tests/unit/test_pymupdf_subprocess_queue.py index 1626daf66..3ee4c01c5 100644 --- a/apps/worker/tests/unit/test_pymupdf_subprocess_queue.py +++ b/apps/worker/tests/unit/test_pymupdf_subprocess_queue.py @@ -30,7 +30,12 @@ def _ok(queue: _FakeQueue, value: str) -> None: queue = _FakeQueue() _ok(queue, "payload") - assert queue.items == [{"ok": True, "value": "payload"}] + assert len(queue.items) == 1 + payload = queue.items[0] + assert isinstance(payload, dict) + # The wrapper adds the child's own CPU time; the parent logs and drops it. + assert payload.pop("child_cpu_ms") >= 0 + assert payload == {"ok": True, "value": "payload"} assert queue.closed is True assert queue.joined is True @@ -91,3 +96,16 @@ def _once(_worker_fn: object, _args: tuple, _timeout: int) -> dict: result = subprocess_mod._run_worker_in_spawned_process(lambda: None, (), 10) assert result == {"ok": True, "assets": []} assert calls["n"] == 2 + + +def test_worker_called_in_process_keeps_the_caller_priority() -> None: + import os + + @subprocess_mod.worker + def _ok(queue: _FakeQueue) -> None: + queue.put({"ok": True}) + + before = os.nice(0) + _ok(_FakeQueue()) + + assert os.nice(0) == before diff --git a/packages/shared-python/shared/services/worker_health.py b/packages/shared-python/shared/services/worker_health.py index 347353b5e..83cecaa4b 100644 --- a/packages/shared-python/shared/services/worker_health.py +++ b/packages/shared-python/shared/services/worker_health.py @@ -68,6 +68,9 @@ def _heartbeat_loop() -> None: task_capacity = None previous_cpu = WorkerCpuSample.read() last_warning = float("-inf") + # Warnings are rate limited; keep the worst delay in between so a stall + # that lands right after a warning is still reported by the next one. + max_delay = 0.0 while not _heartbeat_stop_event.is_set(): try: write_worker_heartbeat() @@ -77,25 +80,31 @@ def _heartbeat_loop() -> None: gevent.sleep(HEARTBEAT_INTERVAL_SECONDS) now = time.monotonic() delay = max(0.0, now - expected) + max_delay = max(max_delay, delay) cpu = WorkerCpuSample.read() observations = cpu.since(previous_cpu, task_capacity) if cpu and previous_cpu else {} previous_cpu = cpu if ( now - last_warning >= _RUNTIME_WARNING_INTERVAL_SECONDS - and (delay >= _SCHEDULING_DELAY_WARNING_SECONDS + and (max_delay >= _SCHEDULING_DELAY_WARNING_SECONDS or observations.get("cpu_utilization_percent", 0) >= _CPU_UTILIZATION_WARNING_PERCENT) ): - last_warning = now logger.bind( event="worker.runtime_pressure", worker_pid=os.getpid(), gevent_delay_ms=round(delay * 1000), + max_gevent_delay_ms=round(max_delay * 1000), + max_gevent_delay_window_seconds=( + None if last_warning == float("-inf") else round(now - last_warning) + ), **observations, ).warning( - "Worker runtime pressure: gevent delay {} ms, CPU utilization {}%", - round(delay * 1000), + "Worker runtime pressure: max gevent delay {} ms, CPU utilization {}%", + round(max_delay * 1000), observations.get("cpu_utilization_percent", "unavailable"), ) + last_warning = now + max_delay = 0.0 def get_worker_heartbeat_age() -> float | None: From 57711df4fcf4a0291c40228565734d7c32dd7be8 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Fri, 4 Dec 2026 00:48:47 -0700 Subject: [PATCH 2/2] Potential fix for pull request finding 'CodeQL / An assert statement has a side-effect' Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- apps/worker/tests/unit/test_pymupdf_subprocess_queue.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/worker/tests/unit/test_pymupdf_subprocess_queue.py b/apps/worker/tests/unit/test_pymupdf_subprocess_queue.py index 3ee4c01c5..d42b21eed 100644 --- a/apps/worker/tests/unit/test_pymupdf_subprocess_queue.py +++ b/apps/worker/tests/unit/test_pymupdf_subprocess_queue.py @@ -34,7 +34,8 @@ def _ok(queue: _FakeQueue, value: str) -> None: payload = queue.items[0] assert isinstance(payload, dict) # The wrapper adds the child's own CPU time; the parent logs and drops it. - assert payload.pop("child_cpu_ms") >= 0 + child_cpu_ms = payload.pop("child_cpu_ms") + assert child_cpu_ms >= 0 assert payload == {"ok": True, "value": "payload"} assert queue.closed is True assert queue.joined is True