Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/worker/app/core/tasks/document_ingestion_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
12 changes: 12 additions & 0 deletions apps/worker/app/core/visibility_recovery_watchdog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -202,19 +205,31 @@ 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)

if wait_result.status == "timeout" and not proc.is_alive():
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"
)
Expand All @@ -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"
)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 {}
62 changes: 62 additions & 0 deletions apps/worker/tests/contract/test_parse_runtime_observation.py
Original file line number Diff line number Diff line change
@@ -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]
4 changes: 3 additions & 1 deletion deploy/ecs/render_task_definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
4 changes: 2 additions & 2 deletions deploy/ecs/test_render_task_definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand All @@ -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


Expand Down
2 changes: 1 addition & 1 deletion packages/shared-python/shared/core/config/publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
54 changes: 44 additions & 10 deletions packages/shared-python/shared/services/redis/distributed_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
"""


Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand All @@ -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
Loading
Loading