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" 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."""