From 21055c38bf8363281920b7d506c570d97deaa67e Mon Sep 17 00:00:00 2001 From: suguanYang Date: Thu, 26 Nov 2026 19:47:00 -0700 Subject: [PATCH 01/22] Move S3 indexing input cleanup to an operator script --- .../test_lexical_index_resolution_contract.py | 3 +- .../test_lexical_maintenance_contract.py | 106 +++++++++- deploy/opensearch/README.md | 27 +++ .../retrieval/lexical/input_collector.py | 195 +++++++++--------- .../services/retrieval/lexical/maintenance.py | 24 +-- scripts/collect-indexing-inputs.py | 58 ++++++ 6 files changed, 283 insertions(+), 130 deletions(-) create mode 100644 scripts/collect-indexing-inputs.py diff --git a/apps/api/tests/contract/test_lexical_index_resolution_contract.py b/apps/api/tests/contract/test_lexical_index_resolution_contract.py index 88966d02a..7670eb5dc 100644 --- a/apps/api/tests/contract/test_lexical_index_resolution_contract.py +++ b/apps/api/tests/contract/test_lexical_index_resolution_contract.py @@ -117,8 +117,7 @@ def resolutionRuntime(monkeypatch: pytest.MonkeyPatch, postgresql_proc: PostgreS clear_application_modules() asyncio.run(prepare_contract_storage()) from shared.core.celery_app import celery_app - for taskName in ("maintainLexical", "cleanBuild", "cleanArchivedDocument", "cleanFailedAttempt", - "collectOrphanInputs", "resolveIndex"): + for taskName in ("maintainLexical", "cleanBuild", "cleanArchivedDocument", "cleanFailedAttempt", "resolveIndex"): celery_app.tasks.pop(f"shared.services.retrieval.lexical.maintenance.{taskName}", None) from shared.services.retrieval.lexical import resolution from shared.services.retrieval.lexical.maintenance_signals import LexicalMaintenanceSignals diff --git a/apps/api/tests/contract/test_lexical_maintenance_contract.py b/apps/api/tests/contract/test_lexical_maintenance_contract.py index 11c642531..e1eabfcb0 100644 --- a/apps/api/tests/contract/test_lexical_maintenance_contract.py +++ b/apps/api/tests/contract/test_lexical_maintenance_contract.py @@ -4,6 +4,10 @@ import asyncio from collections.abc import Iterator +import json +from pathlib import Path +import runpy +import sys from uuid import uuid4 from typing import TypeVar from types import SimpleNamespace @@ -35,7 +39,7 @@ def publishedInput(monkeypatch: pytest.MonkeyPatch, postgresql_proc: PostgreSQLP clear_application_modules() asyncio.run(prepare_contract_storage()) from shared.core.celery_app import celery_app - for taskName in ("maintainLexical", "cleanBuild", "cleanArchivedDocument", "cleanFailedAttempt", "collectOrphanInputs"): + for taskName in ("maintainLexical", "cleanBuild", "cleanArchivedDocument", "cleanFailedAttempt"): celery_app.tasks.pop(f"shared.services.retrieval.lexical.maintenance.{taskName}", None) from shared.models.database.user import User from shared.models.database.job import Job @@ -297,26 +301,39 @@ def test_orphan_inventory_keeps_winner_and_live_preparation_then_reclaims(monkey bucket: str = LexicalInputStorage().bucket adapter.upload_fileobj(BytesIO(b"orphan"), orphan, bucket=bucket) collector = LexicalInputCollector(sessionFactory=sessionmaker(engine, expire_on_commit=False)) - assert collector.discover() == 2 + page = collector.discover() + assert page is not None and len(page.objects) == 2 assert not collector.collectOrphan(winner) assert not collector.collectOrphan(orphan) + assert collector.findCandidates() == ((), ()) identity: str = LexicalInputRetention.getIdentity(bucket=bucket, key=orphan) with Session(engine) as db: requireRow(db, LexicalInputInventory, identity).firstSeenAt -= timedelta(days=1) + requireRow(db, LexicalInputInventory, identity).nextScanAt -= timedelta(days=1) db.commit() assert not collector.collectOrphan(orphan) # Even expired but unsettled work retains it. + assert collector.findCandidates() == ((), ()) with Session(engine) as db: requireRow(db, IndexingAttempt, attemptId).state = "succeeded" db.commit() + assert collector.findCandidates() == ((), (orphan,)) + with Session(engine) as db: + requireRow(db, JobResult, revisionId).indexing_input_key = orphan + db.commit() + assert not collector.collectOrphan(orphan) + assert adapter.exists(orphan, bucket=bucket) + with Session(engine) as db: + requireRow(db, JobResult, revisionId).indexing_input_key = winner + db.commit() assert collector.collectOrphan(orphan) assert not adapter.exists(orphan, bucket=bucket) assert adapter.exists(winner, bucket=bucket) @pytest.mark.parametrize("controlState", [ - None, ("postgresql", "serving"), ("postgresql", "gated"), ("opensearch", "gated"), + None, ("postgresql", "serving"), ("postgresql", "gated"), ("opensearch", "gated"), ("opensearch", "serving"), ]) -def test_worker_maintenance_waits_for_persisted_opensearch_serving( +def test_worker_maintenance_does_not_collect_indexing_inputs( monkeypatch: pytest.MonkeyPatch, publishedInput: tuple[Engine, str, str, str], controlState: tuple[str, str] | None, @@ -345,6 +362,7 @@ def test_worker_maintenance_waits_for_persisted_opensearch_serving( maintenance, "get_sync_session_factory", lambda: sessionmaker(engine, expire_on_commit=False), ) monkeypatch.setattr(LexicalCleanup, "closeEmptyNamespaces", lambda self: 0) + monkeypatch.setattr(maintenance, "turnOverIndexes", lambda: 0) assert maintenance.sweepLexical() == 0 with Session(engine) as db: @@ -357,6 +375,83 @@ def test_worker_maintenance_waits_for_persisted_opensearch_serving( assert db.get(LexicalBackendControl, 1) is None +def test_indexing_input_script_dry_run_and_apply_recheck_current_revision( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + publishedInput: tuple[Engine, str, str, str], +) -> None: + from shared.core.config.storage import get_cached_storage_adapter + from shared.models.database.document import Document + from shared.models.database.job_result import JobResult + from shared.models.database.lexicalbuild import LexicalBuild + from shared.services.retrieval.lexical import input_collector, maintenance + from shared.services.retrieval.lexical.additivecleanup import AdditiveCleanup + from shared.services.retrieval.lexical.cleanup import LexicalCleanup + from shared.services.retrieval.lexical.coordination import LexicalCoordination + + engine, buildId, _, revisionId = publishedInput + sessions: sessionmaker[Session] = sessionmaker(engine, expire_on_commit=False) + with sessions.begin() as db: + build: LexicalBuild = requireRow(db, LexicalBuild, buildId) + build.legacyCopyState = "completed" + documentId: str = build.documentId + document: Document = requireRow(db, Document, documentId) + document.status = "archived" + document.index_cleanup_after = LexicalCoordination.getDatabaseTime(db) + key: str | None = requireRow(db, JobResult, revisionId).indexing_input_key + assert key is not None + + monkeypatch.setattr(maintenance, "get_sync_session_factory", lambda: sessions) + monkeypatch.setattr(AdditiveCleanup, "collectDocument", lambda self, identity: True) + monkeypatch.setattr(LexicalCleanup, "closeEmptyNamespace", lambda self, identity: False) + assert maintenance.cleanArchivedDocument.run(documentId) == "completed" + + script: Path = Path(__file__).resolve().parents[4] / "scripts" / "collect-indexing-inputs.py" + collector = input_collector.LexicalInputCollector(sessionFactory=sessions) + monkeypatch.setattr(input_collector, "get_sync_session_factory", lambda: sessions) + monkeypatch.setattr(sys, "argv", [str(script)]) + with pytest.raises(SystemExit) as dryRun: + runpy.run_path(str(script), run_name="__main__") + assert dryRun.value.code == 0 + assert json.loads(capsys.readouterr().out) == { + "mode": "dry-run", "candidates": 1, "assigned_candidates": 1, "orphan_candidates": 0, + } + with sessions() as db: + result: JobResult = requireRow(db, JobResult, revisionId) + assert result.indexing_input_next_scan_at is None + assert result.indexing_input_gc_attempts == 0 + adapter = get_cached_storage_adapter() + assert adapter.exists(key, bucket=collector.bucket) + + findCandidates = input_collector.LexicalInputCollector.findCandidates + + def restoreReferenceDuringApply( + service: input_collector.LexicalInputCollector, + ) -> tuple[tuple[str, ...], tuple[str, ...]]: + candidates: tuple[tuple[str, ...], tuple[str, ...]] = findCandidates(service) + with sessions.begin() as db: + requireRow(db, Document, documentId).status = "active" + return candidates + + monkeypatch.setattr(sys, "argv", [str(script), "--apply"]) + with monkeypatch.context() as duringApply: + duringApply.setattr(input_collector.LexicalInputCollector, "findCandidates", restoreReferenceDuringApply) + with pytest.raises(SystemExit) as skipped: + runpy.run_path(str(script), run_name="__main__") + assert skipped.value.code == 1 + assert json.loads(capsys.readouterr().out)["not_collected"] == 1 + assert adapter.exists(key, bucket=collector.bucket) + + with sessions.begin() as db: + requireRow(db, Document, documentId).status = "archived" + requireRow(db, JobResult, revisionId).indexing_input_next_scan_at = None + with pytest.raises(SystemExit) as applied: + runpy.run_path(str(script), run_name="__main__") + assert applied.value.code == 0 + assert json.loads(capsys.readouterr().out)["collected"] == 1 + assert not adapter.exists(key, bucket=collector.bucket) + + def test_maintenance_visits_later_pending_builds_when_old_work_stays_blocked(monkeypatch: pytest.MonkeyPatch, publishedInput: tuple[Engine, str, str, str]) -> None: from datetime import timedelta from shared.models.database.lexicalbuild import LexicalBuild @@ -572,7 +667,8 @@ def failInventory(**arguments: object) -> None: cursor.nextScanAt -= timedelta(days=1) db.commit() monkeypatch.setattr(adapter, "list_object_page", listPage) - assert collector.discover() == 1 + page = collector.discover() + assert page is not None and len(page.objects) == 1 with Session(engine) as db: identity: str = LexicalInputRetention.getIdentity(bucket=bucket, key=key) requireRow(db, LexicalInputInventory, identity).firstSeenAt -= timedelta(days=1) diff --git a/deploy/opensearch/README.md b/deploy/opensearch/README.md index 5cd1a2630..32a4d787d 100644 --- a/deploy/opensearch/README.md +++ b/deploy/opensearch/README.md @@ -309,6 +309,33 @@ rechecks their actual UUIDs before each native snapshot delete, and uses no object TTL. File-only `manage.py snapshot-verify` is catalog review; a caller-provided digest cannot satisfy the restored payload proof or retention floor. +## On-demand S3 indexing input cleanup + +Run the operator script from the repository root on a DevOps host or one-off job +with access to the target environment's PostgreSQL database. Use the target +environment's database and object storage settings. Discovery and apply also +need access to the results bucket configured for indexing inputs. + +```bash +uv run --package knowhere-shared python scripts/collect-indexing-inputs.py --dry-run +uv run --package knowhere-shared python scripts/collect-indexing-inputs.py --apply +``` + +Dry-run is the default. It counts eligible assigned inputs and inventoried +orphans in a read-only database transaction. Apply inspects fresh candidates +and rechecks references and active consumers under locks before deleting each +object. The JSON report includes the number collected and the number left +untouched. Apply exits with status 1 when any candidate was left untouched, +including when a new reference or consumer appeared after inspection. + +To inventory objects that have yet to be registered, run the discovery mode. +It lists the indexing input prefix in S3 and updates the database inventory. +Newly observed orphans become eligible after the existing two-hour grace period. + +```bash +uv run --package knowhere-shared python scripts/collect-indexing-inputs.py --discover +``` + ## Manual native recovery An `uncertain` registry row on its own does not need this section. Resolution diff --git a/packages/shared-python/shared/services/retrieval/lexical/input_collector.py b/packages/shared-python/shared/services/retrieval/lexical/input_collector.py index 31fd1b7f6..495bfc62c 100644 --- a/packages/shared-python/shared/services/retrieval/lexical/input_collector.py +++ b/packages/shared-python/shared/services/retrieval/lexical/input_collector.py @@ -4,7 +4,7 @@ import re from loguru import logger -from sqlalchemy import func, or_, select +from sqlalchemy import Select, or_, select, text from sqlalchemy.dialects.postgresql import insert from sqlalchemy.orm import Session, noload, sessionmaker @@ -20,7 +20,6 @@ from shared.models.database.lexicallease import LexicalLease from shared.services.retrieval.corpus_storage import CorpusStorage from shared.services.retrieval.demo_authorization import authorize_demo_transaction -from shared.services.retrieval.lexical.cleanupbatch import CleanupBatch from shared.services.retrieval.lexical.coordination import LexicalCoordination from shared.services.retrieval.lexical.error import LexicalIndexError from shared.services.retrieval.lexical.input_retention import LexicalInputRetention @@ -29,14 +28,12 @@ _INPUT_PATTERN: re.Pattern[str] = re.compile(r"indexing-input/v1/([^/]{1,36})/([^/]{1,36})/[a-f0-9]{64}(?:-[a-f0-9]{32})?\.json\.zlib") _SCAN_INTERVAL: timedelta = timedelta(minutes=5) -# A current published input stays needed until its document is archived, and -# archival dispatches its own collection. The safety sweep only rechecks it daily. +# An input can become current between the operator's inspection and collection. _CURRENT_INPUT_RECHECK_INTERVAL: timedelta = timedelta(days=1) _ORPHAN_GRACE: timedelta = timedelta(seconds=7200) -MAXIMUM_SCAN: int = 100 -_MAXIMUM_BATCH: int = 20 -_MAXIMUM_BYTES: int = 64 * 1024 * 1024 +_MAXIMUM_SCAN: int = 100 _CURSOR_KEY: str = "__indexing_input_cursor__" +_Revision = tuple[JobResult, Job, Document | DemoDocument | None] class LexicalInputCollector: @@ -44,65 +41,60 @@ def __init__(self, *, sessionFactory: sessionmaker[Session] | None = None) -> No self.sessions: sessionmaker[Session] = sessionFactory or get_sync_session_factory() self.bucket: str = LexicalInputStorage().bucket - def run(self) -> int: - """List new bucket objects, then process one fair batch from each queue.""" - try: - self.discover() - except Exception as error: - logger.warning("Indexing input inventory deferred: error_type={}", type(error).__name__) - completed: int = self.runBatch().succeeded - self._logBacklog() - return completed - - def runBatch(self) -> CleanupBatch: - """Process one fair batch from each queue without listing the bucket; no age cutoff on eligibility.""" + def findCandidates(self) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Inspect due revisions and inventoried orphans in one read-only snapshot.""" + assigned: list[str] = [] + orphans: list[str] = [] with self.sessions.begin() as db: + db.execute(text("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")) now: datetime = LexicalCoordination.getDatabaseTime(db) - results: list[JobResult] = list(db.scalars(select(JobResult).options(noload("*")).where( - JobResult.indexing_input_key.is_not(None), JobResult.indexing_input_gc_state != "deleted", - or_(JobResult.indexing_input_next_scan_at.is_(None), JobResult.indexing_input_next_scan_at <= now), - ).order_by(JobResult.indexing_input_next_scan_at.asc().nullsfirst(), JobResult.id) - .limit(_MAXIMUM_BATCH).with_for_update(of=JobResult, skip_locked=True))) - revisions: tuple[str, ...] = tuple(result.id for result in results) - for result in results: - result.indexing_input_next_scan_at = now + _SCAN_INTERVAL - objects: list[LexicalInputInventory] = list(db.scalars(select(LexicalInputInventory).where( - LexicalInputInventory.bucket == self.bucket, - LexicalInputInventory.state.in_(("observed", "deleting")), - LexicalInputInventory.nextScanAt <= now, - ).order_by(LexicalInputInventory.nextScanAt, LexicalInputInventory.id) - .limit(_MAXIMUM_BATCH).with_for_update(skip_locked=True))) - keys: tuple[tuple[str, int], ...] = tuple((item.objectKey, item.sizeBytes or 0) for item in objects) - for item in objects: - item.nextScanAt = now + _SCAN_INTERVAL - completed: int = 0 - reclaimedBytes: int = 0 - for revision in revisions: - with self.sessions.begin() as db: - source = db.execute(select(JobResult.indexing_input_key, JobResult.indexing_input_bytes) - .where(JobResult.id == revision)).one_or_none() - if source is None or source[0] is None: - continue - try: - size: int = source[1] if source[1] is not None else ( - get_cached_storage_adapter().get_object_size(source[0], bucket=self.bucket) or 0) - except Exception as error: - self._recordFailure(source[0], revision, error) - continue - if reclaimedBytes and reclaimedBytes + size > _MAXIMUM_BYTES: - break - if self.collectAssigned(revision, knownSize=size): - completed += 1 - reclaimedBytes += size - for key, size in keys: - if reclaimedBytes and reclaimedBytes + size > _MAXIMUM_BYTES: - break - if self.collectOrphan(key): - completed += 1 - reclaimedBytes += size - return CleanupBatch(claimed=len(revisions) + len(keys), succeeded=completed) + assignedQuery: Select[tuple[str]] = ( + select(JobResult.id) + .where( + JobResult.indexing_input_key.is_not(None), + JobResult.indexing_input_gc_state != "deleted", + or_(JobResult.indexing_input_next_scan_at.is_(None), JobResult.indexing_input_next_scan_at <= now), + ~select(Document.document_id).where( + Document.current_job_result_id == JobResult.id, Document.status == "active", + ).exists(), + ~select(DemoDocument.document_id).where( + DemoDocument.current_job_result_id == JobResult.id, DemoDocument.status == "active", + ).exists(), + ) + .order_by(JobResult.indexing_input_next_scan_at.asc().nullsfirst(), JobResult.id) + ) + for revisionId in db.scalars(assignedQuery).all(): + revision: _Revision | None = self._loadRevision(db, revisionId, lock=False) + if revision is None: + continue + result, job, document = revision + key: str | None = result.indexing_input_key + if (key is not None and not self._isCurrentRevision(result, document) + and not self._hasConsumer(db, result, job, document, includeRetry=True) + and not self._hasReference(db, key, excludingRevision=revisionId)): + assigned.append(revisionId) + + orphanQuery: Select[tuple[str]] = ( + select(LexicalInputInventory.objectKey) + .where( + LexicalInputInventory.bucket == self.bucket, + LexicalInputInventory.state.in_(("observed", "deleting")), + LexicalInputInventory.nextScanAt <= now, + or_(LexicalInputInventory.state == "deleting", LexicalInputInventory.firstSeenAt <= now - _ORPHAN_GRACE), + ~select(JobResult.id).where( + JobResult.indexing_input_key == LexicalInputInventory.objectKey, + JobResult.indexing_input_gc_state != "deleted", + ).exists(), + ) + .order_by(LexicalInputInventory.nextScanAt, LexicalInputInventory.id) + ) + for key in db.scalars(orphanQuery).all(): + match: re.Match[str] | None = _INPUT_PATTERN.fullmatch(key) + if match is not None and self._isOrphanUnused(db, key, match[2], lock=False): + orphans.append(key) + return tuple(assigned), tuple(orphans) - def discover(self, *, isImmediate: bool = False) -> int: + def discover(self, *, isImmediate: bool = False) -> ObjectInventoryPage | None: """One persisted key cursor and at most one remote listing request. ``isImmediate`` lets an operator page through the bucket without waiting @@ -117,12 +109,12 @@ def discover(self, *, isImmediate: bool = False) -> int: cursor: LexicalInputInventory | None = db.scalar(select(LexicalInputInventory).where( LexicalInputInventory.id == identity).with_for_update(skip_locked=True)) if cursor is None or (not isImmediate and cursor.nextScanAt > now): - return 0 + return None after: str | None = cursor.scanAfter cursor.nextScanAt = now + _SCAN_INTERVAL try: page: ObjectInventoryPage = get_cached_storage_adapter().list_object_page( - prefix="indexing-input/v1/", after=after, limit=MAXIMUM_SCAN, bucket=self.bucket) + prefix="indexing-input/v1/", after=after, limit=_MAXIMUM_SCAN, bucket=self.bucket) except Exception as error: self._recordFailure(_CURSOR_KEY, None, error) raise @@ -130,7 +122,7 @@ def discover(self, *, isImmediate: bool = False) -> int: now = LexicalCoordination.getDatabaseTime(db) cursor = db.get(LexicalInputInventory, identity, with_for_update=True) if cursor is None or cursor.scanAfter != after: - return 0 + return None for key, size in page.objects: match: re.Match[str] | None = _INPUT_PATTERN.fullmatch(key) if match is None: @@ -152,13 +144,13 @@ def discover(self, *, isImmediate: bool = False) -> int: cursor.scanAfter = page.nextCursor cursor.nextScanAt = now + _SCAN_INTERVAL cursor.lastError = None - return len(page.objects) + return page - def collectAssigned(self, revisionId: str, *, knownSize: int | None = None) -> bool: + def collectAssigned(self, revisionId: str) -> bool: key: str | None = None try: with self.sessions.begin() as db: - locked = self._lockRevision(db, revisionId) + locked: _Revision | None = self._loadRevision(db, revisionId, lock=True) if locked is None: return False result, job, document = locked @@ -167,24 +159,23 @@ def collectAssigned(self, revisionId: str, *, knownSize: int | None = None) -> b return False now: datetime = LexicalCoordination.getDatabaseTime(db) result.indexing_input_next_scan_at = now + _SCAN_INTERVAL - if knownSize is not None: - result.indexing_input_bytes = knownSize # Backend verification and rollback both read the current published input. - if document is not None and document.status == "active" and document.current_job_result_id == result.id: + if self._isCurrentRevision(result, document): result.indexing_input_next_scan_at = now + _CURRENT_INPUT_RECHECK_INTERVAL return False if self._hasConsumer(db, result, job, document, includeRetry=True): return False - if db.scalar(select(JobResult.id).where(JobResult.indexing_input_key == key, - JobResult.id != revisionId, JobResult.indexing_input_gc_state != "deleted").limit(1)) is not None: + if self._hasReference(db, key, excludingRevision=revisionId): raise LexicalIndexError("Indexing input has another unresolved reference") + size: int | None = result.indexing_input_bytes item: LexicalInputInventory = self._lockObject(db, key, now) result.indexing_input_gc_state = "deleting" result.indexing_input_gc_attempts += 1 item.state = "deleting" item.attempts += 1 item.nextScanAt = now + _SCAN_INTERVAL - size: int | None = knownSize if knownSize is not None else get_cached_storage_adapter().get_object_size(key, bucket=self.bucket) + if size is None: + size = get_cached_storage_adapter().get_object_size(key, bucket=self.bucket) self._deleteObject(key) with self.sessions.begin() as db: result = db.scalar(select(JobResult).options(noload("*")).where(JobResult.id == revisionId).with_for_update(of=JobResult)) @@ -208,22 +199,13 @@ def collectOrphan(self, key: str) -> bool: revisionId: str = match[2] try: with self.sessions.begin() as db: - locked = self._lockRevision(db, revisionId) - # An existing result with a locked document/job is uncertain; - # skip rather than treating it as an absent canonical result. - if locked is None and db.scalar(select(JobResult.id).where(JobResult.id == revisionId)) is not None: - return False - references: list[str] = list(db.scalars(select(JobResult.id).where( - JobResult.indexing_input_key == key, JobResult.indexing_input_gc_state != "deleted"))) - if references: + if not self._isOrphanUnused(db, key, revisionId, lock=True): return False now: datetime = LexicalCoordination.getDatabaseTime(db) item: LexicalInputInventory = self._lockObject(db, key, now) item.nextScanAt = now + _SCAN_INTERVAL if item.state == "deleted": return False - if locked is not None and self._hasConsumer(db, *locked, includeRetry=False): - return False if item.state != "deleting" and now - item.firstSeenAt < _ORPHAN_GRACE: return False item.state = "deleting" @@ -238,7 +220,28 @@ def collectOrphan(self, key: str) -> bool: self._recordFailure(key, None, error) return False - def _lockRevision(self, db: Session, revisionId: str) -> tuple[JobResult, Job, Document | DemoDocument | None] | None: + def _isOrphanUnused(self, db: Session, key: str, revisionId: str, *, lock: bool) -> bool: + revision: _Revision | None = self._loadRevision(db, revisionId, lock=lock) + # A busy document or job can prevent a revision from being locked. + if revision is None and db.scalar(select(JobResult.id).where(JobResult.id == revisionId)) is not None: + return False + if self._hasReference(db, key): + return False + return revision is None or not self._hasConsumer(db, *revision, includeRetry=False) + + @staticmethod + def _hasReference(db: Session, key: str, *, excludingRevision: str | None = None) -> bool: + query: Select[tuple[str]] = select(JobResult.id).where( + JobResult.indexing_input_key == key, JobResult.indexing_input_gc_state != "deleted") + if excludingRevision is not None: + query = query.where(JobResult.id != excludingRevision) + return db.scalar(query.limit(1)) is not None + + @staticmethod + def _isCurrentRevision(result: JobResult, document: Document | DemoDocument | None) -> bool: + return document is not None and document.status == "active" and document.current_job_result_id == result.id + + def _loadRevision(self, db: Session, revisionId: str, *, lock: bool) -> _Revision | None: result: JobResult | None = db.scalar(select(JobResult).options(noload("*")).where(JobResult.id == revisionId)) if result is None: return None @@ -259,10 +262,14 @@ def _lockRevision(self, db: Session, revisionId: str) -> tuple[JobResult, Job, D documentId = str(metadata.get("document_id") or "") if storage.is_demo: authorize_demo_transaction(db, user_id=source.user_id) + documentQuery: Select[tuple[Document | DemoDocument]] = select(storage.Document).where( + storage.Document.document_id == documentId, storage.Document.user_id == storage.resolve_owner(source.user_id)) + if not lock: + return result, source, db.scalar(documentQuery) exists: str | None = db.scalar(select(storage.Document.document_id).where( storage.Document.document_id == documentId, storage.Document.user_id == storage.resolve_owner(source.user_id))) - document: Document | DemoDocument | None = db.scalar(select(storage.Document).where(storage.Document.document_id == documentId, - storage.Document.user_id == storage.resolve_owner(source.user_id)).with_for_update(skip_locked=True)) if exists is not None else None + document: Document | DemoDocument | None = db.scalar( + documentQuery.with_for_update(skip_locked=True)) if exists is not None else None if exists is not None and document is None: return None job: Job | None = db.scalar(select(Job).options(noload("*")).where(Job.job_id == source.job_id) @@ -317,15 +324,3 @@ def _recordFailure(self, key: str | None, revisionId: str | None, error: Excepti item.nextScanAt = now + _SCAN_INTERVAL except Exception as persistenceError: logger.error("Indexing input cleanup warning could not persist: error_type={}", type(persistenceError).__name__) - - def _logBacklog(self) -> None: - with self.sessions.begin() as db: - now: datetime = LexicalCoordination.getDatabaseTime(db) - count, size, firstSeen = db.execute(select(func.count(), func.coalesce(func.sum(LexicalInputInventory.sizeBytes), 0), - func.min(LexicalInputInventory.firstSeenAt)).where(LexicalInputInventory.bucket == self.bucket, - LexicalInputInventory.state.in_(("observed", "deleting")))).one() - retained: int = int(db.scalar(select(func.count()).select_from(JobResult).where( - JobResult.indexing_input_key.is_not(None), JobResult.indexing_input_gc_state != "deleted")) or 0) - oldestSeconds: float = max(0, (now - firstSeen).total_seconds()) if firstSeen is not None else 0 - logger.info("Indexing input backlog: pending_objects={} bytes={} oldest_seen={} oldest_seconds={} assigned_retained={} scan_limit={} queue_batch_limit={} byte_limit={} orphan_grace_seconds={}", - count, size, firstSeen, oldestSeconds, retained, MAXIMUM_SCAN, _MAXIMUM_BATCH, _MAXIMUM_BYTES, int(_ORPHAN_GRACE.total_seconds())) diff --git a/packages/shared-python/shared/services/retrieval/lexical/maintenance.py b/packages/shared-python/shared/services/retrieval/lexical/maintenance.py index 9e86d16f0..4f755b772 100644 --- a/packages/shared-python/shared/services/retrieval/lexical/maintenance.py +++ b/packages/shared-python/shared/services/retrieval/lexical/maintenance.py @@ -34,7 +34,6 @@ from shared.services.retrieval.lexical.cleanup import LexicalCleanup from shared.services.retrieval.lexical.cleanupbatch import CleanupBatch from shared.services.retrieval.lexical.copy_dispatch import LegacyCopyDispatch -from shared.services.retrieval.lexical.input_collector import MAXIMUM_SCAN, LexicalInputCollector from shared.services.retrieval.lexical.coordination import LexicalCoordination from shared.services.retrieval.lexical.maintenance_signals import ( CLEAN_ARCHIVED_DOCUMENT_TASK, CLEAN_BUILD_TASK, CLEAN_FAILED_ATTEMPT_TASK, RESOLVE_INDEX_TASK, @@ -46,7 +45,6 @@ from shared.services.retrieval.lexical.turnover import turnOverIndexes MAINTAIN_TASK: Final[str] = "shared.services.retrieval.lexical.maintenance.maintainLexical" -COLLECT_ORPHAN_INPUTS_TASK: Final[str] = "shared.services.retrieval.lexical.maintenance.collectOrphanInputs" # Matches the hourly beat_schedule slot in celery_app.py. _SWEEP_PERIOD_SECONDS: Final[int] = 3600 # The sweep drains due work in bounded passes and stops well before the next slot. @@ -87,7 +85,6 @@ def sweepLexical() -> int: completed += _runSafely("Index resolution", lambda: LexicalIndexResolution(sessionFactory=sessions).resolveDue(deadline)) completed += _drain("Additive index", lambda: AdditiveCleanup(sessions).runBatch(), deadline) - completed += _drain("Indexing input", lambda: LexicalInputCollector(sessionFactory=sessions).runBatch(), deadline) completed += _runSafely("Empty namespace", lambda: LexicalCleanup(sessionFactory=sessions).closeEmptyNamespaces()) completed += _runSafely("Index turnover", turnOverIndexes) completed += _runSafely("Manifest", lambda: collectPublishedManifests(sessions)) @@ -122,7 +119,7 @@ def cleanBuild(buildId: str, hop: int = 0) -> _Outcome: @celery_app.task(name=CLEAN_ARCHIVED_DOCUMENT_TASK) def cleanArchivedDocument(documentId: str, hop: int = 0) -> _Outcome: - """Remove one archived document from its index, then release its input and empty namespace.""" + """Remove one archived document from its index and close an empty namespace.""" sessions: sessionmaker[Session] = get_sync_session_factory() with sessions.begin() as db: document: Document | None = db.get(Document, documentId) @@ -132,12 +129,8 @@ def cleanArchivedDocument(documentId: str, hop: int = 0) -> _Outcome: if document.index_cleanup_after > now: return _reschedule(CLEAN_ARCHIVED_DOCUMENT_TASK, documentId, document.index_cleanup_after - now, hop) namespaceIndexId: str = LexicalScope(ownerId=document.user_id, namespace=document.namespace).fingerprint - revisionId: str | None = document.current_job_result_id if not AdditiveCleanup(sessions).collectDocument(documentId): return _reschedule(CLEAN_ARCHIVED_DOCUMENT_TASK, documentId, _CLAIM_LEASE, hop) - if revisionId is not None: - _runSafely("Indexing input", lambda: int( - LexicalInputCollector(sessionFactory=sessions).collectAssigned(revisionId))) _runSafely("Empty namespace", lambda: int( LexicalCleanup(sessionFactory=sessions).closeEmptyNamespace(namespaceIndexId))) return "completed" @@ -167,21 +160,6 @@ def resolveIndex(registryId: str, hop: int = 0) -> _Outcome: return LexicalIndexResolution().resolveDispatched(registryId, hop) -@celery_app.task(name=COLLECT_ORPHAN_INPUTS_TASK) -def collectOrphanInputs() -> int: - """Operator-run only: list the input bucket and delete unreferenced objects. - - Not scheduled, because listing S3 is the one maintenance step with no committed - row to trigger it. Run it by hand when orphan inputs need reclaiming. - """ - deadline: float = time.monotonic() + _SWEEP_BUDGET_SECONDS - collector: LexicalInputCollector = LexicalInputCollector() - # A short page is the end of the bucket; the cursor then restarts from the beginning. - while time.monotonic() < deadline and collector.discover(isImmediate=True) >= MAXIMUM_SCAN: - pass - return _drain("Indexing input", collector.runBatch, deadline) - - def _claimPendingBuilds(sessions: sessionmaker[Session], isNativeServing: bool) -> tuple[tuple[str, str, str], ...] | None: """Claim one batch of due builds; None when the backend is not serving.""" diff --git a/scripts/collect-indexing-inputs.py b/scripts/collect-indexing-inputs.py new file mode 100644 index 000000000..1f9eca4ee --- /dev/null +++ b/scripts/collect-indexing-inputs.py @@ -0,0 +1,58 @@ +"""Inspect or collect retained indexing inputs as an on-demand operation.""" + +import argparse +import json +import sys + + +def run() -> int: + parser: argparse.ArgumentParser = argparse.ArgumentParser(description=__doc__) + modes: argparse._MutuallyExclusiveGroup = parser.add_mutually_exclusive_group() + modes.add_argument("--dry-run", action="store_true", help="Count eligible inputs (default)") + modes.add_argument("--apply", action="store_true", help="Recheck and delete eligible inputs") + modes.add_argument("--discover", action="store_true", help="Refresh the S3 input inventory") + options: argparse.Namespace = parser.parse_args() + + try: + from shared.services.retrieval.lexical.input_collector import LexicalInputCollector + from shared.services.storage.object_inventory_page import ObjectInventoryPage + + collector: LexicalInputCollector = LexicalInputCollector() + if options.discover: + listedObjects: int = 0 + while True: + page: ObjectInventoryPage | None = collector.discover(isImmediate=True) + if page is None: + raise RuntimeError("Input inventory cursor moved during discovery") + listedObjects += len(page.objects) + if page.nextCursor is None: + break + print(json.dumps({"mode": "discover", "listed_objects": listedObjects})) + return 0 + + assigned: tuple[str, ...] + orphans: tuple[str, ...] + assigned, orphans = collector.findCandidates() + candidates: int = len(assigned) + len(orphans) + report: dict[str, int | str] = { + "mode": "apply" if options.apply else "dry-run", + "candidates": candidates, + "assigned_candidates": len(assigned), + "orphan_candidates": len(orphans), + } + if not options.apply: + print(json.dumps(report)) + return 0 + + collected: int = sum(collector.collectAssigned(revision) for revision in assigned) + collected += sum(collector.collectOrphan(key) for key in orphans) + report.update(collected=collected, not_collected=candidates - collected) + print(json.dumps(report)) + return int(collected != candidates) + except Exception as error: + print(f"Indexing input maintenance failed: {type(error).__name__}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(run()) From c4c3ee1cb2f95e925803db447927e2f8bb14497f Mon Sep 17 00:00:00 2001 From: suguanYang Date: Thu, 26 Nov 2026 22:55:15 -0700 Subject: [PATCH 02/22] Prepare production database TLS and API transaction timeouts --- .github/workflows/build-images.yml | 11 +++-- .../test_statement_deadline_contract.py | 49 ++++++++++++++++++- deploy/ecs/README.md | 7 +++ .../shared-python/shared/core/database.py | 44 +++++++++++------ 4 files changed, 89 insertions(+), 22 deletions(-) diff --git a/.github/workflows/build-images.yml b/.github/workflows/build-images.yml index 718873ba5..62d0c5ee8 100644 --- a/.github/workflows/build-images.yml +++ b/.github/workflows/build-images.yml @@ -37,6 +37,7 @@ env: AWS_ECS_PROD_SECRETS_ARN: ${{ secrets.AWS_ECS_PROD_SECRETS_ARN }} AWS_ECS_PROD_API_SERVICE_NAME: knowhere-api-prod AWS_ECS_PROD_WORKER_SERVICE_NAME: knowhere-worker-prod + PROD_DB_SSL_MODE: ${{ vars.PROD_DB_SSL_MODE || 'disable' }} jobs: build-and-publish: @@ -292,7 +293,7 @@ jobs: -m alembic upgrade heads migrate-ecs-production: - name: Run production Aurora database migration + name: Run production database migration runs-on: ubuntu-latest needs: build-and-publish if: ${{ github.event_name == 'release' && github.event.action == 'published' }} @@ -327,7 +328,7 @@ jobs: aws ecr get-login-password --region "${AWS_ECS_PROD_REGION}" \ | docker login --username AWS --password-stdin "${ECR_REGISTRY}" - - name: Run migration against production Aurora + - name: Run migration against the production database env: DATABASE_URL: ${{ secrets.PRODUCTION_MIGRATION_DATABASE_URL }} # The image build metadata uses the short release label `prod`, but @@ -345,7 +346,7 @@ jobs: --env S3_BUCKET_NAME \ --env TMP_PATH \ --env S3_TEMP_PATH \ - --env DB_SSL_MODE=disable \ + --env "DB_SSL_MODE=${PROD_DB_SSL_MODE}" \ --env ENVIRONMENT \ --entrypoint python \ "${image_uri}" \ @@ -843,7 +844,7 @@ jobs: --env S3_BUCKET_NAME \ --env S3_TEMP_PATH \ --env TMP_PATH \ - --env DB_SSL_MODE=disable \ + --env "DB_SSL_MODE=${PROD_DB_SSL_MODE}" \ --env ENVIRONMENT \ --entrypoint python \ "${API_IMAGE}" \ @@ -871,7 +872,7 @@ jobs: DEPLOYMENT_ENVIRONMENT: prod RUNTIME_ENVIRONMENT: production APP_ENV: production - DB_SSL_MODE: disable + DB_SSL_MODE: ${{ env.PROD_DB_SSL_MODE }} API_DB_POOL_SIZE: "50" API_DB_MAX_OVERFLOW: "50" WORKER_DB_SYNC_POOL_SIZE: "5" diff --git a/apps/api/tests/contract/test_statement_deadline_contract.py b/apps/api/tests/contract/test_statement_deadline_contract.py index a574d3963..209ee378c 100644 --- a/apps/api/tests/contract/test_statement_deadline_contract.py +++ b/apps/api/tests/contract/test_statement_deadline_contract.py @@ -1,8 +1,9 @@ -"""Owned PostgreSQL checks for the worker's client-side statement deadline (green mode).""" +"""Owned PostgreSQL checks for API and worker database deadlines.""" from __future__ import annotations from collections.abc import Callable, Iterator +from importlib import import_module import time from typing import Any @@ -12,13 +13,57 @@ from loguru import logger from psycopg2 import errors from sqlalchemy import create_engine, text +from sqlalchemy.engine import URL, make_url +from sqlalchemy.exc import DBAPIError from shared.core.statement_deadline import StatementDeadline -from shared.testing.contract_runtime import PostgreSQLProcess +from shared.testing.contract_runtime import ( + PostgreSQLProcess, + clear_application_modules, + configure_contract_environment, + get_contract_database_url, +) Connect = Callable[[], Any] +@pytest.mark.asyncio +async def testApiTransactionTimeouts( + monkeypatch: pytest.MonkeyPatch, + postgresql_proc: PostgreSQLProcess, +) -> None: + configure_contract_environment(monkeypatch, postgresql_proc) + url: URL = make_url(get_contract_database_url()).set(database="postgres") + monkeypatch.setenv("DATABASE_URL", url.render_as_string(hide_password=False)) + clear_application_modules() + database = import_module("shared.core.database") + try: + async with database.engine.connect() as connection: + async with connection.begin(): + await connection.exec_driver_sql("SET statement_timeout = 0") + await connection.exec_driver_sql("SET idle_in_transaction_session_timeout = 0") + + async with connection.begin(): + await connection.exec_driver_sql("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + assert await connection.scalar(text("SHOW transaction_isolation")) == "repeatable read" + assert await connection.scalar(text("SHOW transaction_read_only")) == "on" + assert await connection.scalar(text("SHOW statement_timeout")) == "30s" + assert await connection.scalar(text("SHOW idle_in_transaction_session_timeout")) == "1min" + + async with database.get_db_context_with_timeouts(120, 6) as session: + await session.execute(text("SET statement_timeout = 0")) + await session.commit() + assert await session.scalar(text("SHOW statement_timeout")) == "120ms" + with pytest.raises(DBAPIError) as error: + await session.execute(text("SELECT pg_sleep(2)")) + assert getattr(error.value.orig, "sqlstate", None) == "57014" + await session.rollback() + assert await session.scalar(text("SHOW statement_timeout")) == "120ms" + assert await session.scalar(text("SELECT 1")) == 1 + finally: + await database.dispose_all_engines() + + @pytest.fixture def greenDatabase(postgresql_proc: PostgreSQLProcess) -> Iterator[tuple[Connect, str, list[str]]]: url: str = (f"postgresql+psycopg2://{postgresql_proc.user}:{postgresql_proc.password or ''}" diff --git a/deploy/ecs/README.md b/deploy/ecs/README.md index 247216b0f..2453e1f12 100644 --- a/deploy/ecs/README.md +++ b/deploy/ecs/README.md @@ -75,6 +75,13 @@ additional GitHub Actions secrets: - `AWS_ECS_PROD_SECRETS_ARN` - `PRODUCTION_MIGRATION_DATABASE_URL` (direct migration-only database URL) +The repository variable `PROD_DB_SSL_MODE` controls the production migration, +the lexical backend database check, and both ECS task definitions. The default +is `disable` for the current Aurora configuration. Set it to `require` when +switching production to Neon. At that point, use Neon pooler URLs for the API +and worker runtime secret and a direct Neon URL for +`PRODUCTION_MIGRATION_DATABASE_URL`. + Before publishing the production release, an operator must create and verify the production runtime secret, IAM roles, API and worker ECS services, API target group/listener rule, production ACM certificate attachment, and diff --git a/packages/shared-python/shared/core/database.py b/packages/shared-python/shared/core/database.py index ecd30115b..4aeac9a18 100644 --- a/packages/shared-python/shared/core/database.py +++ b/packages/shared-python/shared/core/database.py @@ -5,6 +5,7 @@ from typing import Any, AsyncGenerator, Awaitable, Callable, TypeVar from sqlalchemy import event, text +from sqlalchemy.engine import Connection from sqlalchemy.ext.asyncio import ( AsyncEngine, AsyncSession, @@ -24,6 +25,7 @@ is_async_database_pool_disabled: bool = ( os.getenv("DB_USE_NULL_POOL", "false").lower() == "true" ) +IDLE_TRANSACTION_TIMEOUT_MS: int = 60_000 def _async_engine_options( @@ -40,7 +42,7 @@ def _async_engine_options( "application_name": "knowhere_api", "timezone": "UTC", "statement_timeout": str(statement_timeout_ms), - "idle_in_transaction_session_timeout": "60000", + "idle_in_transaction_session_timeout": str(IDLE_TRANSACTION_TIMEOUT_MS), }, "command_timeout": command_timeout_seconds, **ssl_connect_args, @@ -60,15 +62,30 @@ def _async_engine_options( return options -engine_options: dict[str, Any] = _async_engine_options( - statement_timeout_ms=30000, - command_timeout_seconds=30, -) +def _createApiEngine( + *, statementTimeoutMs: int, commandTimeoutSeconds: int +) -> AsyncEngine: + apiEngine: AsyncEngine = create_async_engine( + settings.DATABASE_URL, + **_async_engine_options( + statement_timeout_ms=statementTimeoutMs, + command_timeout_seconds=commandTimeoutSeconds, + ), + ) -engine = create_async_engine( - settings.DATABASE_URL, - **engine_options, -) + @event.listens_for(apiEngine.sync_engine, "begin") + def applyTransactionTimeouts(connection: Connection) -> None: + # Pooled PostgreSQL connections can ignore the driver's startup settings. + # SET also leaves callers free to issue SET TRANSACTION before their first query. + connection.exec_driver_sql(f"SET LOCAL statement_timeout = {statementTimeoutMs:d}") + connection.exec_driver_sql( + f"SET LOCAL idle_in_transaction_session_timeout = {IDLE_TRANSACTION_TIMEOUT_MS:d}" + ) + + return apiEngine + + +engine: AsyncEngine = _createApiEngine(statementTimeoutMs=30_000, commandTimeoutSeconds=30) # Create the async session factory. AsyncSessionFactory = async_sessionmaker( bind=engine, @@ -89,12 +106,9 @@ def _session_factory_for_timeouts( factory = _timeout_session_factories.get(key) if factory is not None: return factory - extra_engine = create_async_engine( - settings.DATABASE_URL, - **_async_engine_options( - statement_timeout_ms=statement_timeout_ms, - command_timeout_seconds=command_timeout_seconds, - ), + extra_engine: AsyncEngine = _createApiEngine( + statementTimeoutMs=statement_timeout_ms, + commandTimeoutSeconds=command_timeout_seconds, ) factory = async_sessionmaker(bind=extra_engine, expire_on_commit=False) _timeout_session_factories[key] = factory From daccfc8b3859b2f0f0c99c1f5671deb2ce52706b Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sat, 28 Nov 2026 07:58:20 -0700 Subject: [PATCH 03/22] Isolate Markdown heading preparation from the Worker loop A large Markdown document could starve the gevent heartbeat while the heading rules rewrote candidate rows one at a time. Run those rules in a bounded subprocess, batch candidate updates, and look up predictions by line ID. --- .../formats/markdown/parser.py | 34 ++++--- .../structure/heading_candidates.py | 36 +++++--- .../structure/layout_parser.py | 69 +++++++------- .../structure/markdown_heading_preparation.py | 91 +++++++++++++++++++ .../unit/test_markdown_heading_isolation.py | 89 ++++++++++++++++++ 5 files changed, 253 insertions(+), 66 deletions(-) create mode 100644 apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py create mode 100644 apps/worker/tests/unit/test_markdown_heading_isolation.py diff --git a/apps/worker/app/services/document_parser/formats/markdown/parser.py b/apps/worker/app/services/document_parser/formats/markdown/parser.py index 5c9f618c5..2791511d7 100755 --- a/apps/worker/app/services/document_parser/formats/markdown/parser.py +++ b/apps/worker/app/services/document_parser/formats/markdown/parser.py @@ -4,6 +4,8 @@ import re import shutil +import pandas as pd + from app.services.document_parser.support.identifiers import gen_str_codes, get_str_time from app.services.document_parser.formats.markdown.deferred_summary import ( MarkdownDeferredSummaryInput, @@ -78,7 +80,9 @@ def is_skip(line): return f"{prev_text} {next_text}".strip() -def heading_md_relocate(md_lines, heading_preds): +def heading_md_relocate( + md_lines: list[str], heading_preds: pd.DataFrame +) -> list[str]: """Relocate markdown headings based on predicted levels (sxjg simplified logic) When ``_apply_merge_signals`` has merged continuation rows (level='<') @@ -87,26 +91,20 @@ def heading_md_relocate(md_lines, heading_preds): For positive-level headings, we use the DataFrame's ``heading`` to ensure the merged text is emitted. """ - def remove_hash(txt): - return re.sub(r"^\s*(#+)\s*", "", txt) + predictions_by_line: dict[int, tuple[int, object]] = {} + for line_id, level, heading in heading_preds[["id", "level", "heading"]].itertuples( + index=False, name=None + ): + predictions_by_line.setdefault(line_id, (level, heading)) for lid, line_txt in enumerate(md_lines): - pred_level_df = heading_preds[heading_preds["id"] == lid] - - if pred_level_df.empty: # if the line does not enter predicting - line_txt = remove_hash(line_txt) + prediction: tuple[int, object] | None = predictions_by_line.get(lid) + if prediction is None or prediction[0] < 0: + line_txt = re.sub(r"^\s*(#+)\s*", "", line_txt) else: - pred_level = pred_level_df["level"].iloc[0] - if pred_level < 0: - line_txt = remove_hash(line_txt) - else: - # Use the DataFrame heading text which may have been updated - # by _apply_merge_signals (continuation rows appended). - heading_text = str(pred_level_df["heading"].iloc[0]).strip() - if not heading_text: - # Fallback: strip original line's '#' prefix - heading_text = line_txt.lstrip("#").lstrip() - line_txt = f"{'#' * int(pred_level)} {heading_text}" + level, heading = prediction + heading_text: str = str(heading).strip() or line_txt.lstrip("#").lstrip() + line_txt = f"{'#' * int(level)} {heading_text}" # update lines md_lines[lid] = line_txt.strip() diff --git a/apps/worker/app/services/document_parser/structure/heading_candidates.py b/apps/worker/app/services/document_parser/structure/heading_candidates.py index 8e1cb0592..3d0bff91b 100644 --- a/apps/worker/app/services/document_parser/structure/heading_candidates.py +++ b/apps/worker/app/services/document_parser/structure/heading_candidates.py @@ -252,6 +252,12 @@ def postprocess_headings(df: pd.DataFrame, task: str, max_depth: int = -1) -> pd return df +def estimate_heading_rule_levels(predictions: pd.DataFrame) -> pd.DataFrame: + predictions = _judge_negative_headings(predictions) + predictions["level"] = predictions["level"].replace(-2, 1) + return predictions + + def _is_non_heading_markdown_line(line: str) -> bool: return ( ("" in line) @@ -330,19 +336,27 @@ def _is_bold_docx_paragraph(paragraph: Any): def _judge_negative_headings(df: pd.DataFrame) -> pd.DataFrame: - for index, row in df.iterrows(): - neg_code = remove_by_conditions(row["heading"], include_punc=True) - if any(value > 0 for value in neg_code): - current_code = str(df.loc[index, "reason"]) + demote: list[bool] = [] + reasons: list[str] = [] + for heading, reason in df[["heading", "reason"]].itertuples(index=False, name=None): + neg_code: list[int] = remove_by_conditions(heading, include_punc=True) + should_demote: bool = any(neg_code) + demote.append(should_demote) + if not should_demote: + continue - neg_match = re.search(r"(.*NEG\s*)\[[^\]]*\](.*)", current_code) - if neg_match: - updated_code = f"{neg_match.group(1)}{neg_code}{neg_match.group(2)}" - else: - updated_code = f"{current_code} NEG {neg_code}" + current_code: str = str(reason) + neg_match: re.Match[str] | None = re.search(r"(.*NEG\s*)\[[^\]]*\](.*)", current_code) + updated_code: str = ( + f"{neg_match.group(1)}{neg_code}{neg_match.group(2)}" + if neg_match + else f"{current_code} NEG {neg_code}" + ) + reasons.append(updated_code) - df.loc[index, "level"] = -1 - df.loc[index, "reason"] = updated_code + if reasons: + df.loc[demote, "level"] = -1 + df.loc[demote, "reason"] = reasons return df diff --git a/apps/worker/app/services/document_parser/structure/layout_parser.py b/apps/worker/app/services/document_parser/structure/layout_parser.py index 209ae1eaa..91b2a59b7 100755 --- a/apps/worker/app/services/document_parser/structure/layout_parser.py +++ b/apps/worker/app/services/document_parser/structure/layout_parser.py @@ -4,8 +4,8 @@ import gevent import pandas as pd from app.services.document_parser.structure.heading_candidates import ( + estimate_heading_rule_levels, filter_document_headings, - filter_markdown_headings, postprocess_headings, ) from app.services.document_parser.structure.heading_llm_executor import ( @@ -20,6 +20,9 @@ from app.services.document_parser.structure.heading_tree import ( tree_to_dataframe as heading_tree_to_dataframe, ) +from app.services.document_parser.structure.markdown_heading_preparation import ( + prepare_markdown_headings, +) from app.services.document_parser.support.stage_profiler import stage_timer from app.services.document_parser.tables.table_text_parser import df2md from gevent.pool import Pool as GeventPool @@ -341,6 +344,9 @@ def _apply_merge_signals(df: pd.DataFrame) -> pd.DataFrame: Rows that carry ``"<"`` but have no preceding valid heading (e.g. the very first row) are simply demoted to -1 without merging. """ + if not df["level"].eq("<").any(): + return df + merge_count = 0 last_valid_idx: int | None = None # positional index of last positive-level row @@ -447,44 +453,44 @@ def pred_titles( f"Start to predict title hierarchy: doc_type={doc_type}, smart_parse={smart_parse}, candidate titles={len(infos)}" ) - if doc_type == "md": - raw_preds = filter_markdown_headings(infos) - elif doc_type == "docx": - raw_preds = filter_document_headings(infos, enable_regex=enable_regx) - else: - raw_preds = pd.DataFrame(columns=["id", "heading", "level", "reason"]) - # ── Exclude pre-TOC lines from heading prediction ── # When TOC is detected, lines/blocks before the first TOC area are typically # cover/metadata (company name, version, classification marks), not real # headings. Remove them before LLM judging to avoid misjudgment, then # splice back with level=-1 after all processing is done. - pre_toc_rows = None - first_toc_start = None + pre_toc_rows: pd.DataFrame | None = None if doc_type == "md": first_toc_start = _resolve_first_toc_boundary(toc_hierarchies=toc_hierarchies) + with stage_timer("heading.prepare_markdown_candidates", line_count=len(infos)): + raw_preds, pre_toc_rows = prepare_markdown_headings(infos, first_toc_start) + if pre_toc_rows is not None: + logger.info( + f"📌 Excluded {len(pre_toc_rows)} pre-TOC lines " + f"(id < {first_toc_start}) from heading prediction" + ) elif doc_type == "docx": + raw_preds = filter_document_headings(infos, enable_regex=enable_regx) first_toc_start = _resolve_first_toc_boundary( toc_hierarchies=toc_hierarchies, first_toc_ele_num=first_toc_ele_num, ) - - if first_toc_start is not None and first_toc_start > 0: - pre_toc_mask = raw_preds["id"] < first_toc_start - if pre_toc_mask.any(): - pre_toc_rows = raw_preds[pre_toc_mask].copy() - pre_toc_rows["level"] = -1 - raw_preds = raw_preds[~pre_toc_mask].reset_index(drop=True) - if doc_type == "docx": + if first_toc_start is not None and first_toc_start > 0: + pre_toc_mask: pd.Series = raw_preds["id"] < first_toc_start + if pre_toc_mask.any(): + pre_toc_rows = raw_preds[pre_toc_mask].copy() + pre_toc_rows["level"] = -1 + raw_preds = raw_preds[~pre_toc_mask].reset_index(drop=True) logger.info( f"📌 Excluded {len(pre_toc_rows)} pre-TOC blocks " f"(id < {first_toc_start}) from heading prediction" ) - else: - logger.info( - f"📌 Excluded {len(pre_toc_rows)} pre-TOC lines " - f"(id < {first_toc_start}) from heading prediction" - ) + else: + raw_preds = pd.DataFrame(columns=["id", "heading", "level", "reason"]) + + def apply_heading_rules(predictions: pd.DataFrame) -> pd.DataFrame: + if doc_type == "md": + return predictions + return est_hierarchies_naive(predictions) # 2. Zone-based prediction for native Markdown/DOCX coordinates only. if _supports_multi_toc_zones( @@ -523,11 +529,8 @@ def _process_single_zone(zone_idx, zone_start, zone_end, zone_toc): ) # Independent naive + LLM prediction for this zone - zone_heading = est_hierarchies_naive( - zone_preds, smart_parse, output_dir=output_dir - ) zone_heading = est_hierarchies_llm( - zone_heading, + apply_heading_rules(zone_preds), prompt_limt, toc_hierarchies=[zone_toc], # Single TOC for this zone model_name=model_name, @@ -580,9 +583,7 @@ def _process_single_zone(zone_idx, zone_start, zone_end, zone_toc): logger.info("✅ Zone-based LLM hierarchy parsing completed") else: # Single-zone: current behavior - heading_preds = est_hierarchies_naive( - raw_preds, smart_parse, output_dir=output_dir - ) + heading_preds = apply_heading_rules(raw_preds) if smart_parse: heading_preds = est_hierarchies_llm( heading_preds, @@ -660,13 +661,7 @@ def est_hierarchies_naive(raw_preds, proceed_smart=True, output_dir=None): compatibility but have no effect. """ logger.debug("🚀 non-llm parsing => judge_negs filtering") - heading_preds = postprocess_headings(raw_preds, task="judge_negs") - - # legitimate heading candidates; default them to top-level. - heading_preds["level"] = heading_preds["level"].map( - lambda x: 1 if x == -2 else x - ) - return heading_preds + return estimate_heading_rule_levels(raw_preds) def est_hierarchies_llm( diff --git a/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py b/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py new file mode 100644 index 000000000..6af8d61be --- /dev/null +++ b/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py @@ -0,0 +1,91 @@ +"""Run Markdown heading rules without blocking the Worker greenlets.""" + +from __future__ import annotations + +import pickle +import sys +from typing import TYPE_CHECKING + +from gevent import subprocess +from gevent.lock import BoundedSemaphore + +from shared.core.config import settings +from shared.core.exceptions.domain_exceptions import ( + TimeoutException, + WorkerHandlingException, +) + +if TYPE_CHECKING: + import pandas as pd + + +_HEADING_PROCESS_SLOT: BoundedSemaphore = BoundedSemaphore(1) + + +def prepare_markdown_headings( + lines: list[str], first_toc_start: int | None +) -> tuple[pd.DataFrame, pd.DataFrame | None]: + """Return rule-filtered candidates and the original rows before the TOC.""" + timeout_seconds: int = settings.TASK_TIME_LIMIT_SECONDS + with _HEADING_PROCESS_SLOT: + payload: bytes = pickle.dumps( + (lines, first_toc_start), protocol=pickle.HIGHEST_PROTOCOL + ) + with subprocess.Popen( + [sys.executable, "-m", __name__], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + ) as process: + try: + output, _ = process.communicate(payload, timeout=timeout_seconds) + except BaseException as error: + if process.poll() is None: + try: + process.kill() + except ProcessLookupError: + pass + # Let gevent's pipe readers finish before Popen closes the streams. + process.communicate() + if isinstance(error, subprocess.TimeoutExpired): + raise TimeoutException( + internal_message=f"Markdown heading preparation exceeded {timeout_seconds}s", + retry_after=settings.DOCUMENT_INGESTION_TASK_RETRY_COUNTDOWN, + ) from error + raise + if process.returncode != 0: + raise WorkerHandlingException( + internal_message=f"Markdown heading preparation exited with code {process.returncode}" + ) + result: tuple[pd.DataFrame, pd.DataFrame | None] = pickle.loads(output) + return result + + +def _run_child() -> None: + from app.core.runtime_limits import apply_native_thread_caps + + apply_native_thread_caps() + + from app.services.document_parser.structure.heading_candidates import ( + estimate_heading_rule_levels, + filter_markdown_headings, + ) + + lines, first_toc_start = pickle.load(sys.stdin.buffer) + predictions: pd.DataFrame = filter_markdown_headings(lines) + pre_toc_rows: pd.DataFrame | None = None + if first_toc_start is not None and first_toc_start > 0: + pre_toc_mask: pd.Series = predictions["id"] < first_toc_start + if pre_toc_mask.any(): + pre_toc_rows = predictions[pre_toc_mask].copy() + pre_toc_rows["level"] = -1 + predictions = predictions[~pre_toc_mask].reset_index(drop=True) + + result: tuple[pd.DataFrame, pd.DataFrame | None] = ( + estimate_heading_rule_levels(predictions), + pre_toc_rows, + ) + pickle.dump(result, sys.stdout.buffer, protocol=pickle.HIGHEST_PROTOCOL) + + +if __name__ == "__main__": + _run_child() diff --git a/apps/worker/tests/unit/test_markdown_heading_isolation.py b/apps/worker/tests/unit/test_markdown_heading_isolation.py new file mode 100644 index 000000000..cce4b72f3 --- /dev/null +++ b/apps/worker/tests/unit/test_markdown_heading_isolation.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import sys +from types import SimpleNamespace + +import gevent +import pandas as pd +import pytest + +from app.services.document_parser.structure import markdown_heading_preparation +from app.services.document_parser.structure.heading_candidates import filter_markdown_headings +from app.services.document_parser.structure.heading_hierarchy import ( + HeadingHierarchyInput, + predict_heading_hierarchy, +) +from shared.core.exceptions.domain_exceptions import TimeoutException + + +def test_markdown_heading_prediction_yields_to_the_worker_loop() -> None: + heartbeat: gevent.Greenlet = gevent.spawn(lambda: None) + try: + predictions: pd.DataFrame = predict_heading_hierarchy( + HeadingHierarchyInput(infos=["# Heading", "Body text"], doc_type="md") + ) + + assert heartbeat.ready() + assert predictions["level"].tolist() == [1, -1] + finally: + heartbeat.kill() + + +def test_markdown_heading_prediction_keeps_pre_toc_reasons() -> None: + lines: list[str] = ["# Cover.", "Front matter", "# Heading", "# A sentence."] + initial_predictions: pd.DataFrame = filter_markdown_headings(lines) + + predictions: pd.DataFrame = predict_heading_hierarchy( + HeadingHierarchyInput( + infos=lines, + doc_type="md", + toc_hierarchies=[{"toc_range": [2, 2]}], + ) + ) + + assert predictions["id"].tolist() == [0, 1, 2, 3] + assert predictions["level"].tolist() == [-1, -1, 1, -1] + assert ( + predictions["reason"].iloc[:2].tolist() + == initial_predictions["reason"].iloc[:2].tolist() + ) + assert predictions["reason"].iloc[3] != initial_predictions["reason"].iloc[3] + + +def test_markdown_heading_relocation_uses_first_prediction_for_each_line() -> None: + from app.services.document_parser.formats.markdown.parser import heading_md_relocate + + lines: list[str] = ["# First", "# Keep the original text", "# Body", " "] + predictions: pd.DataFrame = pd.DataFrame( + [(0, 2, "First continued"), (0, 3, "Duplicate"), (1, 1, "")], + columns=["id", "level", "heading"], + ) + + assert heading_md_relocate(lines, predictions) == [ + "## First continued", + "# Keep the original text", + "Body", + ] + + +def test_markdown_heading_timeout_reaps_the_child(monkeypatch: pytest.MonkeyPatch) -> None: + subprocess = markdown_heading_preparation.subprocess + start_process = subprocess.Popen + children: list[subprocess.Popen] = [] + + def start_sleeping_child(command: list[str], **kwargs: object) -> subprocess.Popen: + process = start_process([sys.executable, "-c", "import time; time.sleep(60)"], **kwargs) + children.append(process) + return process + + monkeypatch.setattr(subprocess, "Popen", start_sleeping_child) + monkeypatch.setattr( + markdown_heading_preparation, + "settings", + SimpleNamespace(TASK_TIME_LIMIT_SECONDS=0.1, DOCUMENT_INGESTION_TASK_RETRY_COUNTDOWN=120), + ) + + with pytest.raises(TimeoutException): + markdown_heading_preparation.prepare_markdown_headings(["# Heading"], None) + + assert len(children) == 1 and children[0].poll() is not None From 1b14de6807621b95aed530b47ba30b0918b7e839 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sat, 28 Nov 2026 08:03:46 -0700 Subject: [PATCH 04/22] Resolve Markdown subprocess review checks --- .../structure/markdown_heading_preparation.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py b/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py index 6af8d61be..613438ee3 100644 --- a/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py +++ b/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py @@ -4,7 +4,8 @@ import pickle import sys -from typing import TYPE_CHECKING +from contextlib import suppress +from typing import TYPE_CHECKING, cast from gevent import subprocess from gevent.lock import BoundedSemaphore @@ -40,10 +41,9 @@ def prepare_markdown_headings( output, _ = process.communicate(payload, timeout=timeout_seconds) except BaseException as error: if process.poll() is None: - try: + # The child can exit between poll() and kill(). + with suppress(ProcessLookupError): process.kill() - except ProcessLookupError: - pass # Let gevent's pipe readers finish before Popen closes the streams. process.communicate() if isinstance(error, subprocess.TimeoutExpired): @@ -76,9 +76,11 @@ def _run_child() -> None: if first_toc_start is not None and first_toc_start > 0: pre_toc_mask: pd.Series = predictions["id"] < first_toc_start if pre_toc_mask.any(): - pre_toc_rows = predictions[pre_toc_mask].copy() + pre_toc_rows = cast("pd.DataFrame", predictions[pre_toc_mask].copy()) pre_toc_rows["level"] = -1 - predictions = predictions[~pre_toc_mask].reset_index(drop=True) + predictions = cast( + "pd.DataFrame", predictions[~pre_toc_mask].reset_index(drop=True) + ) result: tuple[pd.DataFrame, pd.DataFrame | None] = ( estimate_heading_rule_levels(predictions), From a90c17221901996c4a64766974270b025dcf242c Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sat, 28 Nov 2026 08:07:57 -0700 Subject: [PATCH 05/22] Keep Markdown heading isolation on alternate execution paths Pass the current worker import path to the child and reuse precomputed Markdown rules when the model fails. Exercise both paths in regression tests. --- .../structure/layout_parser.py | 10 ++++++- .../structure/markdown_heading_preparation.py | 5 ++++ .../unit/test_markdown_heading_isolation.py | 30 +++++++++++++++++-- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/apps/worker/app/services/document_parser/structure/layout_parser.py b/apps/worker/app/services/document_parser/structure/layout_parser.py index 91b2a59b7..dc978e2fc 100755 --- a/apps/worker/app/services/document_parser/structure/layout_parser.py +++ b/apps/worker/app/services/document_parser/structure/layout_parser.py @@ -536,6 +536,7 @@ def _process_single_zone(zone_idx, zone_start, zone_end, zone_toc): model_name=model_name, output_dir=output_dir, csv_suffix=f"_zone_{zone_idx}", + reuse_rule_levels_on_fallback=doc_type == "md", ) valid_count = ( len(zone_heading[zone_heading["level"] > 0]) @@ -591,6 +592,7 @@ def _process_single_zone(zone_idx, zone_start, zone_end, zone_toc): toc_hierarchies, model_name=model_name, output_dir=output_dir, + reuse_rule_levels_on_fallback=doc_type == "md", ) logger.info("✅ LLM hierarchy parsing completed") @@ -673,6 +675,7 @@ def est_hierarchies_llm( model_name=None, output_dir=None, csv_suffix="", + reuse_rule_levels_on_fallback: bool = False, ): """LLM-based hierarchy detection — all chunks evaluated independently. @@ -699,11 +702,16 @@ def est_hierarchies_llm( csv_suffix: suffix for intermediate CSV filenames """ model_name = _resolve_hierarchy_model_name(model_name) + fallback_hierarchy = ( + (lambda predictions: predictions) + if reuse_rule_levels_on_fallback + else est_hierarchies_naive + ) return execute_llm_heading_hierarchy( raw_preds=raw_preds, prompt_limt=prompt_limt, hierarchy_judge=hiearchy_llm, - fallback_hierarchy=est_hierarchies_naive, + fallback_hierarchy=fallback_hierarchy, save_intermediate_csv=save_intermediate_csv, toc_hierarchies=toc_hierarchies, max_len=max_len, diff --git a/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py b/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py index 613438ee3..b96bbb15f 100644 --- a/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py +++ b/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py @@ -2,6 +2,7 @@ from __future__ import annotations +import os import pickle import sys from contextlib import suppress @@ -28,6 +29,9 @@ def prepare_markdown_headings( ) -> tuple[pd.DataFrame, pd.DataFrame | None]: """Return rule-filtered candidates and the original rows before the TOC.""" timeout_seconds: int = settings.TASK_TIME_LIMIT_SECONDS + environment: dict[str, str] = os.environ.copy() + # Local callers can register the Worker package through sys.path. + environment["PYTHONPATH"] = os.pathsep.join(sys.path) with _HEADING_PROCESS_SLOT: payload: bytes = pickle.dumps( (lines, first_toc_start), protocol=pickle.HIGHEST_PROTOCOL @@ -36,6 +40,7 @@ def prepare_markdown_headings( [sys.executable, "-m", __name__], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + env=environment, ) as process: try: output, _ = process.communicate(payload, timeout=timeout_seconds) diff --git a/apps/worker/tests/unit/test_markdown_heading_isolation.py b/apps/worker/tests/unit/test_markdown_heading_isolation.py index cce4b72f3..44f1f398e 100644 --- a/apps/worker/tests/unit/test_markdown_heading_isolation.py +++ b/apps/worker/tests/unit/test_markdown_heading_isolation.py @@ -1,13 +1,14 @@ from __future__ import annotations import sys +from pathlib import Path from types import SimpleNamespace import gevent import pandas as pd import pytest -from app.services.document_parser.structure import markdown_heading_preparation +from app.services.document_parser.structure import layout_parser, markdown_heading_preparation from app.services.document_parser.structure.heading_candidates import filter_markdown_headings from app.services.document_parser.structure.heading_hierarchy import ( HeadingHierarchyInput, @@ -16,7 +17,11 @@ from shared.core.exceptions.domain_exceptions import TimeoutException -def test_markdown_heading_prediction_yields_to_the_worker_loop() -> None: +def test_markdown_heading_prediction_yields_to_the_worker_loop( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("PYTHONPATH", raising=False) heartbeat: gevent.Greenlet = gevent.spawn(lambda: None) try: predictions: pd.DataFrame = predict_heading_hierarchy( @@ -50,6 +55,27 @@ def test_markdown_heading_prediction_keeps_pre_toc_reasons() -> None: assert predictions["reason"].iloc[3] != initial_predictions["reason"].iloc[3] +def test_markdown_heading_model_error_reuses_prepared_rules( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail_model(*args: object, **kwargs: object) -> list[dict[str, int]]: + raise RuntimeError("Model unavailable") + + def reject_repeated_rules(*args: object, **kwargs: object) -> pd.DataFrame: + pytest.fail("Markdown heading rules already ran in the subprocess") + + monkeypatch.setattr(layout_parser, "hiearchy_llm", fail_model) + monkeypatch.setattr(layout_parser, "est_hierarchies_naive", reject_repeated_rules) + + predictions: pd.DataFrame = predict_heading_hierarchy( + HeadingHierarchyInput( + infos=["# Heading", "# A sentence."], doc_type="md", smart_parse=True + ) + ) + + assert predictions["level"].tolist() == [1, -1] + + def test_markdown_heading_relocation_uses_first_prediction_for_each_line() -> None: from app.services.document_parser.formats.markdown.parser import heading_md_relocate From 21771c10ebe5f61275253c53dda842766d80a41a Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sat, 28 Nov 2026 08:47:45 -0700 Subject: [PATCH 06/22] Project heading tree levels in linear time Repeated ID searches in the heading tree projection starved the worker heartbeat on dense Markdown. Collect the first depth-first level per ID once and apply the levels in a single DataFrame write. --- .../document_parser/structure/heading_tree.py | 89 +++++++------------ .../unit/test_heading_tree_projection.py | 80 +++++++++++++++++ 2 files changed, 113 insertions(+), 56 deletions(-) create mode 100644 apps/worker/tests/unit/test_heading_tree_projection.py diff --git a/apps/worker/app/services/document_parser/structure/heading_tree.py b/apps/worker/app/services/document_parser/structure/heading_tree.py index 05f5919c7..5a74847d3 100644 --- a/apps/worker/app/services/document_parser/structure/heading_tree.py +++ b/apps/worker/app/services/document_parser/structure/heading_tree.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import cast + import pandas as pd from loguru import logger @@ -46,39 +48,28 @@ def tree_to_dataframe( node_to_id: dict[tuple[str, str], int], original_df: pd.DataFrame, ) -> pd.DataFrame: - preserved_headings = _extract_headings_from_tree(tree, node_to_id) - preserved_ids = {heading["id"] for heading in preserved_headings} + levels_by_id: dict[int, int] = {} + _collect_levels_by_id(tree, node_to_id, levels_by_id) - updated_df = original_df.copy() - removed_count = 0 - level_changed_count = 0 + original_levels: pd.Series = cast(pd.Series, original_df["level"]) + numeric_levels: pd.Series = original_levels.map( + lambda level: -1 if level == "nan" else int(level) + ) + heading_rows: pd.Series = numeric_levels.ge(0) + heading_ids: pd.Series = cast(pd.Series, original_df.loc[heading_rows, "id"]).map(int) + preserved_levels: pd.Series = heading_ids.map(levels_by_id) + projected_levels: pd.Series = preserved_levels.fillna(-1).astype(int) - for index, row in original_df.iterrows(): - row_id = int(row["id"]) - old_level = int(row["level"]) if row["level"] not in [-2, "nan", -1] else -1 + updated_df: pd.DataFrame = original_df.copy() + updated_df.loc[heading_rows, "level"] = projected_levels - if old_level <= -1: - continue - - if row_id in preserved_ids: - new_level = next( - ( - heading["level"] - for heading in preserved_headings - if heading["id"] == row_id - ), - old_level, - ) - updated_df.at[index, "level"] = new_level - if new_level != old_level: - level_changed_count += 1 - else: - updated_df.at[index, "level"] = -1 - removed_count += 1 + removed_count: int = int(preserved_levels.isna().sum()) + changed_levels: pd.Series = projected_levels.ne(numeric_levels.loc[heading_rows]) + level_changed_count: int = int((preserved_levels.notna() & changed_levels).sum()) logger.debug( f"Tree changed: removed headings={removed_count}, " - f"level changed={level_changed_count}, preserved headings={len(preserved_ids)}" + f"level changed={level_changed_count}, preserved headings={len(levels_by_id)}" ) return updated_df @@ -87,44 +78,30 @@ def remove_isolated_nodes(tree: dict[str, dict]) -> dict[str, dict]: return _remove_isolated_nodes_recursive(tree) -def _extract_headings_from_tree( +def _collect_levels_by_id( node_dict: dict[str, dict], node_to_id: dict[tuple[str, str], int], + levels_by_id: dict[int, int], *, current_level: int = 1, parent_path: str = "", -) -> list[dict[str, object]]: - results: list[dict[str, object]] = [] +) -> None: for tree_node_key, children in node_dict.items(): - node_key = (tree_node_key, parent_path) - row_id = node_to_id.get(node_key, -1) + row_id: int = node_to_id.get((tree_node_key, parent_path), -1) + if row_id < 0: + continue - if row_id >= 0: - original_heading = ( - tree_node_key.split("#")[0] if "#" in tree_node_key else tree_node_key - ) - results.append( - { - "id": row_id, - "heading": original_heading, - "level": current_level, - "tree_key": tree_node_key, - "parent_path": parent_path, - } + # Preserve the first depth-first match when a row appears in multiple nodes. + levels_by_id.setdefault(row_id, current_level) + if isinstance(children, dict) and children: + _collect_levels_by_id( + children, + node_to_id, + levels_by_id, + current_level=current_level + 1, + parent_path=append_document_path(parent_path, tree_node_key), ) - if isinstance(children, dict) and children: - current_path = append_document_path(parent_path, tree_node_key) - results.extend( - _extract_headings_from_tree( - children, - node_to_id, - current_level=current_level + 1, - parent_path=current_path, - ) - ) - return results - def _remove_isolated_nodes_recursive( node_dict: dict[str, dict], diff --git a/apps/worker/tests/unit/test_heading_tree_projection.py b/apps/worker/tests/unit/test_heading_tree_projection.py new file mode 100644 index 000000000..a960bb100 --- /dev/null +++ b/apps/worker/tests/unit/test_heading_tree_projection.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from typing import ClassVar + +import pandas as pd + +from app.services.document_parser.structure.heading_tree import ( + remove_isolated_nodes, + tree_to_dataframe, +) + + +class _MeasuredHeadingId(int): + equality_checks: ClassVar[int] = 0 + __hash__ = int.__hash__ + + def __eq__(self, other: object) -> bool: + type(self).equality_checks += 1 + return super().__eq__(other) + + +def test_tree_projection_does_not_rescan_headings_for_each_row() -> None: + heading_count: int = 512 + tree: dict[str, dict[str, object]] = { + f"Heading {index}": {} for index in range(heading_count) + } + node_to_id: dict[tuple[str, str], int] = { + (heading, ""): _MeasuredHeadingId(index) + for index, heading in enumerate(tree) + } + original: pd.DataFrame = pd.DataFrame( + {"id": range(heading_count), "level": [2] * heading_count} + ) + + _MeasuredHeadingId.equality_checks = 0 + projected: pd.DataFrame = tree_to_dataframe(tree, node_to_id, original) + + assert projected["level"].tolist() == [1] * heading_count + assert _MeasuredHeadingId.equality_checks <= 10 * heading_count + + +def test_tree_projection_preserves_rows_and_uses_first_matching_node() -> None: + tree: dict[str, dict[str, object]] = { + "Parent": {"First child": {}, "Second child": {}}, + "Standalone": {"Removed child": {}}, + "Duplicate ID": {}, + } + node_to_id: dict[tuple[str, str], int] = { + ("Parent", ""): 100, + ("First child", "Parent"): 101, + ("Second child", "Parent"): 102, + ("Standalone", ""): 103, + ("Removed child", "Standalone"): 104, + ("Duplicate ID", ""): 101, + } + original: pd.DataFrame = pd.DataFrame( + { + "id": [100, 101, 102, 103, 104, 105, 106], + "level": [3, 4, 4, 2, 3, -1, -2], + "heading": [ + "Parent", + "First child", + "Second child", + "Standalone", + "Removed child", + "Body", + "Rule candidate", + ], + }, + index=[4, 6, 7, 10, 13, 16, 18], + ) + expected: pd.DataFrame = original.copy() + expected["level"] = [1, 2, 2, 1, -1, -1, -2] + + projected: pd.DataFrame = tree_to_dataframe( + remove_isolated_nodes(tree), node_to_id, original + ) + + pd.testing.assert_frame_equal(projected, expected) + assert original["level"].tolist() == [3, 4, 4, 2, 3, -1, -2] From 5603397f701a8d185752b4acf92f99f28ff9f2ce Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sat, 28 Nov 2026 21:36:23 -0700 Subject: [PATCH 07/22] Raise production lexical indexing input limit --- deploy/ecs/render_task_definitions.py | 8 +++++--- deploy/ecs/test_render_task_definitions.py | 3 +++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/deploy/ecs/render_task_definitions.py b/deploy/ecs/render_task_definitions.py index 956cb1534..9c914c107 100644 --- a/deploy/ecs/render_task_definitions.py +++ b/deploy/ecs/render_task_definitions.py @@ -231,8 +231,8 @@ def render_template(template_path: Path, output_path: Path, variables: dict[str, configure_staging_opensearch(rendered, variables) configure_production_opensearch(rendered, variables) qstash_base_url: str = variables.get("QSTASH_BASE_URL", "") - is_staging: bool = variables.get("DEPLOYMENT_ENVIRONMENT") == "staging" - if qstash_base_url or is_staging: + deployment_environment: str = variables.get("DEPLOYMENT_ENVIRONMENT", "") + if qstash_base_url or deployment_environment in ("staging", "prod"): if not isinstance(rendered, dict): raise ValueError("Task definition must be an object") containers: object = rendered.get("containerDefinitions") @@ -246,8 +246,10 @@ 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 is_staging and container.get("name") == "api": + 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"}) 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 0a7c11121..987fb0ad0 100644 --- a/deploy/ecs/test_render_task_definitions.py +++ b/deploy/ecs/test_render_task_definitions.py @@ -272,6 +272,7 @@ def test_staging_templates_preserve_expected_staging_configuration( for name, value in expected_environment.items(): assert environment_values[name] == value + assert "KNOWHERE_INDEXING_MAXIMUM_UNIT_CHARACTERS" not in environment_values def test_staging_worker_preserves_evidence_selected_capacity(tmp_path: Path) -> None: @@ -377,6 +378,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_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"], @@ -399,6 +401,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 "KNOWHERE_PROD_NATIVE_TLS" not in secrets From 20dc01a1d717a5c389daaef3e8af3fe84cdaa24e Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sun, 29 Nov 2026 00:07:17 -0700 Subject: [PATCH 08/22] Preserve anchors on TOC rehome path collisions --- .../document_agent/structure/toc_rehome.py | 14 ++++++- .../contract/test_toc_rehome_contract.py | 39 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/apps/worker/app/services/document_agent/structure/toc_rehome.py b/apps/worker/app/services/document_agent/structure/toc_rehome.py index 66849663b..255407520 100644 --- a/apps/worker/app/services/document_agent/structure/toc_rehome.py +++ b/apps/worker/app/services/document_agent/structure/toc_rehome.py @@ -323,6 +323,19 @@ def _apply_plans( f"{_LOG_PREFIX} dest parent missing path={dest_parent!r}" ) + new_path: tuple[str, ...] = (*dest_parent, source_path[-1]) + # A reused path makes both leaves share one match during range resolution. + if new_path != source_path and ( + new_path in overrides or node_at_path(working, new_path) is not None + ): + logger.info( + "{} skip occupied destination page={} segment={}", + _LOG_PREFIX, + plan.physical_page, + plan.segment_index, + ) + continue + working, detached = _detach_node(working, source_path) if detached is None: raise ValueError( @@ -330,7 +343,6 @@ def _apply_plans( ) target_level = len(dest_parent) + 1 detached = rebase_levels(detached, target_level - detached.level) - new_path = (*dest_parent, detached.title) working = _insert_under_parent( nodes=working, parent_path=dest_parent, diff --git a/apps/worker/tests/contract/test_toc_rehome_contract.py b/apps/worker/tests/contract/test_toc_rehome_contract.py index 755889275..82be4edb8 100644 --- a/apps/worker/tests/contract/test_toc_rehome_contract.py +++ b/apps/worker/tests/contract/test_toc_rehome_contract.py @@ -76,6 +76,45 @@ def test_no_prev_leaf_by_page_is_noop_for_that_backjump() -> None: assert result.events == [] +def test_rehome_keeps_the_page_anchor_when_destination_path_is_occupied() -> None: + nodes: list[TitleNode] = [ + TitleNode( + title="First section", + level=1, + children=[ + TitleNode(title="Overview", level=2, printed_page=6), + TitleNode(title="Details", level=2, printed_page=7), + ], + ), + TitleNode( + title="Second section", + level=1, + children=[TitleNode(title="Overview", level=2, printed_page=14)], + ), + ] + anchor_path: tuple[str, ...] = ("First section", "Overview") + source_path: tuple[str, ...] = ("Second section", "Overview") + overrides: dict[tuple[str, ...], TitleMatch] = _overrides( + {anchor_path: 9, ("First section", "Details"): 10, source_path: 9} + ) + + rehomed = rehome_forest(nodes, overrides) + ranges = resolve_hierarchy_page_ranges( + rehomed.nodes, + page_count=125, + match_overrides=rehomed.match_overrides, + ) + + assert [item.path_titles for item in ranges] == [ + anchor_path, + ("First section", "Details"), + source_path, + ] + assert ranges[0].start_page <= 9 <= ranges[0].end_page + assert ranges[0].match == overrides[anchor_path] + assert rehomed.match_overrides[source_path] == overrides[source_path] + + def test_equal_page_backjump_inserts_after_front_same_page_leaves() -> None: """Rehome @116 with one or more front @116 leaves → after that same-page group.""" nodes = [ From f7ca9ade8879349173bfa059ef17b649c8d8c68c Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sun, 29 Nov 2026 00:38:24 -0700 Subject: [PATCH 09/22] Make Knowhere production S3 placement configurable --- .github/workflows/build-images.yml | 27 +++++++++++++-- deploy/ecs/render_task_definitions.py | 3 +- deploy/ecs/task-definition-api.staging.json | 2 +- .../ecs/task-definition-worker.staging.json | 2 +- deploy/ecs/test_render_task_definitions.py | 34 +++++++++++++++++++ 5 files changed, 62 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build-images.yml b/.github/workflows/build-images.yml index 62d0c5ee8..876326b18 100644 --- a/.github/workflows/build-images.yml +++ b/.github/workflows/build-images.yml @@ -823,6 +823,24 @@ jobs: resolve_image knowhere-backend api_image resolve_image knowhere-worker worker_image + - name: Resolve production S3 storage + id: production_storage + env: + STORAGE_CONFIGURATION: ${{ vars.PROD_S3_STORAGE || '{"bucket":"knowhere-storage-prod","region":"us-east-1","sns_topic_arn":"arn:aws:sns:us-east-1:107424103509:knowhere-prod-s3-events"}' }} + shell: bash + run: | + set -euo pipefail + bucket="$(jq -er '.bucket | select(test("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$"))' <<< "$STORAGE_CONFIGURATION")" + region="$(jq -er '.region | select(test("^[a-z]{2}(-[a-z]+)+-[0-9]+$"))' <<< "$STORAGE_CONFIGURATION")" + topic="$(jq -er '.sns_topic_arn | select(test("^arn:aws:sns:[a-z0-9-]+:107424103509:[A-Za-z0-9_-]+$"))' <<< "$STORAGE_CONFIGURATION")" + if [[ "$topic" != "arn:aws:sns:$region:107424103509:"* ]]; then + echo "::error::Production S3 storage and upload notifications must use the same region." + exit 1 + fi + echo "bucket=$bucket" >> "$GITHUB_OUTPUT" + echo "region=$region" >> "$GITHUB_OUTPUT" + echo "sns_topic_arn=$topic" >> "$GITHUB_OUTPUT" + - name: Read lexical backend from the database control row id: lexical_backend # Render the backend the database serves. A gated control row means an @@ -831,7 +849,8 @@ jobs: DATABASE_URL: ${{ secrets.PRODUCTION_MIGRATION_DATABASE_URL }} API_IMAGE: ${{ steps.images.outputs.api_image }} ENVIRONMENT: production - S3_BUCKET_NAME: knowhere-storage-prod + S3_BUCKET_NAME: ${{ steps.production_storage.outputs.bucket }} + S3_REGION: ${{ steps.production_storage.outputs.region }} S3_TEMP_PATH: /tmp TMP_PATH: /tmp/aismart_bid shell: bash @@ -846,6 +865,7 @@ jobs: --env TMP_PATH \ --env "DB_SSL_MODE=${PROD_DB_SSL_MODE}" \ --env ENVIRONMENT \ + --env S3_REGION \ --entrypoint python \ "${API_IMAGE}" \ -m shared.services.retrieval.lexical.deployment_backend)" @@ -877,11 +897,12 @@ jobs: API_DB_MAX_OVERFLOW: "50" WORKER_DB_SYNC_POOL_SIZE: "5" WORKER_DB_SYNC_MAX_OVERFLOW: "5" - S3_BUCKET_NAME: knowhere-storage-prod + S3_BUCKET_NAME: ${{ steps.production_storage.outputs.bucket }} + S3_REGION: ${{ steps.production_storage.outputs.region }} INTERNAL_DASHBOARD_ENDPOINT: https://knowhereto.ai FRONTEND_URL: https://knowhereto.ai API_WEBHOOK_ENDPOINT: https://api.knowhereto.ai/v1/internal/s3-events - SNS_TOPIC_ARN: arn:aws:sns:us-east-1:107424103509:knowhere-prod-s3-events + SNS_TOPIC_ARN: ${{ steps.production_storage.outputs.sns_topic_arn }} QSTASH_CALLBACK_BASE_URL: https://api.knowhereto.ai/api/v1 QSTASH_BASE_URL: https://qstash-us-east-1.upstash.io API_CPU: "512" diff --git a/deploy/ecs/render_task_definitions.py b/deploy/ecs/render_task_definitions.py index 9c914c107..130185803 100644 --- a/deploy/ecs/render_task_definitions.py +++ b/deploy/ecs/render_task_definitions.py @@ -227,7 +227,7 @@ def attach_opensearch( def render_template(template_path: Path, output_path: Path, variables: dict[str, str]) -> None: """Render one JSON template to a deployment-only output path.""" definition = json.loads(template_path.read_text(encoding="utf-8")) - rendered = replace_placeholders(definition, variables) + rendered = replace_placeholders(definition, {"S3_REGION": "us-east-1", **variables}) configure_staging_opensearch(rendered, variables) configure_production_opensearch(rendered, variables) qstash_base_url: str = variables.get("QSTASH_BASE_URL", "") @@ -280,6 +280,7 @@ def load_variables() -> dict[str, str]: # Preserve the SDK default when no override is supplied, while production # explicitly selects the region that owns its existing QStash token. variables["QSTASH_BASE_URL"] = os.environ.get("QSTASH_BASE_URL", "") + variables["S3_REGION"] = os.environ.get("S3_REGION", "us-east-1") return variables diff --git a/deploy/ecs/task-definition-api.staging.json b/deploy/ecs/task-definition-api.staging.json index a2f129950..3cc8bce75 100644 --- a/deploy/ecs/task-definition-api.staging.json +++ b/deploy/ecs/task-definition-api.staging.json @@ -37,7 +37,7 @@ {"name": "S3_BUCKET_NAME", "value": "${S3_BUCKET_NAME}"}, {"name": "S3_RESULTS_BUCKET", "value": "${S3_BUCKET_NAME}"}, {"name": "S3_TEMP_PATH", "value": "/tmp"}, - {"name": "S3_REGION", "value": "us-east-1"}, + {"name": "S3_REGION", "value": "${S3_REGION}"}, {"name": "S3_USE_SSL", "value": "true"}, {"name": "S3_ADDRESSING_STYLE", "value": "virtual"}, {"name": "SUPPORTED_EXTENSIONS", "value": ".doc,.docx,.pdf,.txt,.xls,.xlsx,.csv,.tsv,.pptx,.jpg,.jpeg,.png,.gif,.webp,.bmp,.tif,.tiff,.heic,.heif,.md,.html,.htm,.mp3,.wav,.m4a,.aac,.flac,.ogg,.opus,.mp4,.mov,.webm,.mkv"}, diff --git a/deploy/ecs/task-definition-worker.staging.json b/deploy/ecs/task-definition-worker.staging.json index 3073791d4..f0a647615 100644 --- a/deploy/ecs/task-definition-worker.staging.json +++ b/deploy/ecs/task-definition-worker.staging.json @@ -32,7 +32,7 @@ {"name": "S3_BUCKET_NAME", "value": "${S3_BUCKET_NAME}"}, {"name": "S3_RESULTS_BUCKET", "value": "${S3_BUCKET_NAME}"}, {"name": "S3_TEMP_PATH", "value": "/tmp"}, - {"name": "S3_REGION", "value": "us-east-1"}, + {"name": "S3_REGION", "value": "${S3_REGION}"}, {"name": "S3_USE_SSL", "value": "true"}, {"name": "S3_ADDRESSING_STYLE", "value": "virtual"}, {"name": "SUPPORTED_EXTENSIONS", "value": ".doc,.docx,.pdf,.txt,.xls,.xlsx,.csv,.tsv,.pptx,.jpg,.jpeg,.png,.gif,.webp,.bmp,.tif,.tiff,.heic,.heif,.md,.html,.htm,.mp3,.wav,.m4a,.aac,.flac,.ogg,.opus,.mp4,.mov,.webm,.mkv"}, diff --git a/deploy/ecs/test_render_task_definitions.py b/deploy/ecs/test_render_task_definitions.py index 987fb0ad0..c1e304c41 100644 --- a/deploy/ecs/test_render_task_definitions.py +++ b/deploy/ecs/test_render_task_definitions.py @@ -50,6 +50,40 @@ "TMP_PATH": "/tmp/aismart_bid", } +@pytest.mark.parametrize( + "template_name", + ("task-definition-api.staging.json", "task-definition-worker.staging.json"), +) +def test_production_storage_can_use_a_different_region( + tmp_path: Path, template_name: str +) -> None: + output_path = tmp_path / "production.json" + bucket = "knowhere-test-singapore" + topic = "arn:aws:sns:ap-southeast-1:107424103509:knowhere-test" + render_template( + TEMPLATE_DIRECTORY / template_name, + output_path, + { + **RENDER_VARIABLES, + "DEPLOYMENT_ENVIRONMENT": "prod", + "RUNTIME_ENVIRONMENT": "production", + "S3_BUCKET_NAME": bucket, + "S3_REGION": "ap-southeast-1", + "SNS_TOPIC_ARN": topic, + }, + ) + definition = json.loads(output_path.read_text(encoding="utf-8")) + environment = { + entry["name"]: entry["value"] + for entry in definition["containerDefinitions"][0]["environment"] + } + assert environment["S3_BUCKET_NAME"] == bucket + assert environment["S3_RESULTS_BUCKET"] == bucket + assert environment["S3_REGION"] == "ap-southeast-1" + assert environment["SNS_TOPIC_ARN"] == topic + assert environment["AWS_REGION"] == "us-east-1" + + API_STAGING_ENVIRONMENT: dict[str, str] = { **SHARED_STAGING_ENVIRONMENT, "DB_MAX_OVERFLOW": "5", From 7b85a354449ffa665fc51d2dc2bd9a95e6e0b621 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Sun, 29 Nov 2026 05:56:08 -0700 Subject: [PATCH 10/22] Retire the Virginia storage fallback from production releases --- .github/workflows/build-images.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-images.yml b/.github/workflows/build-images.yml index 876326b18..7e797e556 100644 --- a/.github/workflows/build-images.yml +++ b/.github/workflows/build-images.yml @@ -334,7 +334,8 @@ jobs: # The image build metadata uses the short release label `prod`, but # AppConfig validates the runtime environment as `production`. ENVIRONMENT: production - S3_BUCKET_NAME: knowhere-storage-prod + S3_BUCKET_NAME: ${{ fromJSON(vars.PROD_S3_STORAGE).bucket }} + S3_REGION: ${{ fromJSON(vars.PROD_S3_STORAGE).region }} S3_TEMP_PATH: /tmp TMP_PATH: /tmp/aismart_bid shell: bash @@ -344,6 +345,7 @@ jobs: docker run --rm \ --env DATABASE_URL \ --env S3_BUCKET_NAME \ + --env S3_REGION \ --env TMP_PATH \ --env S3_TEMP_PATH \ --env "DB_SSL_MODE=${PROD_DB_SSL_MODE}" \ @@ -826,10 +828,14 @@ jobs: - name: Resolve production S3 storage id: production_storage env: - STORAGE_CONFIGURATION: ${{ vars.PROD_S3_STORAGE || '{"bucket":"knowhere-storage-prod","region":"us-east-1","sns_topic_arn":"arn:aws:sns:us-east-1:107424103509:knowhere-prod-s3-events"}' }} + STORAGE_CONFIGURATION: ${{ vars.PROD_S3_STORAGE }} shell: bash run: | set -euo pipefail + if [[ -z "$STORAGE_CONFIGURATION" ]]; then + echo "::error::PROD_S3_STORAGE is not configured." + exit 1 + fi bucket="$(jq -er '.bucket | select(test("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$"))' <<< "$STORAGE_CONFIGURATION")" region="$(jq -er '.region | select(test("^[a-z]{2}(-[a-z]+)+-[0-9]+$"))' <<< "$STORAGE_CONFIGURATION")" topic="$(jq -er '.sns_topic_arn | select(test("^arn:aws:sns:[a-z0-9-]+:107424103509:[A-Za-z0-9_-]+$"))' <<< "$STORAGE_CONFIGURATION")" From 0e1b31b8de2c7e68eca4160a132360d560d16ab8 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Tue, 1 Dec 2026 07:43:50 -0700 Subject: [PATCH 11/22] Let the OpenSearch worker clear its delete-by-query scrolls Build cleanup runs _delete_by_query, which opens a scroll and clears it when the delete finishes. The worker role granted indices:data/read/scroll but not indices:data/read/scroll/clear, so every clear was denied and each scroll stayed open for its 5-minute keep-alive. Once the hourly maintenance sweep had opened 500 scrolls, the node rejected every later delete and the worker request timed out after 30 seconds. Grant both scroll actions at cluster and index level, as OpenSearch requires, and add a role-check test for a worker role that cannot clear scrolls. Co-Authored-By: Claude Opus 5.5 --- deploy/opensearch/README.md | 10 +++++--- deploy/opensearch/operations.py | 12 +++++++--- deploy/opensearch/tests/test_operations.py | 28 +++++++++++++++++++--- 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/deploy/opensearch/README.md b/deploy/opensearch/README.md index 32a4d787d..00dd33c57 100644 --- a/deploy/opensearch/README.md +++ b/deploy/opensearch/README.md @@ -486,9 +486,13 @@ certificate, then run It lists every rendered action that a live API or worker role does not grant and exits 1 until none are missing. Both roles write: the API publishes builds when it retries indexing and writes a manifest when it archives a document, and -the worker's build cleanup scrolls, bulk-deletes and refreshes. A missing action -shows up only as HTTP 403 on that path, for example retrieval returning 503 or -retired builds that are never collected. +the worker's build cleanup scrolls, bulk-deletes, refreshes and clears its +scroll. A missing action shows up only as HTTP 403 on that path, for example +retrieval returning 503 or retired builds that are never collected. A missing +`indices:data/read/scroll/clear` is quieter: OpenSearch logs the denial and +keeps each cleanup's scroll open for its 5-minute keep-alive. Once 500 scrolls +are open on the node (`search.max_open_scroll_context`), every later delete is +rejected and the worker request times out. Each environment caps its open namespace indexes with `KNOWHERE_OPENSEARCH_OPEN_INDEX_LIMIT` and closes idle ones from diff --git a/deploy/opensearch/operations.py b/deploy/opensearch/operations.py index bfa5f4d63..2a7f69537 100644 --- a/deploy/opensearch/operations.py +++ b/deploy/opensearch/operations.py @@ -338,8 +338,14 @@ def _renderApplicationRoles(indexPrefix: str) -> dict[str, dict[str, list]]: "indices:admin/create", "indices:admin/open", "indices:admin/close*", "indices:data/write/bulk*", "indices:data/write/index", "indices:data/read/count", ] - # Build cleanup runs _delete_by_query?refresh=true, which scrolls, bulk-deletes and then refreshes. - cleanup: list[str] = ["indices:data/write/delete/byquery", "indices:data/write/delete", "indices:admin/refresh"] + # Build cleanup runs _delete_by_query?refresh=true, which scrolls, bulk-deletes, refreshes and + # then clears its scroll. Scroll actions must be granted at both cluster and index level. A + # denied clear leaves each scroll open for its 5-minute keep-alive, and the node's 500 open + # scroll limit then rejects later deletes. + scroll: list[str] = ["indices:data/read/scroll", "indices:data/read/scroll/clear"] + cleanup: list[str] = [ + "indices:data/write/delete/byquery", "indices:data/write/delete", "indices:admin/refresh", *scroll, + ] # Namespace indexes use a 48-character fingerprint. Keep their actions off the manifest index. namespacePattern: str = f"/{indexPrefix}-[a-f0-9]{{48}}/" manifestIndex: str = f"{indexPrefix}-published-manifests" @@ -353,7 +359,7 @@ def _renderApplicationRoles(indexPrefix: str) -> dict[str, dict[str, list]]: {"index_patterns": [manifestIndex], "allowed_actions": manifestActions}, {"index_patterns": [deploymentProbe], "allowed_actions": [_SEARCH]}, ]}, - "knowhere_worker": {"cluster_permissions": [*applicationCluster, "indices:data/read/scroll"], "index_permissions": [ + "knowhere_worker": {"cluster_permissions": [*applicationCluster, *scroll], "index_permissions": [ {"index_patterns": [namespacePattern], "allowed_actions": [*_INDEX_READ, *publication, *cleanup]}, {"index_patterns": [manifestIndex], "allowed_actions": [*manifestActions, "indices:data/write/delete"]}, {"index_patterns": [deploymentProbe], "allowed_actions": [_SEARCH]}, diff --git a/deploy/opensearch/tests/test_operations.py b/deploy/opensearch/tests/test_operations.py index 6bf9a4d97..884e16717 100644 --- a/deploy/opensearch/tests/test_operations.py +++ b/deploy/opensearch/tests/test_operations.py @@ -142,11 +142,12 @@ def test_preserves_namespace_publication_and_deployment_probe_search(roleName: s "cluster:monitor/main", "cluster:monitor/state", "cluster:monitor/health", "indices:data/write/bulk", } if roleName == "knowhere_worker": - # Build cleanup is _delete_by_query?refresh=true: scroll, bulk delete, then refresh. + # Build cleanup is _delete_by_query?refresh=true: scroll, bulk delete, refresh, then clear the scroll. expectedNamespaceActions |= { "indices:data/write/delete/byquery", "indices:data/write/delete", "indices:admin/refresh", + "indices:data/read/scroll", "indices:data/read/scroll/clear", } - expectedClusterActions.add("indices:data/read/scroll") + expectedClusterActions |= {"indices:data/read/scroll", "indices:data/read/scroll/clear"} assert getIndexActions(role, f"{prefix}-{namespaceSuffix}") == expectedNamespaceActions assert getIndexActions(role, f"{prefix}-deployment-probe") == {"indices:data/read/search*"} @@ -192,6 +193,25 @@ def test_application_role_check_detects_missing_close_shard_action(roleName: str ] +def test_application_role_check_detects_worker_unable_to_clear_scrolls() -> None: + # Without this action every build cleanup leaks its scroll until the node's open scroll limit rejects deletes. + operations: type = loadOperations() + prefix: str = "knowhere-staging-lexical-v1" + bundle: dict[str, object] = operations.renderBundle({**createManifest(), "index_prefix": prefix}) + roles: dict[str, _Role] = cast(dict[str, _Role], bundle["roles.yml"]) + worker: _Role = roles["knowhere_worker"] + worker["cluster_permissions"] = [ + action for action in worker["cluster_permissions"] if action != "indices:data/read/scroll/clear" + ] + + result: dict[str, object] = operations.checkApplicationRoles(roles, indexPrefix=prefix, rolePrefix="knowhere_") + + assert result["passed"] is False + assert cast(dict[str, list[str]], result["missing"])["knowhere_worker"] == [ + "cluster indices:data/read/scroll/clear", + ] + + def test_application_role_check_reports_the_read_only_production_api_role() -> None: operations: type = loadOperations() prefix: str = "knowhere-prod-lexical-v1" @@ -224,7 +244,9 @@ def test_application_role_check_reports_the_read_only_production_api_role() -> N f"{manifest} indices:data/write/index", ], "knowhere_prod_worker": [ - f"{namespace} indices:admin/close*", f"{manifest} indices:data/read/get", + "cluster indices:data/read/scroll/clear", + f"{namespace} indices:admin/close*", f"{namespace} indices:data/read/scroll", + f"{namespace} indices:data/read/scroll/clear", f"{manifest} indices:data/read/get", ], } From 0c6d4f77f0e1da0ed8269d49698320cfc81274d6 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Tue, 1 Dec 2026 07:44:39 -0700 Subject: [PATCH 12/22] Stop deploy/opensearch/operator.py shadowing the stdlib operator module Scripts in deploy/opensearch run with that folder first on sys.path, so Python's own `import operator` (from collections, at startup) loaded the repository's operator.py and failed with a circular-import ImportError. It stayed hidden only because the shared package's editable-install .pth happens to import collections before the script folder is added. Rename the module to native_operator.py, the name workload_snapshot.py already loads it under, and update every reference. The launch-issuer kind stays `operator`, so installed backup services keep their command. Co-Authored-By: Claude Opus 5.5 --- deploy/opensearch/README.md | 12 ++++++------ deploy/opensearch/launch-issuer.py | 2 +- deploy/opensearch/manage.py | 2 +- .../opensearch/{operator.py => native_operator.py} | 0 deploy/opensearch/tests/test_execution.py | 6 +++--- deploy/opensearch/workload_snapshot.py | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) rename deploy/opensearch/{operator.py => native_operator.py} (100%) diff --git a/deploy/opensearch/README.md b/deploy/opensearch/README.md index 32a4d787d..2ae065b6e 100644 --- a/deploy/opensearch/README.md +++ b/deploy/opensearch/README.md @@ -357,24 +357,24 @@ does not prove that a native issuer stopped. recovery observes the old instance stopped before non-forced detach, waits for attach on the approved target, verifies filesystem and mount identity, and starts the pinned service. It never formats or provisions. -- Unresolved prior physical issuer: execute `operator.py fence-host` in its own +- Unresolved prior physical issuer: execute `native_operator.py fence-host` in its own physical unit. The plan binds the exact actual `old_issuer_receipt_path` and raw `old_issuer_receipt_sha256`, plus the old issuer identity fields. The source gate reserves one durable fencing intent before the SSM sends. It retains the actual command IDs and confirms the exact operator control group and native unit are stopped. If an acknowledgment is lost, - `operator.py reconcile-fence --fence-token ORIGINAL_UUID` observes existing + `native_operator.py reconcile-fence --fence-token ORIGINAL_UUID` observes existing tagged commands only; it never reissues them. Takeover requires the proven receipt and exact old-token CAS. No TTL frees unknown authority. - An interrupted first shadow pilot while PostgreSQL is serving can use - `operator.py release-empty-shadow` with the same old-issuer plan. The command + `native_operator.py release-empty-shadow` with the same old-issuer plan. The command observes the collected transient unit through SSM and checks the exact native identity, namespace inventory, and primary shard history. It records the release only before any migration attempt or native write. The shared native service stays online. Run the selected inputs through the read-only preflight under the pilot's temporary database role before retrying. - A shadow backfill that stopped after native writes while PostgreSQL is - serving can use `operator.py release-stopped-shadow` with the same + serving can use `native_operator.py release-stopped-shadow` with the same old-issuer plan. It observes the collected transient unit through SSM like `release-empty-shadow`, then releases only when no migration attempt is pending or running, no migration build is writing, no lease is unreleased, @@ -387,7 +387,7 @@ does not prove that a native issuer stopped. attempt, writing build or uncertain lease, and the command refuses; use `fence-host` then. Check each condition with read-only SQL before running it. - After a successful host restart, execute the source-owned - `operator.py reconcile-restart` against the same recovery operation UUID in + `native_operator.py reconcile-restart` against the same recovery operation UUID in a new physical invocation. The plan binds `inventory_path`, `inventory_sha256`, `host_recovery_receipt_path`, `transition_script_sha256`, `target_backend` and `maximum_step_seconds`. The restart inventory v1 contains @@ -515,7 +515,7 @@ of about 100 units each: limit keeps more namespaces warm and makes such bursts rarer. Use `launch-issuer.py --kind operator` with the `release` child command shown -by `operator.py --help`. Review separate plans for `phase:"prepare"`, +by `native_operator.py --help`. Review separate plans for `phase:"prepare"`, `"forward"` and `"rollback"`. Each plan binds `account_id`, exact source hash, transition script SHA, existing gate rule ARN, conditions SHA, original forward actions and a known fixed 503 response. The tool checks the actual route diff --git a/deploy/opensearch/launch-issuer.py b/deploy/opensearch/launch-issuer.py index 6959dc91b..ed1567ff9 100644 --- a/deploy/opensearch/launch-issuer.py +++ b/deploy/opensearch/launch-issuer.py @@ -12,7 +12,7 @@ _ROOT: Path = Path(__file__).resolve().parents[2] -_PROGRAMS: dict[str, Path] = {"operator": _ROOT / "deploy/opensearch/operator.py", +_PROGRAMS: dict[str, Path] = {"operator": _ROOT / "deploy/opensearch/native_operator.py", "recovery": _ROOT / "deploy/opensearch/recovery.py", "release-step": _ROOT / "deploy/opensearch/release.py", "workload": _ROOT / "scripts/probes/run-opensearch-workload.py"} diff --git a/deploy/opensearch/manage.py b/deploy/opensearch/manage.py index 980adf675..70ffc7fc5 100644 --- a/deploy/opensearch/manage.py +++ b/deploy/opensearch/manage.py @@ -348,7 +348,7 @@ def _main() -> int: result = OpenSearchOperations.planCost(_readJson(arguments.quote), _readJson(arguments.usage)) elif command == "backup-cycle": if arguments.execute: - raise ValueError("Run the authoritative operator.py backup command to snapshot and qualify data") + raise ValueError("Run the authoritative native_operator.py backup command to snapshot and qualify data") inventory: object = _readJson(arguments.inventory) boundaryDigest: str = sha256(arguments.boundary.read_bytes()).hexdigest() result = {"mode": "dry-run", "data_verified": False, "retention_authorized": False, diff --git a/deploy/opensearch/operator.py b/deploy/opensearch/native_operator.py similarity index 100% rename from deploy/opensearch/operator.py rename to deploy/opensearch/native_operator.py diff --git a/deploy/opensearch/tests/test_execution.py b/deploy/opensearch/tests/test_execution.py index b8ad246c0..c67edd7bf 100644 --- a/deploy/opensearch/tests/test_execution.py +++ b/deploy/opensearch/tests/test_execution.py @@ -92,10 +92,10 @@ def test_manifest_seed_is_an_explicit_fenced_operator_command(tmp_path: Path) -> assert launch.returncode == 0, launch.stderr launchPlan = json.loads(launch.stdout) assert launchPlan["resource_mutations_issued"] is False - assert launchPlan["command"][-len(arguments) - 4:] == [str(directory / "operator.py"), *arguments, + assert launchPlan["command"][-len(arguments) - 4:] == [str(directory / "native_operator.py"), *arguments, "--issuer-token", launchPlan["invocation_token"], "--execute"] - result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, str(directory / "operator.py"), *arguments], + result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, str(directory / "native_operator.py"), *arguments], capture_output=True, text=True, check=False) assert result.returncode == 0, result.stderr assert json.loads(result.stdout)["operation"] == "seed-manifests" @@ -106,7 +106,7 @@ def test_manifest_seed_is_an_explicit_fenced_operator_command(tmp_path: Path) -> def test_manifest_seed_requires_receipt_from_the_admitted_epoch( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, receiptEpoch: int, ) -> None: - path: Path = Path(__file__).parents[1] / "operator.py" + path: Path = Path(__file__).parents[1] / "native_operator.py" monkeypatch.syspath_prepend(str(path.parent)) specification = importlib.util.spec_from_file_location("native_operator", path) assert specification is not None and specification.loader is not None diff --git a/deploy/opensearch/workload_snapshot.py b/deploy/opensearch/workload_snapshot.py index 5f62b76a8..1bba4bbb0 100644 --- a/deploy/opensearch/workload_snapshot.py +++ b/deploy/opensearch/workload_snapshot.py @@ -49,7 +49,7 @@ def _run(configuration: dict[str, object], request: dict[str, object], *, should def persist(value: dict[str, object]) -> None: _writeJson(journal, {**value, "binding": binding}, replace=journal.exists()) - specification = importlib.util.spec_from_file_location("knowhere_native_operator", Path(__file__).with_name("operator.py")) + specification = importlib.util.spec_from_file_location("knowhere_native_operator", Path(__file__).with_name("native_operator.py")) if specification is None or specification.loader is None: raise ValueError("Authoritative backup implementation is unavailable") module = importlib.util.module_from_spec(specification) From ed3743703cbcc34d2447331103bc23035a8824eb Mon Sep 17 00:00:00 2001 From: suguanYang Date: Tue, 1 Dec 2026 09:40:03 -0700 Subject: [PATCH 13/22] Release uncertain lexical leases that can no longer cover a request An index-use lease turns uncertain when its holder loses track of an in-flight OpenSearch request, and nothing ever released it again. Until then its build stays pending cleanup, its namespace index cannot close as empty, and its revision's indexing input is retained. - Build cleanup now always releases its own lease. A delete with an unknown outcome can only remove the retired or failed build's records, and the build stays pending until a later delete verifies it is empty. - The hourly maintenance sweep first releases uncertain leases that expired more than 15 minutes ago. Writers check their lease before every batch, so after expiry at most one request is still in flight, and it ends within the 30-second request timeout. Co-Authored-By: Claude Opus 5.5 --- .../test_lexical_maintenance_contract.py | 91 +++++++++++++++++++ .../services/retrieval/lexical/cleanup.py | 8 +- .../services/retrieval/lexical/maintenance.py | 33 ++++++- 3 files changed, 123 insertions(+), 9 deletions(-) diff --git a/apps/api/tests/contract/test_lexical_maintenance_contract.py b/apps/api/tests/contract/test_lexical_maintenance_contract.py index e1eabfcb0..a42848247 100644 --- a/apps/api/tests/contract/test_lexical_maintenance_contract.py +++ b/apps/api/tests/contract/test_lexical_maintenance_contract.py @@ -599,6 +599,97 @@ def close(self) -> None: assert actions == ["open", "delete_build"] +def retireCurrentBuild(db: Session, buildId: str, *, state: str) -> str: + """Make the fixture build a non-current cleanup candidate and return its namespace index id.""" + from shared.models.database.document import Document + from shared.models.database.lexicalbuild import LexicalBuild + + build: LexicalBuild = requireRow(db, LexicalBuild, buildId) + document: Document = requireRow(db, Document, build.documentId) + document.current_indexing_build_id = None + build.state = state + build.cleanupState = "pending" + build.legacyCopyState = "completed" + return build.namespaceIndexId + + +def test_cleanup_releases_its_lease_when_delete_outcome_is_unknown(monkeypatch: pytest.MonkeyPatch, publishedInput: tuple[Engine, str, str, str]) -> None: + from shared.models.database.lexicalbuild import LexicalBuild + from shared.models.database.lexicallease import LexicalLease + from shared.services.retrieval.lexical import cleanup + from shared.services.retrieval.lexical.error import LexicalIndexError + + engine, buildId, _, _ = publishedInput + with Session(engine) as db: + registryId: str = retireCurrentBuild(db, buildId, state="retired") + db.commit() + class Native: + def __init__(self, **arguments: object) -> None: + pass + def getClusterUuid(self) -> None: + return None + def getIndexUuid(self) -> str: + return "test-index" + def deleteBuild(self, identity: str) -> bool: + raise LexicalIndexError("Native lexical transport failed", isRetryable=True, hasUnknownOutcome=True) + def close(self) -> None: + pass + monkeypatch.setattr(cleanup, "OpenSearchLexicalIndex", Native) + + with pytest.raises(LexicalIndexError): + cleanup.LexicalCleanup(sessionFactory=sessionmaker(engine, expire_on_commit=False)).collect(buildId) + + with Session(engine) as db: + states: list[str] = list(db.scalars(select(LexicalLease.state).where(LexicalLease.namespaceIndexId == registryId))) + assert states == ["released"] + assert requireRow(db, LexicalBuild, buildId).cleanupState == "pending" + + +def test_sweep_releases_settled_uncertain_writer_lease_and_completes_its_build(monkeypatch: pytest.MonkeyPatch, publishedInput: tuple[Engine, str, str, str]) -> None: + from datetime import timedelta + from shared.models.database.lexicalbuild import LexicalBuild + from shared.models.database.lexicallease import LexicalLease + from shared.services.retrieval.lexical import cleanup, maintenance + from shared.services.retrieval.lexical.coordination import LexicalCoordination + + engine, buildId, _, _ = publishedInput + with Session(engine) as db: + registryId: str = retireCurrentBuild(db, buildId, state="failed") + now = LexicalCoordination.getDatabaseTime(db) + settled: LexicalLease = LexicalLease(namespaceIndexId=registryId, kind="index_use", ownerToken=str(uuid4()), + backendEpoch=1, buildId=buildId, state="uncertain", expiresAt=now - timedelta(minutes=16)) + recent: LexicalLease = LexicalLease(namespaceIndexId=registryId, kind="index_use", ownerToken=str(uuid4()), + backendEpoch=1, state="uncertain", expiresAt=now - timedelta(minutes=1)) + db.add_all([settled, recent]) + db.commit() + settledId, recentId = settled.id, recent.id + deleted: list[str] = [] + class Native: + def __init__(self, **arguments: object) -> None: + pass + def getClusterUuid(self) -> None: + return None + def getIndexUuid(self) -> str: + return "test-index" + def deleteBuild(self, identity: str) -> bool: + deleted.append(identity) + return True + def close(self) -> None: + pass + monkeypatch.setattr(maintenance, "get_sync_session_factory", lambda: sessionmaker(engine, expire_on_commit=False)) + monkeypatch.setattr(cleanup, "OpenSearchLexicalIndex", Native) + monkeypatch.setattr(cleanup.LexicalCleanup, "closeEmptyNamespaces", lambda self: 0) + monkeypatch.setattr(maintenance, "turnOverIndexes", lambda: 0) + + maintenance.sweepLexical() + + assert deleted == [buildId] + with Session(engine) as db: + assert requireRow(db, LexicalLease, settledId).state == "released" + assert requireRow(db, LexicalLease, recentId).state == "uncertain" + assert requireRow(db, LexicalBuild, buildId).cleanupState == "completed" + + @pytest.mark.parametrize("retirement", ["archived", "superseded", "canonical_removed"]) def test_ineligible_failed_candidate_reclaims_only_working_input(publishedInput: tuple[Engine, str, str, str], retirement: str) -> None: from shared.models.database.document import Document diff --git a/packages/shared-python/shared/services/retrieval/lexical/cleanup.py b/packages/shared-python/shared/services/retrieval/lexical/cleanup.py index e86520e2f..eae455731 100644 --- a/packages/shared-python/shared/services/retrieval/lexical/cleanup.py +++ b/packages/shared-python/shared/services/retrieval/lexical/cleanup.py @@ -156,20 +156,18 @@ def collect(self, buildId: str) -> bool: native: OpenSearchLexicalIndex = OpenSearchLexicalIndex( endpoint=settings.KNOWHERE_OPENSEARCH_URL, scope=scope, indexPrefix=settings.KNOWHERE_OPENSEARCH_INDEX_PREFIX) - isKnown: bool = True isEmpty: bool = False try: if native.getClusterUuid() != self._getClusterUuid() or native.getIndexUuid() != indexUuid: raise LexicalIndexError("Cleanup encountered a changed native identity") isEmpty = native.deleteBuild(buildId) - except LexicalIndexError as error: - isKnown = not error.hasUnknownOutcome - raise finally: native.close() + # Released even when the delete outcome is unknown: a late delete only removes this retired + # or failed build's records, and the build stays pending until a later delete verifies it empty. with self.sessions.begin() as db: use = db.scalars(select(LexicalLease).where(LexicalLease.id == leaseId).with_for_update()).one() - use.state = "released" if isKnown else "uncertain" + use.state = "released" with self.sessions.begin() as db: if scope.corpusKind == "demo": authorize_demo_transaction(db, user_id=actorId) diff --git a/packages/shared-python/shared/services/retrieval/lexical/maintenance.py b/packages/shared-python/shared/services/retrieval/lexical/maintenance.py index 4f755b772..474b147c3 100644 --- a/packages/shared-python/shared/services/retrieval/lexical/maintenance.py +++ b/packages/shared-python/shared/services/retrieval/lexical/maintenance.py @@ -6,9 +6,10 @@ Each cleanup task claims its row with the same ``FOR UPDATE SKIP LOCKED`` lease as the sweep, so a task and a sweep never process one row at the same time. -``maintainLexical`` runs hourly in the shared periodic database slot. It resolves -unsettled indexes, collects whatever a lost or failed dispatch left pending, and -runs index turnover as a safety net. Between sweeps nothing here queries the database unless work was committed. +``maintainLexical`` runs hourly in the shared periodic database slot. It releases +uncertain leases that can no longer cover a request, resolves unsettled indexes, +collects whatever a lost or failed dispatch left pending, and runs index turnover +as a safety net. Between sweeps nothing here queries the database unless work was committed. Low-priority rollback-copy and retired-build work never gates completion. """ @@ -29,6 +30,7 @@ from shared.models.database.document_enrichment_publication import DocumentEnrichmentPublication from shared.models.database.lexicalbuild import LexicalBuild from shared.models.database.lexicalcontrol import LexicalBackendControl +from shared.models.database.lexicallease import LexicalLease from shared.services.redis.periodic_task_lock import periodic_task_lock from shared.services.retrieval.lexical.additivecleanup import AdditiveCleanup from shared.services.retrieval.lexical.cleanup import LexicalCleanup @@ -54,6 +56,9 @@ _RESCHEDULE_HORIZON: Final[timedelta] = timedelta(hours=1) # Bounds reschedules for work that keeps declining (late writers, closed registries). _MAXIMUM_HOPS: Final[int] = 3 +# Writers check their lease before every batch, so once an uncertain lease expires at most one native +# request is still in flight, and it ends within the 30-second request timeout. The grace is a wide margin. +_UNCERTAIN_LEASE_GRACE: Final[timedelta] = timedelta(minutes=15) _Outcome = str @@ -72,7 +77,8 @@ def sweepLexical() -> int: deadline: float = time.monotonic() + _SWEEP_BUDGET_SECONDS isNativeServing: bool = settings.KNOWHERE_LEXICAL_BACKEND == "opensearch" sessions: sessionmaker[Session] = get_sync_session_factory() - completed: int = 0 + # First, so builds whose only blocker was a settled uncertain lease complete in this sweep. + completed: int = _runSafely("Uncertain lease", lambda: _releaseSettledLeases(sessions)) while time.monotonic() < deadline: claimed: tuple[tuple[str, str, str], ...] | None = _claimPendingBuilds(sessions, isNativeServing) if claimed is None: @@ -160,6 +166,25 @@ def resolveIndex(registryId: str, hop: int = 0) -> _Outcome: return LexicalIndexResolution().resolveDispatched(registryId, hop) +def _releaseSettledLeases(sessions: sessionmaker[Session]) -> int: + """Release uncertain index-use leases once no request they covered can still reach the node. + + A lease turns uncertain when its holder lost track of an in-flight native request. Nothing else + resolves it, and until it is released its build stays pending, its namespace index cannot close + as empty and its revision's indexing input is retained. + """ + with sessions.begin() as db: + cutoff: datetime = LexicalCoordination.getDatabaseTime(db) - _UNCERTAIN_LEASE_GRACE + leases: list[LexicalLease] = list(db.scalars(select(LexicalLease).where( + LexicalLease.state == "uncertain", LexicalLease.expiresAt <= cutoff, + ).with_for_update(skip_locked=True))) + for lease in leases: + lease.state = "released" + if leases: + logger.info("Released settled uncertain lexical leases: count={}", len(leases)) + return len(leases) + + def _claimPendingBuilds(sessions: sessionmaker[Session], isNativeServing: bool) -> tuple[tuple[str, str, str], ...] | None: """Claim one batch of due builds; None when the backend is not serving.""" From b4c21ffe18783ec7058f58f8e74f511d319a5d0d Mon Sep 17 00:00:00 2001 From: suguanYang Date: Tue, 1 Dec 2026 10:48:03 -0700 Subject: [PATCH 14/22] Keep a cold numpy import out of the execution-timeout test's timer The failure transition records audit metadata through make_json_safe, which imports numpy and pandas on first use. When nothing earlier in the process had loaded them, that import (about half a second) landed inside the measured region and exceeded the 0.40-second bound. Run make_json_safe once before the timer starts so the test measures cancellation only. Co-Authored-By: Claude Opus 5.5 --- apps/api/tests/contract/test_indexing_execution_contract.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/api/tests/contract/test_indexing_execution_contract.py b/apps/api/tests/contract/test_indexing_execution_contract.py index 86d3f7da3..f18896e4e 100644 --- a/apps/api/tests/contract/test_indexing_execution_contract.py +++ b/apps/api/tests/contract/test_indexing_execution_contract.py @@ -219,6 +219,10 @@ def blockedNative(self: OpenSearchLexicalIndex, *, isExact: bool, monkeypatch.setattr(settings, "KNOWHERE_INDEXING_TIMEOUT_SECONDS", executionBudget) monkeypatch.setattr(OpenSearchLexicalIndex, "getLifecycleSnapshot", blockedNative) + # The failure transition's audit metadata goes through make_json_safe, which imports numpy and + # pandas on first use. Load them here so the timed region measures cancellation, not a cold import. + from shared.utils.json_utils import make_json_safe + make_json_safe({}) startedAt: float = time.monotonic() worker: IndexingWorker = IndexingWorker(sessionFactory=sessionmaker(engine, expire_on_commit=False)) assert worker.run(jobId) == "failed" From 59736427c236dffa248194fafc27c7ca94823629 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Thu, 3 Dec 2026 05:28:17 -0700 Subject: [PATCH 15/22] Raise production indexing limit and observe parser stalls --- .../core/tasks/document_ingestion_tasks.py | 2 +- .../app/core/visibility_recovery_watchdog.py | 12 +++ .../formats/pdf/pymupdf_subprocess.py | 75 +++++++++++++--- .../test_parse_runtime_observation.py | 62 +++++++++++++ deploy/ecs/render_task_definitions.py | 4 +- deploy/ecs/test_render_task_definitions.py | 4 +- .../shared/core/config/publication.py | 2 +- .../shared/services/redis/distributed_lock.py | 54 +++++++++--- .../shared/services/worker_cpu.py | 86 +++++++++++++++++++ .../shared/services/worker_health.py | 40 +++++++++ 10 files changed, 314 insertions(+), 27 deletions(-) create mode 100644 apps/worker/tests/contract/test_parse_runtime_observation.py create mode 100644 packages/shared-python/shared/services/worker_cpu.py 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..067293962 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,9 +404,11 @@ def run_in_child_process( ) executor = _get_process_pool_executor() + caller_context = copy_context() + queued_at = time.monotonic() task_result = executor.apply( - _run_worker_in_spawned_process_safe, - (worker_fn, args, timeout), + caller_context.run, + (_run_worker_in_spawned_process_safe, worker_fn, args, timeout, queued_at), ) if task_result.error is not None: raise task_result.error 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: From 0634cc2f8d686cef9ca01f1d3666bad98cba5f13 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Thu, 3 Dec 2026 05:56:13 -0700 Subject: [PATCH 16/22] Preserve the PyMuPDF thread handoff result type --- .../document_parser/formats/pdf/pymupdf_subprocess.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) 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 067293962..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 @@ -406,10 +406,13 @@ def run_in_child_process( executor = _get_process_pool_executor() caller_context = copy_context() queued_at = time.monotonic() - task_result = executor.apply( - caller_context.run, - (_run_worker_in_spawned_process_safe, worker_fn, args, timeout, queued_at), - ) + + 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 {} From a860ce807a41bad1b3f10f8ff84837d6a76213b7 Mon Sep 17 00:00:00 2001 From: chengke <404835780@qq.com> Date: Thu, 3 Dec 2026 23:37:55 -0800 Subject: [PATCH 17/22] Screen page images only for slides and text-less PDFs Text PDFs already find TOC candidates by keywords in the page text. The image screen on them only added TOC nodes for unnumbered section lists and cost about 40% of the coarse model calls (Sydney: 139 -> 79 calls, 207s -> 117s, same 105 section nodes). Slide decks and PDFs without a text layer (scanned, or no page text after the text scan) keep the screen, since keywords cannot find their TOCs (TAOCP still finds pages 14-15). The native-text test is shared with the stop_after_native_baseline check. Co-Authored-By: Claude Opus 5.5 --- .../services/document_agent/coordinator.py | 26 +++++---- .../test_doc_profile_anatomy_contract.py | 55 ++++++++++++++++++- .../contract/test_slide_structure_contract.py | 2 +- .../design/pdf-toc-structural-pages-phase2.md | 7 +++ 4 files changed, 77 insertions(+), 13 deletions(-) diff --git a/apps/worker/app/services/document_agent/coordinator.py b/apps/worker/app/services/document_agent/coordinator.py index 6ee3b06bb..5ff649ac7 100644 --- a/apps/worker/app/services/document_agent/coordinator.py +++ b/apps/worker/app/services/document_agent/coordinator.py @@ -92,14 +92,7 @@ def _run_coarse(self) -> DocumentProfile: page_count=self.blackboard.page_count, ): self._run_text_scan() - if ( - self.ctx.settings.get("stop_after_native_baseline") - and not profile.is_scanned - and any( - page_content(bands).strip() - for bands in self.blackboard.page_full_text_cache.values() - ) - ): + if self.ctx.settings.get("stop_after_native_baseline") and self._has_native_text(): # Progressive native pages already have their complete band text. # Asset flags remain unknown until the background structure stage. return profile @@ -231,7 +224,10 @@ def _ensure_toc_profile(self) -> None: if self.blackboard.toc_result is not None: return - self._run_page_screen() + if self._is_slide_deck() or not self._has_native_text(): + # Text PDFs find TOC candidates by keywords in the page text; the + # image screen serves slides and PDFs without a text layer. + self._run_page_screen() try: if self._is_slide_deck(): self._run_slide_structure_route() @@ -292,8 +288,18 @@ def _is_slide_deck(self) -> bool: routing = getattr(self.blackboard.document_profile, "routing_category", None) return PdfRoutingCategory.normalize(routing) is PdfRoutingCategory.SLIDES + def _has_native_text(self) -> bool: + """Whether the text scan found a native text layer on any page.""" + profile = self.blackboard.document_profile + if profile is None or profile.is_scanned: + return False + return any( + page_content(bands).strip() + for bands in self.blackboard.page_full_text_cache.values() + ) + def _run_page_screen(self) -> None: - """Screen every page image for structural pages before either route.""" + """Screen page images for structural pages (slides, text-less PDFs).""" result = run_page_screen(self.ctx) self.trace.record_step( round_index=self.round_index, diff --git a/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py b/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py index 29127fbb7..b3d1ce13e 100644 --- a/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py +++ b/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py @@ -5,6 +5,8 @@ from pathlib import Path from types import SimpleNamespace +import pytest + os.environ.setdefault("DATABASE_URL", "postgresql+asyncpg://test:test@localhost/test") os.environ.setdefault("TMP_PATH", "/tmp/knowhere-test") os.environ.setdefault("S3_BUCKET_NAME", "test-uploads") @@ -233,7 +235,6 @@ def fake_page_screen(_ctx) -> ToolResult: "text_scan", "probe.page_assets", "aggregate.doc_stats", - "page_screen", "toc", ] assert coordinator.blackboard.global_signals["assets_probed"] is True @@ -453,10 +454,60 @@ def fake_classify(_self): coordinator.run_coarse() anatomy = coordinator.run_anatomy() - assert calls == ["coarse_profile", "text_scan", "page_screen", "toc", "persist"] + assert calls == ["coarse_profile", "text_scan", "toc", "persist"] assert anatomy.toc_result.toc_pages == [17] +@pytest.mark.parametrize( + ("is_scanned", "routing", "page_text", "screened"), + [ + (False, PdfRoutingCategory.GENERIC, "Contents", False), + (False, PdfRoutingCategory.GENERIC, " ", True), + (True, PdfRoutingCategory.GENERIC, "Contents", True), + (False, PdfRoutingCategory.SLIDES, "Agenda", True), + ], +) +def test_page_screen_runs_for_slides_and_pdfs_without_text( + monkeypatch, + tmp_path: Path, + is_scanned: bool, + routing: PdfRoutingCategory, + page_text: str, + screened: bool, +) -> None: + coordinator = ProfileCoordinator( + pdf_path=str(tmp_path / "doc.pdf"), + job_id="job-page-screen-gate", + output_dir=str(tmp_path / "profile"), + ) + coordinator.blackboard.page_count = 1 + coordinator.blackboard.page_features = [_page_feature()] + coordinator.blackboard.page_full_text_cache = {1: page_text} + coordinator.blackboard.document_profile = DocumentProfile( + is_scanned=is_scanned, + category=["OTHER"], + category_label="Report", + routing_category=routing.value, + ) + calls: list[str] = [] + + def fake_page_screen(_ctx) -> ToolResult: + calls.append("page_screen") + return ToolResult(status="ok") + + def fake_route() -> None: + calls.append("route") + coordinator.blackboard.toc_result = TocResult(method="none") + + monkeypatch.setattr(coordinator_module, "run_page_screen", fake_page_screen) + monkeypatch.setattr(coordinator, "_run_toc_extraction_pipeline", fake_route) + monkeypatch.setattr(coordinator, "_run_slide_structure_route", fake_route) + + coordinator._ensure_toc_profile() + + assert calls == (["page_screen", "route"] if screened else ["route"]) + + def test_run_text_scan_native_uses_read_page_text_bands( monkeypatch, tmp_path: Path, diff --git a/apps/worker/tests/contract/test_slide_structure_contract.py b/apps/worker/tests/contract/test_slide_structure_contract.py index a3a13546e..92a1aff41 100644 --- a/apps/worker/tests/contract/test_slide_structure_contract.py +++ b/apps/worker/tests/contract/test_slide_structure_contract.py @@ -371,5 +371,5 @@ def test_coordinator_routes_slide_decks_to_slide_structure( coordinator._ensure_toc_profile() # noqa: SLF001 - # Every format is screened before its route. + # No page has a text layer here, so every route is screened first. assert called == ["screen", expected_route] diff --git a/docs/design/pdf-toc-structural-pages-phase2.md b/docs/design/pdf-toc-structural-pages-phase2.md index e33d92693..1012960dd 100644 --- a/docs/design/pdf-toc-structural-pages-phase2.md +++ b/docs/design/pdf-toc-structural-pages-phase2.md @@ -3,6 +3,13 @@ Status: proposal (2026-11-18). Scope: PDF TOC route only. The PPT route and the page screen are unchanged. +Update (2026-12-03): the page screen now runs only for slide decks and PDFs +without a text layer (scanned, or no page text after the text scan). Text +PDFs take TOC candidates from keyword hits alone, so on them this phase keeps +only the unnumbered TOCs that the keywords find. On Sydney the screen added +TOC nodes only (166, 202, 214, 226) and left the section nodes unchanged, +while costing about 40% of the coarse calls. + ## 1. Background and goal ### 1.1 Where this comes from From 2b8729a4594b9ca109ae7e9216e897acb270b0a5 Mon Sep 17 00:00:00 2001 From: suguanYang Date: Fri, 4 Dec 2026 00:43:22 -0700 Subject: [PATCH 18/22] 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 19/22] 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 From e9b3e63af5a8c31b9708476cad274732684edbf3 Mon Sep 17 00:00:00 2001 From: chengke <404835780@qq.com> Date: Fri, 4 Dec 2026 01:15:39 -0800 Subject: [PATCH 20/22] Give the coarse profile scanning evidence and probe images in one pass The coarse profile decides is_scanned from page screenshots, but since the asset probe moved after it the model saw no image measurements, every page labelled "normal" (defined as having native text) and every textless page as blank-like. A clean scan such as TAOCP was judged digital in 2 of 5 runs. - The text probe now records image coverage and image count, so the coarse call sees them; doc_stats adds invisible-text and image-coverage distributions (no sampling extrema). - The coarse prompt explains the evidence: a page is scanned when its screenshot shows clearly more text than its visible text layer holds and images cover most of it; a matching visible text layer means digital. Sampled page rows add invisible text, image coverage and image count and drop the text-only blank flag. - The geometry-only page kind "normal" is renamed "portrait"; persisted labels other than landscape still read as portrait. - Image placements come from one get_image_info pass instead of a get_image_rects call per image, in both probes (TAOCP asset probe 16s -> 0.15s; has_asset unchanged on all pages of four test documents). TAOCP is now judged scanned in 10 of 10 runs; Sydney, a standards document and a slide deck stay digital in 18 of 18. Co-Authored-By: Claude Opus 5.5 --- .../bootstrap/aggregate_stats.py | 9 ++- .../coarse_profile/classifier.py | 9 +-- .../document_agent/coarse_profile/prompts.py | 16 +++- .../app/services/document_agent/manifest.py | 2 +- .../tools/classify_page_kinds.py | 2 +- .../tools/probe_page_features.py | 77 +++++++++++-------- .../app/services/page_memory/page_plan.py | 2 +- .../page_memory/scope_enrichment_service.py | 2 +- .../test_doc_profile_anatomy_contract.py | 28 +++---- ...e_memory_scope_enrichment_task_contract.py | 2 +- ...profile_skeleton_anchor_wiring_contract.py | 4 +- .../tests/contract/test_toc_graft_contract.py | 2 +- .../unit/test_probe_dense_visual_assets.py | 6 +- .../tests/unit/test_probe_visible_text.py | 23 ++++++ 14 files changed, 117 insertions(+), 67 deletions(-) diff --git a/apps/worker/app/services/document_agent/bootstrap/aggregate_stats.py b/apps/worker/app/services/document_agent/bootstrap/aggregate_stats.py index da0ac9aac..15fb31121 100644 --- a/apps/worker/app/services/document_agent/bootstrap/aggregate_stats.py +++ b/apps/worker/app/services/document_agent/bootstrap/aggregate_stats.py @@ -10,15 +10,20 @@ # Coarse sampling extrema are text-only. Low text / density already proxy # chart-heavy or asset-heavy pages; table/drawing counts are not used to -# nominate extrema pages for VLM coarse classification. +# nominate extrema pages for VLM coarse classification. Invisible text and +# image coverage are reported as statistics (scanning evidence) only. PROFILE_METRICS = ( "raw_text_length", "text_density", + "invisible_text_length", + "image_coverage", ) -EXTREMA_ROLES = { +EXTREMA_ROLES: dict[str, tuple[str, ...]] = { "raw_text_length": ("min", "max"), "text_density": ("min", "max"), + "invisible_text_length": (), + "image_coverage": (), } EXTREMA_LABELS = { diff --git a/apps/worker/app/services/document_agent/coarse_profile/classifier.py b/apps/worker/app/services/document_agent/coarse_profile/classifier.py index 90486709a..9b548fab9 100644 --- a/apps/worker/app/services/document_agent/coarse_profile/classifier.py +++ b/apps/worker/app/services/document_agent/coarse_profile/classifier.py @@ -25,10 +25,7 @@ from app.services.document_parser.profiling.taxonomy import PdfRoutingCategory PAGE_KIND_DEFINITIONS = { - "normal": ( - "Page with enough extractable native text and no dominant table/image " - "structure." - ), + "portrait": "Portrait-oriented page (height at least width).", "landscape": "Landscape-oriented page, often wide tables, drawings, slides, or diagrams.", } @@ -48,11 +45,13 @@ def _feature_rows(ctx: ToolContext, pages: list[int]) -> list[dict[str, Any]]: "page": feature.page, "kind": label.kind if label else None, "raw_text_length": feature.raw_text_length, + "invisible_text_length": feature.invisible_text_length, "text_density": feature.text_density, + "image_coverage": feature.image_coverage, + "image_count": feature.image_count, "orientation": feature.orientation, "width": feature.width, "height": feature.height, - "is_blank_like": feature.is_blank_like, } ) return selected diff --git a/apps/worker/app/services/document_agent/coarse_profile/prompts.py b/apps/worker/app/services/document_agent/coarse_profile/prompts.py index 1e6c47a6c..8e5a5b165 100644 --- a/apps/worker/app/services/document_agent/coarse_profile/prompts.py +++ b/apps/worker/app/services/document_agent/coarse_profile/prompts.py @@ -12,8 +12,20 @@ "the document is about; section titles without a number are not selectable. " "Pick the Other entry alone, and only when no listed topic fits. " "category_label is a concise semantic document type in at most 5 English words. " - "is_scanned is true when the pages are scanned or photographed images " - "rather than digitally produced pages, whatever kind of document it is. " + "is_scanned is true when the pages are images of paper pages (scanned or " + "photographed) rather than digitally produced pages, whatever kind of " + "document it is. Decide it from the screenshots and the page measurements " + "together; a clean scan can look like a digital page. raw_text_length counts " + "the visible characters in the PDF text layer, invisible_text_length the " + "characters drawn invisibly (as an OCR layer over a scan usually is), and " + "image_coverage is the share of the page area covered by embedded images; " + "doc_stats gives their distribution over all pages. A page is scanned when " + "its screenshot shows clearly more text than its visible text layer holds " + "and embedded images cover most of the page. A page whose visible text layer " + "holds the text its screenshot shows is digitally produced, even if it also " + "carries large images. Pages that show little text, such as covers, photos " + "or blank pages, tell little either way. Set is_scanned from the pages that " + "show text: true when most of them are scanned. " "routing_category is the page format, independent of is_scanned, and must " "be one of atlas, slides, generic: " "atlas when pages are primarily drawing/detail sheets rather than prose; " diff --git a/apps/worker/app/services/document_agent/manifest.py b/apps/worker/app/services/document_agent/manifest.py index 61594e7e3..f0268c093 100644 --- a/apps/worker/app/services/document_agent/manifest.py +++ b/apps/worker/app/services/document_agent/manifest.py @@ -7,7 +7,7 @@ from typing import Any, Literal -PageKind = Literal["normal", "landscape"] +PageKind = Literal["portrait", "landscape"] TocFailureKind = Literal["none", "confirm_failed", "rejected_all", "degraded"] diff --git a/apps/worker/app/services/document_agent/tools/classify_page_kinds.py b/apps/worker/app/services/document_agent/tools/classify_page_kinds.py index 421fd6c3b..5499f4660 100644 --- a/apps/worker/app/services/document_agent/tools/classify_page_kinds.py +++ b/apps/worker/app/services/document_agent/tools/classify_page_kinds.py @@ -24,7 +24,7 @@ def _label_feature(feature: PageFeature) -> PageLabel: ) return PageLabel( page=page, - kind="normal", + kind="portrait", evidence={"source": "geometry", "rule": "width_le_height"}, ) 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 604c95f41..f6dba8072 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 @@ -1,4 +1,4 @@ -"""Full-page structural probing: text pass, then optional asset pass. +"""Full-page structural probing: text and image-coverage pass, then asset pass. Text metrics count **visible** extractable characters only. PDF text drawn with rendering mode ``3 Tr`` (MuPDF texttrace ``type == 3``) is recorded separately as @@ -266,6 +266,37 @@ def _is_dense_visual_page(*, image_count: int, drawings_count: int) -> bool: return image_count > _DENSE_IMAGE_LIMIT or drawings_count > _DENSE_DRAWING_LIMIT +def _image_boxes(page: Any) -> list[list[float]]: + """Distinct on-page image placements, clipped to the page, from one content pass. + + Uses ``get_image_info`` rather than per-image ``get_image_rects``: the + latter re-reads the page content once per image and dominates the probe + on documents with hundreds of full-page scans. + """ + boxes: list[list[float]] = [] + seen: set[tuple[float, float, float, float]] = set() + for info in page.get_image_info() or []: + x0, y0, x1, y1 = (float(value) for value in info["bbox"]) + box = _clip_bbox(x0, y0, x1, y1, clip=page.rect) + if not _valid_bbox(box): + continue + key = (box[0], box[1], box[2], box[3]) + if key in seen: + continue + seen.add(key) + boxes.append(box) + return boxes + + +def _image_coverage(boxes: list[list[float]], page_area: float) -> float: + """Share of the page area covered by the given image boxes.""" + image_area = sum( + max(box[2] - box[0], 0.0) * max(box[3] - box[1], 0.0) for box in boxes + ) + coverage = min(image_area / page_area, 1.0) if page_area > 0 else 0.0 + return round(coverage, 4) + + def _probe_visual_assets( page: Any, page_area: float, @@ -274,35 +305,12 @@ def _probe_visual_assets( footer_y: float | None, ) -> dict[str, Any]: """Collect counts + has_asset gate from images / tables / drawings.""" - image_area = 0.0 - bboxes: list[dict[str, Any]] = [] - seen_image_rects: set[tuple[float, float, float, float]] = set() page_rect = page.rect - - images = page.get_images(full=True) or [] - image_count = len(images) - for image in images: - xref = image[0] - try: - rects = page.get_image_rects(xref) or [] - except Exception: - rects = [] - for rect in rects: - box = _clip_bbox( - float(getattr(rect, "x0", 0.0) or 0.0), - float(getattr(rect, "y0", 0.0) or 0.0), - float(getattr(rect, "x1", 0.0) or 0.0), - float(getattr(rect, "y1", 0.0) or 0.0), - clip=page_rect, - ) - if not _valid_bbox(box): - continue - key = (box[0], box[1], box[2], box[3]) - if key in seen_image_rects: - continue - seen_image_rects.add(key) - image_area += max(box[2] - box[0], 0.0) * max(box[3] - box[1], 0.0) - bboxes.append({"kind": "image", "bbox": box}) + image_count = len(page.get_images(full=True) or []) + image_boxes = _image_boxes(page) + bboxes: list[dict[str, Any]] = [ + {"kind": "image", "bbox": box} for box in image_boxes + ] try: drawings = page.get_drawings() or [] @@ -349,9 +357,8 @@ def _probe_visual_assets( ) ) - coverage = min(image_area / page_area, 1.0) if page_area > 0 else 0.0 return { - "image_coverage": round(coverage, 4), + "image_coverage": _image_coverage(image_boxes, page_area), "image_count": image_count, "table_count": table_count, "drawings_count": drawings_count, @@ -370,6 +377,8 @@ def _probe_text_one(page: Any, page_number: int) -> dict[str, Any]: "raw_text_length": raw_text_length, "invisible_text_length": invisible_text_length, "text_density": round(raw_text_length / area * 10000, 4), + "image_coverage": _image_coverage(_image_boxes(page), area), + "image_count": len(page.get_images(full=True) or []), "orientation": orientation, "width": round(float(rect.width), 2), "height": round(float(rect.height), 2), @@ -426,7 +435,7 @@ def _probe_assets_worker( def probe_page_features(ctx: ToolContext, _args: dict[str, Any]) -> ToolResult: - """Text-only page probe used before coarse VLM classification.""" + """Text and image-coverage page probe used before coarse VLM classification.""" start = time.monotonic() try: result = run_in_child_process(_probe_text_worker, ctx.pdf_path, timeout=300) @@ -435,8 +444,8 @@ def probe_page_features(ctx: ToolContext, _args: dict[str, Any]) -> ToolResult: page=int(item["page"]), raw_text_length=int(item.get("raw_text_length") or 0), text_density=float(item.get("text_density") or 0.0), - image_coverage=None, - image_count=None, + image_coverage=float(item.get("image_coverage") or 0.0), + image_count=int(item.get("image_count") or 0), table_count=None, drawings_count=None, orientation=str(item.get("orientation") or "portrait"), # type: ignore[arg-type] diff --git a/apps/worker/app/services/page_memory/page_plan.py b/apps/worker/app/services/page_memory/page_plan.py index 234e28075..511503bc9 100644 --- a/apps/worker/app/services/page_memory/page_plan.py +++ b/apps/worker/app/services/page_memory/page_plan.py @@ -63,7 +63,7 @@ def _classify_page( feature: PageFeature | None, ) -> tuple[PageProcessingStrategy, str]: """Determine the strategy for a single page.""" - kind = label.kind if label else "normal" + kind = label.kind if label else "portrait" is_blank = feature.is_blank_like if feature else False if is_blank: diff --git a/apps/worker/app/services/page_memory/scope_enrichment_service.py b/apps/worker/app/services/page_memory/scope_enrichment_service.py index 41e1c6654..b4b0601c6 100644 --- a/apps/worker/app/services/page_memory/scope_enrichment_service.py +++ b/apps/worker/app/services/page_memory/scope_enrichment_service.py @@ -1250,7 +1250,7 @@ def _parse_features_and_labels( labels.append( PageLabel( page=int(item.get("page") or 0), - kind="landscape" if kind == "landscape" else "normal", + kind="landscape" if kind == "landscape" else "portrait", evidence=dict(item.get("evidence") or {}), ) ) diff --git a/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py b/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py index b3d1ce13e..d0317ba13 100644 --- a/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py +++ b/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py @@ -67,11 +67,11 @@ def _seed_preprobed_pages( coordinator.blackboard.page_count = page_count coordinator.blackboard.page_features = [_page_feature(page) for page in probed_pages] coordinator.blackboard.page_labels = [ - PageLabel(page=page, kind="normal") for page in probed_pages + PageLabel(page=page, kind="portrait") for page in probed_pages ] coordinator.blackboard.doc_stats = {"page_count": page_count} coordinator.blackboard.global_signals["page_kind_counts"] = { - "normal": page_count + "portrait": page_count } coordinator.blackboard.global_signals["assets_probed"] = True @@ -179,11 +179,11 @@ def test_run_coarse_runs_asset_probe_after_coarse_profile(monkeypatch, tmp_path: coordinator.blackboard.page_count = 2 coordinator.blackboard.page_features = [_page_feature(1), _page_feature(2)] coordinator.blackboard.page_labels = [ - PageLabel(page=1, kind="normal"), - PageLabel(page=2, kind="normal"), + PageLabel(page=1, kind="portrait"), + PageLabel(page=2, kind="portrait"), ] coordinator.blackboard.doc_stats = {"page_count": 2} - coordinator.blackboard.global_signals["page_kind_counts"] = {"normal": 2} + coordinator.blackboard.global_signals["page_kind_counts"] = {"portrait": 2} calls: list[str] = [] @@ -257,8 +257,8 @@ def test_parse_run_recorder_doc_profile_uses_final_anatomy_toc() -> None: page_count=2, page_features=[_page_feature(1), _page_feature(2)], page_labels=[ - PageLabel(page=1, kind="normal"), - PageLabel(page=2, kind="normal"), + PageLabel(page=1, kind="portrait"), + PageLabel(page=2, kind="portrait"), ], toc_result=TocResult(toc_pages=[2], method="vlm_batch", notes="ok"), toc_hierarchies=[{"toc_range": [2, 2], "toc_tree": {}}], @@ -313,7 +313,7 @@ def rollback(self) -> None: file_path="/tmp/doc.pdf", page_count=12, page_features=[_page_feature(1)], - page_labels=[PageLabel(page=1, kind="normal")], + page_labels=[PageLabel(page=1, kind="portrait")], toc_result=TocResult(toc_pages=[2], method="vlm_batch", notes="ok"), toc_hierarchies=[{"toc_range": [2, 2], "toc_tree": {}}], global_signals={"assets_probed": True}, @@ -351,7 +351,7 @@ def test_classify_page_kinds_keeps_profile_json_serializable() -> None: }, ) serialized = json.loads(json.dumps(profile.to_dict())) - assert serialized["metrics"]["page_kind_counts"] == {"normal": 2} + assert serialized["metrics"]["page_kind_counts"] == {"portrait": 2} def test_run_anatomy_keeps_the_existing_toc_result( @@ -753,7 +753,7 @@ def test_large_atlas_runs_the_single_anatomy_path( file_path=str(tmp_path / "large-atlas.pdf"), page_count=250, page_features=[_page_feature(1)], - page_labels=[PageLabel(page=1, kind="normal")], + page_labels=[PageLabel(page=1, kind="portrait")], toc_result=TocResult( toc_pages=[4], evidence=[ @@ -837,7 +837,7 @@ def test_find_toc_anchor_pages_scanned_unions_text_and_visual( category_label="Scanned Book", routing_category="generic", ) - blackboard.page_labels = [PageLabel(page=page, kind="normal") for page in range(1, 21)] + blackboard.page_labels = [PageLabel(page=page, kind="portrait") for page in range(1, 21)] blackboard.page_full_text_cache = { 14: build_page_text_bands((LineDraft(text="CONTENTS"),)), 15: build_page_text_bands((LineDraft(text="CONTENTS"),)), @@ -885,7 +885,7 @@ def test_find_toc_anchor_pages_empty_text_and_visual_returns_no_anchors( category_label="Report", routing_category=PdfRoutingCategory.GENERIC.value, ) - blackboard.page_labels = [PageLabel(page=page, kind="normal") for page in range(1, 21)] + blackboard.page_labels = [PageLabel(page=page, kind="portrait") for page in range(1, 21)] blackboard.page_full_text_cache = {} ctx = ToolContext( pdf_path=str(tmp_path / "empty.pdf"), @@ -924,7 +924,7 @@ def test_find_toc_anchor_pages_born_digital_drops_consecutive_duplicates_and_kee category_label="Report", routing_category=PdfRoutingCategory.GENERIC.value, ) - blackboard.page_labels = [PageLabel(page=page, kind="normal") for page in range(1, 21)] + blackboard.page_labels = [PageLabel(page=page, kind="portrait") for page in range(1, 21)] blackboard.page_full_text_cache = { 10: build_page_text_bands((LineDraft(text="Contents"),)), 11: build_page_text_bands((LineDraft(text="Contents"),)), @@ -972,7 +972,7 @@ def test_find_toc_anchor_pages_adds_page_screen_toc_pages( category_label="Report", routing_category=PdfRoutingCategory.GENERIC.value, ) - blackboard.page_labels = [PageLabel(page=page, kind="normal") for page in range(1, 21)] + blackboard.page_labels = [PageLabel(page=page, kind="portrait") for page in range(1, 21)] blackboard.page_full_text_cache = { 2: build_page_text_bands((LineDraft(text="Contents"),)), } diff --git a/apps/worker/tests/contract/test_page_memory_scope_enrichment_task_contract.py b/apps/worker/tests/contract/test_page_memory_scope_enrichment_task_contract.py index c0b0cae04..b90ba4f52 100644 --- a/apps/worker/tests/contract/test_page_memory_scope_enrichment_task_contract.py +++ b/apps/worker/tests/contract/test_page_memory_scope_enrichment_task_contract.py @@ -516,7 +516,7 @@ def _build_storage_inputs() -> dict[str, bytes]: ) for page in range(1, 5) ], - page_labels=[PageLabel(page=page, kind="normal") for page in range(1, 5)], + page_labels=[PageLabel(page=page, kind="portrait") for page in range(1, 5)], toc_result=TocResult(toc_pages=[]), ) return { diff --git a/apps/worker/tests/contract/test_profile_skeleton_anchor_wiring_contract.py b/apps/worker/tests/contract/test_profile_skeleton_anchor_wiring_contract.py index b8af99e77..0e5e2b3b3 100644 --- a/apps/worker/tests/contract/test_profile_skeleton_anchor_wiring_contract.py +++ b/apps/worker/tests/contract/test_profile_skeleton_anchor_wiring_contract.py @@ -102,7 +102,7 @@ def _anatomy(*, with_anchor: bool) -> PageAnatomyMap: for page in range(1, 11) ], "page_labels": [ - PageLabel(page=page, kind="normal") + PageLabel(page=page, kind="portrait") for page in range(1, 11) ], "toc_result": TocResult(method="vlm_batch", toc_pages=[1]), @@ -360,7 +360,7 @@ def test_c4_uses_persisted_pending_relationship_and_does_not_classify() -> None: for page in range(1, 31) ] anatomy.page_labels = [ - PageLabel(page=page, kind="normal") + PageLabel(page=page, kind="portrait") for page in range(1, 31) ] anatomy.toc_hierarchies = _pending_tocs() diff --git a/apps/worker/tests/contract/test_toc_graft_contract.py b/apps/worker/tests/contract/test_toc_graft_contract.py index f4a1931ab..37a1d2840 100644 --- a/apps/worker/tests/contract/test_toc_graft_contract.py +++ b/apps/worker/tests/contract/test_toc_graft_contract.py @@ -663,7 +663,7 @@ def _anatomy( page_count=page_count, page_features=[_feature(page) for page in range(1, page_count + 1)], page_labels=[ - PageLabel(page=page, kind="normal") + PageLabel(page=page, kind="portrait") for page in range(1, page_count + 1) ], toc_result=TocResult(method="vlm_batch", toc_pages=toc_pages), 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 7bd7f5b39..35b5e9f4f 100644 --- a/apps/worker/tests/unit/test_probe_dense_visual_assets.py +++ b/apps/worker/tests/unit/test_probe_dense_visual_assets.py @@ -46,8 +46,10 @@ def __init__( def get_images(self, full: bool = True) -> list[tuple[int, ...]]: return self._images - def get_image_rects(self, _xref: int) -> list[_FakeRect]: - return self._image_rects + def get_image_info(self) -> list[dict[str, tuple[float, ...]]]: + return [ + {"bbox": (rect.x0, rect.y0, rect.x1, rect.y1)} for rect in self._image_rects + ] def find_tables(self) -> SimpleNamespace: self.find_tables_calls += 1 diff --git a/apps/worker/tests/unit/test_probe_visible_text.py b/apps/worker/tests/unit/test_probe_visible_text.py index 3909fd396..cf1eaf4ec 100644 --- a/apps/worker/tests/unit/test_probe_visible_text.py +++ b/apps/worker/tests/unit/test_probe_visible_text.py @@ -93,3 +93,26 @@ def test_invisible_only_page_counts_as_empty_for_probe(tmp_path: Path) -> None: assert feature["invisible_text_length"] == len("OnlyInvisibleInk") assert feature["text_density"] == 0.0 assert feature["is_blank_like"] is True + + +def test_probe_text_one_reports_image_coverage_for_a_full_page_image( + tmp_path: Path, +) -> None: + pdf_path = tmp_path / "scan_like.pdf" + doc = fitz.open() + page = doc.new_page(width=600, height=800) + pixmap = fitz.Pixmap(fitz.csRGB, fitz.IRect(0, 0, 60, 80), False) + pixmap.clear_with(255) + page.insert_image(page.rect, pixmap=pixmap) + doc.save(pdf_path) + doc.close() + + doc = fitz.open(pdf_path) + try: + feature = _probe_text_one(doc[0], 1) + finally: + doc.close() + + assert feature["raw_text_length"] == 0 + assert feature["image_count"] == 1 + assert feature["image_coverage"] == 1.0 From 8b6e14739597a83d7cff2984612be96d93f13a98 Mon Sep 17 00:00:00 2001 From: chengke <404835780@qq.com> Date: Fri, 4 Dec 2026 04:20:30 -0800 Subject: [PATCH 21/22] Time the blocked native wait, not the whole run, in the execution-timeout test The test bounded the whole worker run, settlement included, by the budget plus 0.32s. The settlement's database work takes about 0.1s locally but 0.8s on the CI runner, so the test failed there without any regression. It now measures how long the blocked native wait lasted and asserts the deadline ended it before its own end. Settlement keeps its own deadline; missing it makes the run return "pending", which the test already rejects. Co-Authored-By: Claude Opus 5.5 --- .../test_indexing_execution_contract.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/apps/api/tests/contract/test_indexing_execution_contract.py b/apps/api/tests/contract/test_indexing_execution_contract.py index f18896e4e..125c9ca48 100644 --- a/apps/api/tests/contract/test_indexing_execution_contract.py +++ b/apps/api/tests/contract/test_indexing_execution_contract.py @@ -211,24 +211,31 @@ def test_execution_timeout_stops_native_wait_and_returns_without_replay( # check measures cancellation of the blocked native wait itself. monkeypatch.setattr(OpenSearchRuntime, "resolve", lambda endpoint: SimpleNamespace(client=None, release=lambda: None)) + nativeWaitSeconds: float = executionBudget * 20 + waitedSeconds: list[float] = [] + def blockedNative(self: OpenSearchLexicalIndex, *, isExact: bool, timeoutSeconds: float) -> NativeLifecycleSnapshot: calls.append("native") - gevent.sleep(executionBudget * 20) + waitStartedAt: float = time.monotonic() + try: + gevent.sleep(nativeWaitSeconds) + finally: + waitedSeconds.append(time.monotonic() - waitStartedAt) raise LexicalIndexError("Native wait reached its deliberately long end") monkeypatch.setattr(settings, "KNOWHERE_INDEXING_TIMEOUT_SECONDS", executionBudget) monkeypatch.setattr(OpenSearchLexicalIndex, "getLifecycleSnapshot", blockedNative) # The failure transition's audit metadata goes through make_json_safe, which imports numpy and - # pandas on first use. Load them here so the timed region measures cancellation, not a cold import. + # pandas on first use. Load them here so a cold import does not spend the settlement deadline. from shared.utils.json_utils import make_json_safe make_json_safe({}) - startedAt: float = time.monotonic() worker: IndexingWorker = IndexingWorker(sessionFactory=sessionmaker(engine, expire_on_commit=False)) assert worker.run(jobId) == "failed" - assert time.monotonic() - startedAt < executionBudget + 0.32 + ( - settings.KNOWHERE_INDEXING_SETTLEMENT_TIMEOUT_SECONDS if executionBudget > 0.08 else 0) assert calls == ["native"] + # Time the blocked native wait itself: the deadline must end it before its own end. The + # settlement that follows has its own deadline, and missing it would return "pending" above. + assert len(waitedSeconds) == 1 and waitedSeconds[0] < nativeWaitSeconds with Session(engine) as session: attempt: IndexingAttempt = session.scalars(select(IndexingAttempt)).one() job: Job = session.scalars(select(Job)).one() From 749da16707f2865e017c887ddf5400da09ffd998 Mon Sep 17 00:00:00 2001 From: chengke <404835780@qq.com> Date: Fri, 4 Dec 2026 04:52:04 -0800 Subject: [PATCH 22/22] Give the execution-timeout test a budget a slow runner can reach the native wait in The 0.08s execution budget also covers the database work before the native wait. On a slow CI runner the deadline fired before the wait began, so the fake native call never ran. A one second budget still ends the twenty second wait early and keeps the test about one second long. Co-Authored-By: Claude Sonnet 5.5 --- apps/api/tests/contract/test_indexing_execution_contract.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/api/tests/contract/test_indexing_execution_contract.py b/apps/api/tests/contract/test_indexing_execution_contract.py index 125c9ca48..241c898c1 100644 --- a/apps/api/tests/contract/test_indexing_execution_contract.py +++ b/apps/api/tests/contract/test_indexing_execution_contract.py @@ -204,7 +204,9 @@ def test_execution_timeout_stops_native_wait_and_returns_without_replay( engine, jobId = parsedRuntime calls: list[str] = [] - executionBudget: float = float(os.environ.get("KNOWHERE_TEST_SHORT_INDEXING_TIMEOUT_SECONDS", "0.08")) + # The budget also covers the database work before the native wait starts. It must be long enough + # for a slow runner to reach the wait, and far shorter than the wait itself. + executionBudget: float = float(os.environ.get("KNOWHERE_TEST_SHORT_INDEXING_TIMEOUT_SECONDS", "1")) from shared.services.retrieval.lexical.runtime import OpenSearchRuntime from types import SimpleNamespace # The RPC is fake; omit unrelated cold TLS/client initialization so this