diff --git a/apps/worker/app/core/tasks/document_ingestion_tasks.py b/apps/worker/app/core/tasks/document_ingestion_tasks.py index 1545d7f8d..b6e4d3a0c 100644 --- a/apps/worker/app/core/tasks/document_ingestion_tasks.py +++ b/apps/worker/app/core/tasks/document_ingestion_tasks.py @@ -151,7 +151,7 @@ def _run_parse_task( job_type: str = _DOCUMENT_INGESTION_JOB_TYPE, ): del job_type - with log_context(task_id=self.request.id): + with log_context(task_id=self.request.id, job_id=job_id): if not job_id: raise WorkerHandlingException( user_message="An unexpected system error occurred", diff --git a/apps/worker/app/core/visibility_recovery_watchdog.py b/apps/worker/app/core/visibility_recovery_watchdog.py index fa3b3febc..de6e22738 100644 --- a/apps/worker/app/core/visibility_recovery_watchdog.py +++ b/apps/worker/app/core/visibility_recovery_watchdog.py @@ -15,6 +15,8 @@ from shared.core.config import app_config from shared.core.logging import setup_logging from shared.services.worker_health import ( + HEARTBEAT_STALE_AFTER_SECONDS, + get_worker_heartbeat_age, remove_visibility_recovery_heartbeat, write_visibility_recovery_heartbeat, ) @@ -43,7 +45,17 @@ def run_visibility_recovery_watchdog() -> None: ) try: + reported_stale_heartbeat = False while True: + heartbeat_age = get_worker_heartbeat_age() + stale_heartbeat = ( + heartbeat_age is not None and heartbeat_age >= HEARTBEAT_STALE_AFTER_SECONDS / 2 + ) + if stale_heartbeat and not reported_stale_heartbeat: + logger.bind( + event="worker.heartbeat_delayed", heartbeat_age_seconds=heartbeat_age + ).warning("Main worker heartbeat delayed by {:.1f} seconds", heartbeat_age) + reported_stale_heartbeat = stale_heartbeat try: result: VisibilityRecoveryResult = restore_expired_reservations() if result["status"] == "attempted": 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 5b3b0c3dd..64e280f8c 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 @@ -18,14 +18,17 @@ import atexit import functools import multiprocessing +import os import queue as queue_module import time +from contextvars import copy_context from dataclasses import dataclass from multiprocessing.process import BaseProcess from multiprocessing.queues import Queue as MultiprocessingQueue from threading import RLock from typing import TYPE_CHECKING +import psutil from app.core.runtime_limits import read_pymupdf_max_concurrent from loguru import logger @@ -202,7 +205,13 @@ def _run_worker_in_spawned_process_once( t0 = time.monotonic() proc.start() child_pid = proc.pid - logger.info(f"[pymupdf-subprocess] started pid={child_pid} fn={worker_fn.__name__}") + child_log = logger.bind( + pymupdf_function=worker_fn.__name__, + child_pid=child_pid, + child_timeout_seconds=timeout, + child_spawn_ms=round((time.monotonic() - t0) * 1_000), + ) + child_log.info(f"[pymupdf-subprocess] started pid={child_pid} fn={worker_fn.__name__}") wait_result = _wait_for_child_result(proc, result_queue, timeout) @@ -210,11 +219,17 @@ def _run_worker_in_spawned_process_once( wait_result = _ChildWaitResult(status="crash") if wait_result.status == "timeout": + child_observation = _read_child_observation(child_pid) proc.kill() proc.join(timeout=CHILD_EXIT_GRACE_SECONDS) _close_result_queue(result_queue) elapsed = time.monotonic() - t0 - logger.error( + child_log.bind( + event="worker.pymupdf_timeout", + child_elapsed_ms=round(elapsed * 1_000), + child_exit_code=proc.exitcode, + **child_observation, + ).error( f"[pymupdf-subprocess] TIMEOUT pid={child_pid} fn={worker_fn.__name__} " f"after {timeout}s elapsed={elapsed:.1f}s — child killed" ) @@ -230,7 +245,11 @@ def _run_worker_in_spawned_process_once( proc.join(timeout=CHILD_EXIT_GRACE_SECONDS) elapsed = time.monotonic() - t0 _close_result_queue(result_queue) - logger.error( + child_log.bind( + event="worker.pymupdf_child_exit", + child_elapsed_ms=round(elapsed * 1_000), + child_exit_code=proc.exitcode, + ).error( f"[pymupdf-subprocess] CRASH pid={child_pid} fn={worker_fn.__name__} " f"exitcode={proc.exitcode} elapsed={elapsed:.1f}s — no result on queue" ) @@ -275,25 +294,55 @@ def _run_worker_in_spawned_process_once( ), ) - logger.info( + child_log.bind( + child_elapsed_ms=round(elapsed * 1_000), + child_result_ms=( + None if wait_result.received_at is None + else round((wait_result.received_at - t0) * 1_000) + ), + ).info( f"[pymupdf-subprocess] done pid={child_pid} fn={worker_fn.__name__} " f"elapsed={elapsed:.1f}s" ) return result +def _read_child_observation(pid: int | None) -> dict[str, int | str]: + """Sample an unresponsive child before killing it. It may exit during the read.""" + if pid is None: + return {} + try: + child = psutil.Process(pid) + with child.oneshot(): + cpu = child.cpu_times() + return { + "child_cpu_ms": round((cpu.user + cpu.system) * 1_000), + "child_rss_bytes": child.memory_info().rss, + "child_state_at_timeout": child.status(), + "child_thread_count": child.num_threads(), + } + except (psutil.Error, OSError): + return {} + + def _run_worker_in_spawned_process_safe( worker_fn, args: tuple, timeout: int, + queued_at: float, ) -> _ThreadPoolTaskResult: """Return exceptions to the caller greenlet so gevent does not log them as thread failures.""" - try: - return _ThreadPoolTaskResult( - result=_run_worker_in_spawned_process(worker_fn, args, timeout) - ) - except Exception as exc: - return _ThreadPoolTaskResult(error=exc) + with logger.contextualize( + worker_pid=os.getpid(), + pymupdf_pool_size=PROCESS_POOL_SIZE, + pymupdf_queue_wait_ms=round((time.monotonic() - queued_at) * 1_000), + ): + try: + return _ThreadPoolTaskResult( + result=_run_worker_in_spawned_process(worker_fn, args, timeout) + ) + except Exception as exc: + return _ThreadPoolTaskResult(error=exc) atexit.register(_shutdown_process_pool) @@ -355,10 +404,15 @@ def run_in_child_process( ) executor = _get_process_pool_executor() - task_result = executor.apply( - _run_worker_in_spawned_process_safe, - (worker_fn, args, timeout), - ) + caller_context = copy_context() + queued_at = time.monotonic() + + def run_with_caller_context() -> _ThreadPoolTaskResult: + return caller_context.run( + _run_worker_in_spawned_process_safe, worker_fn, args, timeout, queued_at + ) + + task_result = executor.apply(run_with_caller_context) if task_result.error is not None: raise task_result.error return task_result.result or {} diff --git a/apps/worker/tests/contract/test_parse_runtime_observation.py b/apps/worker/tests/contract/test_parse_runtime_observation.py new file mode 100644 index 000000000..6a765e446 --- /dev/null +++ b/apps/worker/tests/contract/test_parse_runtime_observation.py @@ -0,0 +1,62 @@ +"""Exercise bounded Worker diagnostics and the production indexing limit.""" + +import time +from pathlib import Path + +import pytest +from app.services.document_parser.formats.pdf import pymupdf_subprocess +from loguru import logger +from pydantic import ValidationError + +from shared.core.config.publication import PublicationConfig +from shared.services.worker_cpu import WorkerCpuSample + + +def test_production_indexing_limit_accepts_two_million_work_units() -> None: + config = PublicationConfig(KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS=2_097_152) + assert config.KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS == 2_097_152 + with pytest.raises(ValidationError): + PublicationConfig(KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS=2_097_153) + + +def test_cpu_pressure_uses_counter_deltas_and_task_capacity(tmp_path: Path) -> None: + (tmp_path / "cpu.stat").write_text( + "usage_usec 10900000\nnr_throttled 14\nthrottled_usec 450000\n" + ) + (tmp_path / "cpu.max").write_text("max 100000\n") + sample = WorkerCpuSample.read(tmp_path) + assert sample is not None + previous = WorkerCpuSample(sample.sampled_at - 5, 1, 10, 0.2, None) + + assert sample.since(previous, 2) == { + "cpu_sample_seconds": 5, + "cpu_cores_used": 1.98, + "cpu_throttled_periods": 4, + "cpu_throttled_ms": 250, + "cpu_capacity_cores": 2, + "cpu_utilization_percent": 99, + } + + +@pymupdf_subprocess.worker +def _sleep_in_child(_queue: object) -> None: + time.sleep(5) + + +def test_pymupdf_timeout_keeps_job_context_after_pool_handoff() -> None: + captured: list[dict[str, object]] = [] + sink = logger.add(lambda message: captured.append(dict(message.record["extra"]))) + try: + with logger.contextualize(job_id="job_observation_contract"): + with pytest.raises(pymupdf_subprocess.TimeoutException): + pymupdf_subprocess.run_in_child_process(_sleep_in_child, timeout=2) + finally: + logger.remove(sink) + + matching = [record for record in captured if record.get("event") == "worker.pymupdf_timeout"] + assert len(matching) == 1 + assert matching[0]["job_id"] == "job_observation_contract" + assert matching[0]["pymupdf_function"] == "_sleep_in_child" + assert matching[0]["child_timeout_seconds"] == 2 + assert "pymupdf_queue_wait_ms" in matching[0] + assert "child_cpu_ms" in matching[0] diff --git a/deploy/ecs/render_task_definitions.py b/deploy/ecs/render_task_definitions.py index 130185803..7643dbcb4 100644 --- a/deploy/ecs/render_task_definitions.py +++ b/deploy/ecs/render_task_definitions.py @@ -246,10 +246,12 @@ def render_template(template_path: Path, output_path: Path, variables: dict[str, raise ValueError("Task container must contain environment entries") if qstash_base_url: environment.append({"name": "QSTASH_BASE_URL", "value": qstash_base_url}) + if container.get("name") == "worker" and variables.get("WORKER_CPU"): + environment.append({"name": "WORKER_TASK_CPU_UNITS", "value": variables["WORKER_CPU"]}) if deployment_environment == "staging" and container.get("name") == "api": environment.append({"name": "DB_POOL_RECYCLE", "value": "-1"}) if deployment_environment == "prod": - environment.append({"name": "KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS", "value": "1048576"}) + environment.append({"name": "KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS", "value": "2097152"}) validate_rendered_definition(rendered) output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(json.dumps(rendered, indent=2) + "\n", encoding="utf-8") diff --git a/deploy/ecs/test_render_task_definitions.py b/deploy/ecs/test_render_task_definitions.py index c1e304c41..24dfdd49b 100644 --- a/deploy/ecs/test_render_task_definitions.py +++ b/deploy/ecs/test_render_task_definitions.py @@ -412,7 +412,7 @@ def test_production_cli_renders_the_backend_read_by_the_release( environment = {item["name"]: item["value"] for item in container["environment"]} secrets = {item["name"]: item["valueFrom"] for item in container["secrets"]} assert environment["KNOWHERE_LEXICAL_BACKEND"] == backend - assert environment["KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS"] == "1048576" + assert environment["KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS"] == "2097152" assert environment["KNOWHERE_OPENSEARCH_URL"] == PRODUCTION_OPENSEARCH["PROD_OPENSEARCH_URL"] assert environment["KNOWHERE_OPENSEARCH_INDEX_PREFIX"] == "knowhere-prod-lexical-v1" assert (environment["KNOWHERE_OPENSEARCH_OPEN_INDEX_LIMIT"], environment["KNOWHERE_OPENSEARCH_IDLE_HIGH_WATERMARK"], @@ -435,7 +435,7 @@ def test_production_cli_without_opensearch_keeps_the_postgresql_default( environment = {item["name"]: item["value"] for item in container["environment"]} secrets = {item["name"]: item["valueFrom"] for item in container["secrets"]} assert "KNOWHERE_LEXICAL_BACKEND" not in environment - assert environment["KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS"] == "1048576" + assert environment["KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS"] == "2097152" assert "KNOWHERE_PROD_NATIVE_TLS" not in secrets diff --git a/packages/shared-python/shared/core/config/publication.py b/packages/shared-python/shared/core/config/publication.py index 7eceba64d..5e8dfb5d9 100644 --- a/packages/shared-python/shared/core/config/publication.py +++ b/packages/shared-python/shared/core/config/publication.py @@ -42,7 +42,7 @@ class PublicationConfig(BaseSettings): KNOWHERE_INDEXING_UNSTARTED_TIMEOUT_SECONDS: int = Field(default=300, ge=1, le=1800) KNOWHERE_INDEXING_SETTLEMENT_TIMEOUT_SECONDS: float = Field(default=2, gt=0, le=10) KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS: int = Field( - default=524_288, ge=1_024, le=1_048_576, + default=524_288, ge=1_024, le=2_097_152, description="Maximum raw character/work count per record or scoring unit, before tokenization.", ) KNOWHERE_INDEXING_MAXIMUM_CJK_SPAN_CHARACTERS: int = Field(default=4_096, ge=256, le=8_192) diff --git a/packages/shared-python/shared/services/redis/distributed_lock.py b/packages/shared-python/shared/services/redis/distributed_lock.py index cd6f1e6a0..2e29892d1 100644 --- a/packages/shared-python/shared/services/redis/distributed_lock.py +++ b/packages/shared-python/shared/services/redis/distributed_lock.py @@ -37,11 +37,14 @@ # Prevents extending a lock that expired and was re-acquired # by another worker between GET and EXPIRE. _RENEW_SCRIPT = """ -if redis.call("get", KEYS[1]) == ARGV[1] then - return redis.call("expire", KEYS[1], ARGV[2]) -else +local owner = redis.call("get", KEYS[1]) +if not owner then return 0 end +if owner ~= ARGV[1] then + return 2 +end +return redis.call("expire", KEYS[1], ARGV[2]) """ @@ -92,9 +95,10 @@ def acquire(self, *, waitSeconds: float = 0.0) -> bool: client = self._redis._get_client() full_key = self._redis._build_key(self._lock_key) while True: + acquired_at = monotonic() if client.set(full_key, self._token, nx=True, ex=self._ttl): self._acquired = True - self._start_renewal() + self._start_renewal(acquired_at) logger.debug(f"Lock acquired: {self._lock_key}") return True remaining: float = deadline - monotonic() @@ -148,9 +152,9 @@ def __exit__(self, exc_type, exc_val, exc_tb) -> bool: # Renewal greenlet # ------------------------------------------------------------------ - def _start_renewal(self) -> None: + def _start_renewal(self, acquired_at: float) -> None: self._stop_event.clear() - self._renewal_greenlet = gevent.spawn(self._renewal_loop) + self._renewal_greenlet = gevent.spawn(self._renewal_loop, acquired_at) def _stop_renewal(self) -> None: self._stop_event.set() @@ -159,24 +163,54 @@ def _stop_renewal(self) -> None: g.kill(block=True, timeout=2) self._renewal_greenlet = None - def _renewal_loop(self) -> None: + def _renewal_loop(self, last_renewed_at: float) -> None: """Periodically reset the lock TTL while we still own it.""" + log = logger.bind( + event="worker.parse_lease_renewal", + job_id=self._job_id, + lease_ttl_seconds=self._ttl, + renewal_interval_seconds=self._renewal_interval, + ) + next_renewal_at = last_renewed_at + self._renewal_interval while not self._stop_event.is_set(): self._stop_event.wait(timeout=self._renewal_interval) if self._stop_event.is_set(): break + started_at = monotonic() + observation = log.bind( + renewal_delay_ms=round(max(0, started_at - next_renewal_at) * 1000), + since_redis_renewal_ms=round((started_at - last_renewed_at) * 1000), + ) + stage = "redis" try: result = self._redis.eval( _RENEW_SCRIPT, keys=[self._lock_key], args=[self._token, self._ttl], ) + redis_ms = round((monotonic() - started_at) * 1000) + observation = observation.bind(redis_renewal_ms=redis_ms) if result != 1: - logger.warning(f"Lock lost during renewal: {self._lock_key}") + reason = "owner_changed" if result == 2 else "key_missing" + observation.bind(outcome=reason).warning( + "Lock lost during renewal: {} ({})", self._lock_key, reason + ) self._acquired = False break + last_renewed_at = started_at + stage = "durable" + durable_started_at = monotonic() if self._onRenew is not None and not self._onRenew(): - logger.warning(f"Durable parsing ownership lost: {self._job_id}") + observation.bind( + outcome="durable_ownership_lost", + durable_renewal_ms=round((monotonic() - durable_started_at) * 1000), + ).warning("Durable parsing ownership lost: {}", self._job_id) break except Exception as exc: - logger.warning(f"Lock renewal failed for {self._lock_key}: {exc}") + observation.bind( + outcome="renewal_error", + renewal_stage=stage, + renewal_elapsed_ms=round((monotonic() - started_at) * 1000), + error_type=type(exc).__name__, + ).warning("Lock renewal failed for {} during {}", self._lock_key, stage) + next_renewal_at = monotonic() + self._renewal_interval diff --git a/packages/shared-python/shared/services/worker_cpu.py b/packages/shared-python/shared/services/worker_cpu.py new file mode 100644 index 000000000..d817ce211 --- /dev/null +++ b/packages/shared-python/shared/services/worker_cpu.py @@ -0,0 +1,86 @@ +"""Read container CPU counters without an agent or network call.""" + +from dataclasses import dataclass +from pathlib import Path +from time import monotonic + +_CGROUP_ROOT = Path("/sys/fs/cgroup") + + +@dataclass(frozen=True) +class WorkerCpuSample: + sampled_at: float + used_seconds: float + throttled_periods: int + throttled_seconds: float + capacity_cores: float | None + + @classmethod + def read(cls, root: Path = _CGROUP_ROOT) -> "WorkerCpuSample | None": + try: + return cls._read_v2(root) + except (OSError, ValueError, KeyError, ZeroDivisionError): + pass + for directory in ("cpu,cpuacct", "cpu"): + try: + return cls._read_v1(root, root / directory) + except (OSError, ValueError, KeyError, ZeroDivisionError): + continue + return None + + @classmethod + def _read_v2(cls, root: Path) -> "WorkerCpuSample": + counters = _read_counters(root / "cpu.stat") + quota, period = (root / "cpu.max").read_text().split() + return cls( + monotonic(), + counters["usage_usec"] / 1_000_000, + counters.get("nr_throttled", 0), + counters.get("throttled_usec", 0) / 1_000_000, + None if quota == "max" else int(quota) / int(period), + ) + + @classmethod + def _read_v1(cls, root: Path, cpu: Path) -> "WorkerCpuSample": + counters = _read_counters(cpu / "cpu.stat") + usage = cpu / "cpuacct.usage" + if not usage.exists(): + usage = root / "cpuacct" / "cpuacct.usage" + quota = int((cpu / "cpu.cfs_quota_us").read_text()) + period = int((cpu / "cpu.cfs_period_us").read_text()) + return cls( + monotonic(), + int(usage.read_text()) / 1_000_000_000, + counters["nr_throttled"], + counters["throttled_time"] / 1_000_000_000, + quota / period if quota > 0 else None, + ) + + def since( + self, previous: "WorkerCpuSample", task_capacity: float | None + ) -> dict[str, float | int]: + elapsed = self.sampled_at - previous.sampled_at + used = self.used_seconds - previous.used_seconds + throttled = self.throttled_periods - previous.throttled_periods + throttled_seconds = self.throttled_seconds - previous.throttled_seconds + if elapsed <= 0 or min(used, throttled, throttled_seconds) < 0: + return {} + cores = used / elapsed + observations: dict[str, float | int] = { + "cpu_sample_seconds": round(elapsed, 3), + "cpu_cores_used": round(cores, 3), + "cpu_throttled_periods": throttled, + "cpu_throttled_ms": round(throttled_seconds * 1_000), + } + capacity = self.capacity_cores or task_capacity + if capacity: + observations["cpu_capacity_cores"] = capacity + observations["cpu_utilization_percent"] = round(cores / capacity * 100, 1) + return observations + + +def _read_counters(path: Path) -> dict[str, int]: + return { + name: int(value) + for name, value in (line.split() for line in path.read_text().splitlines()) + } diff --git a/packages/shared-python/shared/services/worker_health.py b/packages/shared-python/shared/services/worker_health.py index affadcc3c..347353b5e 100644 --- a/packages/shared-python/shared/services/worker_health.py +++ b/packages/shared-python/shared/services/worker_health.py @@ -15,6 +15,7 @@ from loguru import logger from shared.core.config import app_config +from shared.services.worker_cpu import WorkerCpuSample HEARTBEAT_PATH = Path( os.getenv("WORKER_HEARTBEAT_FILE", "/tmp/knowhere-worker-heartbeat.json") @@ -36,6 +37,9 @@ _heartbeat_greenlet: Optional[gevent.Greenlet] = None _heartbeat_stop_event = Event() _heartbeat_lock = Semaphore() +_RUNTIME_WARNING_INTERVAL_SECONDS = 60.0 +_SCHEDULING_DELAY_WARNING_SECONDS = 2.0 +_CPU_UTILIZATION_WARNING_PERCENT = 90.0 def _write_heartbeat(path: Path) -> None: @@ -58,12 +62,48 @@ def remove_visibility_recovery_heartbeat() -> None: def _heartbeat_loop() -> None: + try: + task_capacity = int(os.getenv("WORKER_TASK_CPU_UNITS", "0")) / 1024 or None + except ValueError: + task_capacity = None + previous_cpu = WorkerCpuSample.read() + last_warning = float("-inf") while not _heartbeat_stop_event.is_set(): try: write_worker_heartbeat() except Exception as exc: logger.warning(f"Failed to write worker heartbeat: {exc}") + expected = time.monotonic() + HEARTBEAT_INTERVAL_SECONDS gevent.sleep(HEARTBEAT_INTERVAL_SECONDS) + now = time.monotonic() + delay = max(0.0, now - expected) + 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 + 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), + **observations, + ).warning( + "Worker runtime pressure: gevent delay {} ms, CPU utilization {}%", + round(delay * 1000), + observations.get("cpu_utilization_percent", "unavailable"), + ) + + +def get_worker_heartbeat_age() -> float | None: + """Read the main worker heartbeat from the independent recovery process.""" + try: + return max(0.0, time.time() - HEARTBEAT_PATH.stat().st_mtime) + except OSError: + return None def start_worker_heartbeat() -> None: