From f53e6344e62b1be9a13ebac90d62c8ed8045416a Mon Sep 17 00:00:00 2001 From: Peter Chang Date: Wed, 12 Aug 2026 09:57:06 -0400 Subject: [PATCH 1/7] Add uploaded filenames and stub summary to Summary Store Signed-off-by: Peter Chang --- .../src/nemo_retriever/adapter.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/sources/knowledge_layer/src/nemo_retriever/adapter.py b/sources/knowledge_layer/src/nemo_retriever/adapter.py index e7be03ba7..0f5d9090a 100644 --- a/sources/knowledge_layer/src/nemo_retriever/adapter.py +++ b/sources/knowledge_layer/src/nemo_retriever/adapter.py @@ -454,6 +454,7 @@ def __init__(self, config: dict[str, Any] | None = None): self._file_jobs: dict[str, str] = {} self._file_sizes: dict[str, int] = {} self._job_collections: dict[str, str] = {} + self._summarized: set[str] = set() @property def backend_name(self) -> str: @@ -636,6 +637,8 @@ def get_job_status(self, job_id: str) -> IngestionJobStatus: if status in {FileStatus.SUCCESS, FileStatus.FAILED}: terminal += 1 attempt_ids[item.document_id] = item.attempt_id + # Always register at least the filename. We may want to gate this behind the generate_summary flag later. + self._register_summary(aggregate.collection_name, item) file_details.append( FileProgress( file_id=item.document_id, @@ -803,3 +806,16 @@ async def health_check(self) -> bool: return isinstance(payload, dict) and payload.get("status") in {"ok", "healthy"} except NemoRetrieverError: return False + + def _register_summary(self, collection_name: str, document: JobDocumentWire) -> None: + """Register a summary for a document if it has been successfully ingested.""" + from aiq_agent.knowledge import register_summary + + if ( + _status_to_file_status(document.status) == FileStatus.SUCCESS + and document.document_id not in self._summarized + ): + logger.info(f"registering summary for {document.filename or document.document_id}") + # TODO: Get the summary for the document + register_summary(collection_name, document.filename or document.document_id, "No Summary Available") + self._summarized.add(document.document_id) From 862a8e7953ebaece47dfe494d770ee1a1fe1cc4b Mon Sep 17 00:00:00 2001 From: Peter Chang Date: Wed, 12 Aug 2026 10:45:07 -0400 Subject: [PATCH 2/7] Remove deleted summaries Signed-off-by: Peter Chang --- .../src/nemo_retriever/adapter.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/sources/knowledge_layer/src/nemo_retriever/adapter.py b/sources/knowledge_layer/src/nemo_retriever/adapter.py index 0f5d9090a..56528f4fc 100644 --- a/sources/knowledge_layer/src/nemo_retriever/adapter.py +++ b/sources/knowledge_layer/src/nemo_retriever/adapter.py @@ -30,8 +30,11 @@ from aiq_agent.knowledge import IngestionJobStatus from aiq_agent.knowledge import JobState from aiq_agent.knowledge import RetrievalResult +from aiq_agent.knowledge import clear_collection_summaries from aiq_agent.knowledge import register_ingestor from aiq_agent.knowledge import register_retriever +from aiq_agent.knowledge import register_summary +from aiq_agent.knowledge import unregister_summary from aiq_agent.knowledge.schema import CollectionInfo from aiq_agent.knowledge.schema import FileInfo from aiq_agent.knowledge.schema import FileStatus @@ -454,7 +457,8 @@ def __init__(self, config: dict[str, Any] | None = None): self._file_jobs: dict[str, str] = {} self._file_sizes: dict[str, int] = {} self._job_collections: dict[str, str] = {} - self._summarized: set[str] = set() + self._summarized: dict[str, set[str]] = {} + self._collection_expirations: dict[str, datetime] = {} @property def backend_name(self) -> str: @@ -478,6 +482,7 @@ def create_collection( "expires_at": expires_at.isoformat(), }, ) + self._collection_expirations[name] = expires_at return _collection_info(_wire(CollectionWire, payload, "create collection")) def update_collection( @@ -511,6 +516,9 @@ def delete_collection(self, name: str) -> bool: params={"if_exists": "true"}, ) result = _wire(CollectionDeleteWire, payload, "delete collection") + clear_collection_summaries(name) + self._collection_expirations.pop(name, None) + self._summarized.pop(name, None) return result.deleted or not result.existed or result.cleanup_pending def list_collections(self) -> list[CollectionInfo]: @@ -736,6 +744,8 @@ def delete_file(self, file_id: str, collection_name: str) -> bool: params={"if_exists": "true"}, ) result = _wire(DocumentDeleteWire, payload, "delete document") + unregister_summary(collection_name, file_id) + self._summarized[collection_name].discard(file_id) return result.deleted or not result.existed or result.cleanup_pending def list_files(self, collection_name: str) -> list[FileInfo]: @@ -809,13 +819,11 @@ async def health_check(self) -> bool: def _register_summary(self, collection_name: str, document: JobDocumentWire) -> None: """Register a summary for a document if it has been successfully ingested.""" - from aiq_agent.knowledge import register_summary - if ( _status_to_file_status(document.status) == FileStatus.SUCCESS - and document.document_id not in self._summarized + and document.document_id not in self._summarized[collection_name] ): logger.info(f"registering summary for {document.filename or document.document_id}") # TODO: Get the summary for the document register_summary(collection_name, document.filename or document.document_id, "No Summary Available") - self._summarized.add(document.document_id) + self._summarized[collection_name].add(document.document_id) From 2a7088a25481e903afbc41eb8fe2dac366b8bcff Mon Sep 17 00:00:00 2001 From: Peter Chang Date: Wed, 12 Aug 2026 13:31:29 -0400 Subject: [PATCH 3/7] fix key errors Signed-off-by: Peter Chang --- .../knowledge_layer/src/nemo_retriever/adapter.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/sources/knowledge_layer/src/nemo_retriever/adapter.py b/sources/knowledge_layer/src/nemo_retriever/adapter.py index 56528f4fc..302f9c6de 100644 --- a/sources/knowledge_layer/src/nemo_retriever/adapter.py +++ b/sources/knowledge_layer/src/nemo_retriever/adapter.py @@ -457,6 +457,9 @@ def __init__(self, config: dict[str, Any] | None = None): self._file_jobs: dict[str, str] = {} self._file_sizes: dict[str, int] = {} self._job_collections: dict[str, str] = {} + # Needed because we want the summary to show the filename, but we work with document_ids + # TODO: Need to warm start this in case the instance is restarted + self._document_id_to_filename: dict[str, str] = {} self._summarized: dict[str, set[str]] = {} self._collection_expirations: dict[str, datetime] = {} @@ -744,8 +747,8 @@ def delete_file(self, file_id: str, collection_name: str) -> bool: params={"if_exists": "true"}, ) result = _wire(DocumentDeleteWire, payload, "delete document") - unregister_summary(collection_name, file_id) - self._summarized[collection_name].discard(file_id) + unregister_summary(collection_name, self._document_id_to_filename.get(file_id, file_id)) + self._summarized.get(collection_name, set()).discard(file_id) return result.deleted or not result.existed or result.cleanup_pending def list_files(self, collection_name: str) -> list[FileInfo]: @@ -819,11 +822,15 @@ async def health_check(self) -> bool: def _register_summary(self, collection_name: str, document: JobDocumentWire) -> None: """Register a summary for a document if it has been successfully ingested.""" + if not self._summarized.get(collection_name): + self._summarized[collection_name] = set() if ( _status_to_file_status(document.status) == FileStatus.SUCCESS and document.document_id not in self._summarized[collection_name] ): logger.info(f"registering summary for {document.filename or document.document_id}") # TODO: Get the summary for the document - register_summary(collection_name, document.filename or document.document_id, "No Summary Available") + filename = document.filename or document.document_id + self._document_id_to_filename[document.document_id] = filename + register_summary(collection_name, filename, "No Summary Available") self._summarized[collection_name].add(document.document_id) From fc70ae4717113de5635b4fc8122610cb32bb258e Mon Sep 17 00:00:00 2001 From: Peter Chang Date: Wed, 12 Aug 2026 14:54:27 -0400 Subject: [PATCH 4/7] warm start NRL (summary store) Signed-off-by: Peter Chang --- .../src/nemo_retriever/README.md | 13 ++ .../src/nemo_retriever/adapter.py | 117 +++++++++++++++--- src/aiq_agent/knowledge/__init__.py | 2 + src/aiq_agent/knowledge/factory.py | 5 + src/aiq_agent/knowledge/summary_store.py | 12 ++ 5 files changed, 131 insertions(+), 18 deletions(-) diff --git a/sources/knowledge_layer/src/nemo_retriever/README.md b/sources/knowledge_layer/src/nemo_retriever/README.md index 727d2be6c..870b5b671 100644 --- a/sources/knowledge_layer/src/nemo_retriever/README.md +++ b/sources/knowledge_layer/src/nemo_retriever/README.md @@ -122,6 +122,19 @@ Query results preserve the order returned by NeMo Retriever and expose its nativ vector distance as `Chunk.distance`. Lower values are closer; AIQ does not normalize or re-rank these backend-specific values. +## Summary reconciliation + +Document summaries live in AIQ's summary store, but NeMo Retriever owns document +lifetime, including server-side collection expiration. Collections therefore +disappear without AIQ observing a delete. On startup the ingestor reconciles the +two on a background thread: documents NRL serves gain a summary row, rows NRL no +longer backs are removed, and a collection's summaries are cleared once NRL +positively reports the collection as absent. + +Reconciliation never blocks or fails startup, and a transport failure leaves the +store untouched rather than deleting summaries NRL could not confirm. The same +pass warms the document-ID-to-filename mapping that document deletes rely on. + ## Validation Run the contract tests without a service: diff --git a/sources/knowledge_layer/src/nemo_retriever/adapter.py b/sources/knowledge_layer/src/nemo_retriever/adapter.py index 302f9c6de..cfdda4ddc 100644 --- a/sources/knowledge_layer/src/nemo_retriever/adapter.py +++ b/sources/knowledge_layer/src/nemo_retriever/adapter.py @@ -9,6 +9,7 @@ import json import logging import threading +from collections import defaultdict from concurrent.futures import ThreadPoolExecutor from concurrent.futures import as_completed from dataclasses import dataclass @@ -31,6 +32,8 @@ from aiq_agent.knowledge import JobState from aiq_agent.knowledge import RetrievalResult from aiq_agent.knowledge import clear_collection_summaries +from aiq_agent.knowledge import get_available_documents +from aiq_agent.knowledge import list_summary_collections from aiq_agent.knowledge import register_ingestor from aiq_agent.knowledge import register_retriever from aiq_agent.knowledge import register_summary @@ -74,6 +77,7 @@ ) _SUCCESS_STATUSES = frozenset({"completed", "indexed", "ready", "success", "succeeded"}) _FAILED_STATUSES = frozenset({"failed", "error"}) +_PLACEHOLDER_SUMMARY = "No Summary Available" @dataclass(frozen=True) @@ -88,6 +92,7 @@ class _Settings: verify_ssl: bool ca_bundle: str | None collection_ttl_hours: float + warm_start: bool @dataclass(frozen=True) @@ -145,6 +150,7 @@ def _settings(config: dict[str, Any]) -> _Settings: verify_ssl=bool(config.get("verify_ssl", True)), ca_bundle=str(config["ca_bundle"]) if config.get("ca_bundle") else None, collection_ttl_hours=collection_ttl_hours, + warm_start=bool(config.get("warm_start", True)), ) @@ -458,10 +464,72 @@ def __init__(self, config: dict[str, Any] | None = None): self._file_sizes: dict[str, int] = {} self._job_collections: dict[str, str] = {} # Needed because we want the summary to show the filename, but we work with document_ids - # TODO: Need to warm start this in case the instance is restarted self._document_id_to_filename: dict[str, str] = {} - self._summarized: dict[str, set[str]] = {} + self._summarized: defaultdict[str, set[str]] = defaultdict(set) self._collection_expirations: dict[str, datetime] = {} + if self._settings.warm_start: + self._start_warm_start_task() + + def _start_warm_start_task(self) -> None: + """Reconcile on a daemon thread so startup neither blocks on NRL nor fails with it.""" + thread = threading.Thread( + target=self._warm_start, + daemon=True, + name=f"{self.backend_name}-warm-start", + ) + thread.start() + + def _warm_start(self) -> None: + """Reconcile the summary store with NRL and leave the adapter caches warm.""" + try: + self._reconcile_summaries() + except Exception: + logger.exception("NeMo Retriever warm start did not complete") + + def _reconcile_summaries(self) -> None: + """Make the summary store match the documents NRL actually holds. + + NRL owns document lifetime, including server-side collection expiration, so it is the + authority here: documents it serves must have a summary row, and rows it no longer backs + are dropped. A collection is cleared only once NRL positively reports it absent, so a + transport failure leaves the store untouched instead of deleting live summaries. + """ + live_collections = {collection.name for collection in self.list_collections()} + for name in live_collections | set(list_summary_collections()): + try: + if name in live_collections: + self._reconcile_collection(name) + elif self.get_collection(name) is None: + clear_collection_summaries(name) + logger.info("Dropped summaries for a collection NeMo Retriever no longer holds") + except NemoRetrieverError: + logger.warning("Skipped summary reconciliation for one collection (NeMo Retriever unavailable)") + + def _reconcile_collection(self, collection_name: str) -> None: + """Reconcile one collection that NRL still holds against its stored summaries. + + The store is read before NRL so that a document ingested mid-reconcile is treated as new + rather than as an orphan: an extra idempotent write is harmless, a wrong delete is not. + """ + stored = {document.file_name for document in get_available_documents(collection_name)} + documents = self.list_files(collection_name) + known: set[str] = set() + for document in documents: + filename = document.file_name or document.file_id + known.add(filename) + if document.status != FileStatus.SUCCESS: + continue + if filename not in stored: + self._register_summary( + collection_name, document.status, document.file_id, filename, _PLACEHOLDER_SUMMARY + ) + else: + # This document is already in the summary store, so we need to update the filename and summarized set + with self._tracking_lock: + self._document_id_to_filename[document.file_id] = filename + self._summarized[collection_name].add(document.file_id) + for orphan in stored - known: + unregister_summary(collection_name, orphan) @property def backend_name(self) -> str: @@ -649,7 +717,13 @@ def get_job_status(self, job_id: str) -> IngestionJobStatus: terminal += 1 attempt_ids[item.document_id] = item.attempt_id # Always register at least the filename. We may want to gate this behind the generate_summary flag later. - self._register_summary(aggregate.collection_name, item) + # TODO: Get the summary for the document + self._register_summary( + aggregate.collection_name, + status, + item.document_id, + item.filename, + ) file_details.append( FileProgress( file_id=item.document_id, @@ -747,8 +821,12 @@ def delete_file(self, file_id: str, collection_name: str) -> bool: params={"if_exists": "true"}, ) result = _wire(DocumentDeleteWire, payload, "delete document") - unregister_summary(collection_name, self._document_id_to_filename.get(file_id, file_id)) - self._summarized.get(collection_name, set()).discard(file_id) + with self._tracking_lock: + summary_key = self._document_id_to_filename.get(file_id, file_id) + unregister_summary(collection_name, summary_key) + with self._tracking_lock: + self._document_id_to_filename.pop(file_id, None) + self._summarized[collection_name].discard(file_id) return result.deleted or not result.existed or result.cleanup_pending def list_files(self, collection_name: str) -> list[FileInfo]: @@ -820,17 +898,20 @@ async def health_check(self) -> bool: except NemoRetrieverError: return False - def _register_summary(self, collection_name: str, document: JobDocumentWire) -> None: + def _register_summary( + self, + collection_name: str, + status: FileStatus, + document_id: str, + filename: str | None, + summary: str | None = None, + ) -> None: """Register a summary for a document if it has been successfully ingested.""" - if not self._summarized.get(collection_name): - self._summarized[collection_name] = set() - if ( - _status_to_file_status(document.status) == FileStatus.SUCCESS - and document.document_id not in self._summarized[collection_name] - ): - logger.info(f"registering summary for {document.filename or document.document_id}") - # TODO: Get the summary for the document - filename = document.filename or document.document_id - self._document_id_to_filename[document.document_id] = filename - register_summary(collection_name, filename, "No Summary Available") - self._summarized[collection_name].add(document.document_id) + if status == FileStatus.SUCCESS and document_id not in self._summarized[collection_name]: + summary = summary or _PLACEHOLDER_SUMMARY + logger.info(f"registering summary for {filename or document_id}") + filename = filename or document_id + with self._tracking_lock: + self._document_id_to_filename[document_id] = filename + self._summarized[collection_name].add(document_id) + register_summary(collection_name, filename, summary) diff --git a/src/aiq_agent/knowledge/__init__.py b/src/aiq_agent/knowledge/__init__.py index 6a3ac0e56..aa90406bc 100644 --- a/src/aiq_agent/knowledge/__init__.py +++ b/src/aiq_agent/knowledge/__init__.py @@ -46,6 +46,7 @@ from .factory import get_available_documents_async from .factory import get_ingestor from .factory import get_retriever +from .factory import list_summary_collections from .factory import register_ingestor from .factory import register_retriever from .factory import register_summary @@ -86,6 +87,7 @@ "unregister_summary", "get_available_documents", "get_available_documents_async", + "list_summary_collections", "clear_collection_summaries", "clear_all_summaries", ] diff --git a/src/aiq_agent/knowledge/factory.py b/src/aiq_agent/knowledge/factory.py index 6692d9646..74c00d408 100644 --- a/src/aiq_agent/knowledge/factory.py +++ b/src/aiq_agent/knowledge/factory.py @@ -325,6 +325,11 @@ async def get_available_documents_async(collection: str) -> list["AvailableDocum return await _get_summary_store().get_all_async(collection) +def list_summary_collections() -> list[str]: + """Get every collection that currently holds summaries.""" + return _get_summary_store().list_collections() + + def unregister_summary(collection: str, filename: str) -> None: """Delete a file's summary.""" _get_summary_store().unregister(collection, filename) diff --git a/src/aiq_agent/knowledge/summary_store.py b/src/aiq_agent/knowledge/summary_store.py index 2c2ae6a7e..0b604a035 100644 --- a/src/aiq_agent/knowledge/summary_store.py +++ b/src/aiq_agent/knowledge/summary_store.py @@ -314,6 +314,18 @@ async def get_all_async(self, collection: str) -> list[AvailableDocument]: # Fallback to sync return self.get_all(collection) + def list_collections(self) -> list[str]: + """Get every collection that currently holds summaries (sync).""" + from sqlalchemy import text + + try: + with self._sync_engine.connect() as conn: + result = conn.execute(text("SELECT DISTINCT collection FROM summaries")) + return [row[0] for row in result] + except Exception as e: + logger.warning("Failed to list summary collections (%s)", type(e).__name__) + return [] + def unregister(self, collection: str, filename: str) -> None: """Remove a document's summary (sync).""" from sqlalchemy import text From 0f421099fb6e312c2824998013093c77fc5cfde0 Mon Sep 17 00:00:00 2001 From: Peter Chang Date: Wed, 12 Aug 2026 16:59:28 -0400 Subject: [PATCH 5/7] remove expired collection summaries --- docs/source/customization/knowledge-layer.md | 13 ++- .../src/nemo_retriever/README.md | 17 +++- .../src/nemo_retriever/adapter.py | 92 ++++++++++++++++--- 3 files changed, 107 insertions(+), 15 deletions(-) diff --git a/docs/source/customization/knowledge-layer.md b/docs/source/customization/knowledge-layer.md index f484d113c..7dcd85fdd 100644 --- a/docs/source/customization/knowledge-layer.md +++ b/docs/source/customization/knowledge-layer.md @@ -278,6 +278,13 @@ per-attempt IDs remain diagnostic metadata. Query filters are rejected until the public NRL query contract supports them. AI-Q does not expose NRL pipeline tuning and does not consume physical VectorDB names or LanceDB locations. +`nrl_collection_ttl_hours` is sent as an absolute expiration when AI-Q creates a +collection, and NRL deletes the expired collection itself. TTL cleanup clears the +document summaries and cached state AI-Q holds for it, so agents stop being +offered documents NRL no longer serves. Expiration comes from NRL rather than +from how long a collection sat idle: the deadline used is the one NRL last +reported for the collection. + The tested baseline is NeMo Retriever commit `edfed55da` plus the TXT/HTML tokenizer landing patch, or a merged successor containing both changes. See the backend operator guide at `sources/knowledge_layer/src/nemo_retriever/README.md` @@ -439,6 +446,10 @@ COLLECTION_TTL_HOURS = 24 TTL_CLEANUP_INTERVAL_SECONDS = 3600 ``` +NeMo Retriever runs the same hourly thread, but that service owns collection lifetime: it deletes collections on the +absolute deadline it was given at creation (`nrl_collection_ttl_hours`), and the thread only expires the summaries and +cached state AI-Q keeps for them rather than deleting anything itself. + --- ## Architecture @@ -533,7 +544,7 @@ Configuration values are resolved in the following order (highest to lowest prio | `KNOWLEDGE_INGESTOR_BACKEND` | All | Default ingestor backend (fallback if not in YAML) | | `AIQ_CHROMA_DIR` | llamaindex | ChromaDB persistence path | | `AIQ_COLLECTION_TTL_HOURS` | all local/managed backends | Hours before stale collections are deleted (default: 24) | -| `AIQ_TTL_CLEANUP_INTERVAL_SECONDS` | all local/managed backends | Collection cleanup interval (default: 3600) | +| `AIQ_TTL_CLEANUP_INTERVAL_SECONDS` | All | Collection cleanup interval (default: 3600) | | `RAG_SERVER_URL` | foundational_rag | Query server URL (port 8081) | | `RAG_INGEST_URL` | foundational_rag | Ingestion server URL (port 8082) | | `OPENSEARCH_URL` | opensearch | OpenSearch endpoint URL | diff --git a/sources/knowledge_layer/src/nemo_retriever/README.md b/sources/knowledge_layer/src/nemo_retriever/README.md index 870b5b671..6bc9ca91a 100644 --- a/sources/knowledge_layer/src/nemo_retriever/README.md +++ b/sources/knowledge_layer/src/nemo_retriever/README.md @@ -133,7 +133,22 @@ positively reports the collection as absent. Reconciliation never blocks or fails startup, and a transport failure leaves the store untouched rather than deleting summaries NRL could not confirm. The same -pass warms the document-ID-to-filename mapping that document deletes rely on. +pass warms the document-ID-to-filename mapping that document deletes rely on, +and adopts the expirations NRL reports so cleanup also covers collections this +process did not create. + +## Collection expiration + +`nrl_collection_ttl_hours` is sent as an absolute expiration when AIQ creates a +collection, and NRL deletes the collection itself once that expiration passes. +A background thread retires only what AIQ keeps alongside it — the collection's +summaries and the adapter's cached document state — so agents stop being offered +documents that can no longer be retrieved. It runs every +`AIQ_TTL_CLEANUP_INTERVAL_SECONDS` (3600 by default), the shared knowledge-layer +setting; unlike the other backends, expiration comes from NRL rather than from +how long a collection sat idle. The deadline used is the one NRL last reported, +recorded when AIQ creates or updates a collection and refreshed by startup +reconciliation. ## Validation diff --git a/sources/knowledge_layer/src/nemo_retriever/adapter.py b/sources/knowledge_layer/src/nemo_retriever/adapter.py index cfdda4ddc..211df2475 100644 --- a/sources/knowledge_layer/src/nemo_retriever/adapter.py +++ b/sources/knowledge_layer/src/nemo_retriever/adapter.py @@ -8,6 +8,7 @@ import hashlib import json import logging +import os import threading from collections import defaultdict from concurrent.futures import ThreadPoolExecutor @@ -38,6 +39,7 @@ from aiq_agent.knowledge import register_retriever from aiq_agent.knowledge import register_summary from aiq_agent.knowledge import unregister_summary +from aiq_agent.knowledge.base import TTLCleanupMixin from aiq_agent.knowledge.schema import CollectionInfo from aiq_agent.knowledge.schema import FileInfo from aiq_agent.knowledge.schema import FileStatus @@ -78,6 +80,8 @@ _SUCCESS_STATUSES = frozenset({"completed", "indexed", "ready", "success", "succeeded"}) _FAILED_STATUSES = frozenset({"failed", "error"}) _PLACEHOLDER_SUMMARY = "No Summary Available" +# Shared with the other knowledge backends so one setting paces every TTL cleanup thread. +TTL_CLEANUP_INTERVAL_SECONDS = int(os.environ.get("AIQ_TTL_CLEANUP_INTERVAL_SECONDS", "3600")) @dataclass(frozen=True) @@ -93,6 +97,7 @@ class _Settings: ca_bundle: str | None collection_ttl_hours: float warm_start: bool + start_ttl_cleanup: bool @dataclass(frozen=True) @@ -151,6 +156,7 @@ def _settings(config: dict[str, Any]) -> _Settings: ca_bundle=str(config["ca_bundle"]) if config.get("ca_bundle") else None, collection_ttl_hours=collection_ttl_hours, warm_start=bool(config.get("warm_start", True)), + start_ttl_cleanup=bool(config.get("start_ttl_cleanup", True)), ) @@ -332,6 +338,18 @@ def _collection_info(item: CollectionWire) -> CollectionInfo: ) +def _collection_expiration(info: CollectionInfo) -> datetime | None: + """Read back the expiration that ``_collection_info`` carries as an ISO string in metadata.""" + raw = info.metadata.get("expires_at") + if not raw: + return None + try: + return _parse_timestamp(datetime.fromisoformat(str(raw))) + except ValueError: + logger.warning("NeMo Retriever reported a collection expiration that could not be parsed") + return None + + def _document_info(item: DocumentWire) -> FileInfo: status = _status_to_file_status(item.status) return FileInfo( @@ -451,7 +469,7 @@ async def health_check(self) -> bool: @register_ingestor(_BACKEND_NAME) -class NemoRetrieverIngestor(BaseIngestor): +class NemoRetrieverIngestor(TTLCleanupMixin, BaseIngestor): """Manage NRL collections and accepted ingestion jobs through REST.""" def __init__(self, config: dict[str, Any] | None = None): @@ -469,6 +487,8 @@ def __init__(self, config: dict[str, Any] | None = None): self._collection_expirations: dict[str, datetime] = {} if self._settings.warm_start: self._start_warm_start_task() + if self._settings.start_ttl_cleanup: + self._start_ttl_cleanup_task(self._settings.collection_ttl_hours, TTL_CLEANUP_INTERVAL_SECONDS) def _start_warm_start_task(self) -> None: """Reconcile on a daemon thread so startup neither blocks on NRL nor fails with it.""" @@ -480,27 +500,69 @@ def _start_warm_start_task(self) -> None: thread.start() def _warm_start(self) -> None: - """Reconcile the summary store with NRL and leave the adapter caches warm.""" + """Reconcile with NRL, retire collections that expired while down, and warm the caches.""" try: self._reconcile_summaries() + self._cleanup_expired_collections() except Exception: logger.exception("NeMo Retriever warm start did not complete") + def _cleanup_expired_collections(self) -> None: + """Drop the summaries and cached state of collections whose NRL expiration has passed. + + NRL expires the collection itself, so cleanup never issues a delete: it only retires the + state AI-Q keeps alongside it, which would otherwise keep offering agents documents that + can no longer be retrieved. + + It also replaces the mixin's idle-time policy: NRL is given an absolute expiration at + creation and enforces it, so inferring one from ``updated_at`` would push AI-Q's view of a + collection past the deadline the service will actually act on. + + Each deadline is the one NRL last reported, recorded at create, update, or reconcile time. + """ + now = datetime.now(UTC) + with self._tracking_lock: + due = [name for name, expires_at in self._collection_expirations.items() if expires_at <= now] + for name in due: + self._forget_collection(name) + logger.info("Dropped summaries for an expired NeMo Retriever collection") + + def _track_expiration(self, name: str, expires_at: datetime | None) -> None: + """Record when NRL will expire a collection, or stop tracking one that no longer expires.""" + with self._tracking_lock: + if expires_at is None: + self._collection_expirations.pop(name, None) + else: + self._collection_expirations[name] = expires_at + + def _forget_collection(self, name: str) -> None: + """Drop a collection's summaries and the adapter state that tracked its documents.""" + clear_collection_summaries(name) + with self._tracking_lock: + self._collection_expirations.pop(name, None) + for document_id in self._summarized.pop(name, set()): + self._document_id_to_filename.pop(document_id, None) + def _reconcile_summaries(self) -> None: """Make the summary store match the documents NRL actually holds. NRL owns document lifetime, including server-side collection expiration, so it is the authority here: documents it serves must have a summary row, and rows it no longer backs are dropped. A collection is cleared only once NRL positively reports it absent, so a - transport failure leaves the store untouched instead of deleting live summaries. + transport failure leaves the store untouched instead of deleting live summaries. The + expirations NRL reports are adopted as well, which is what lets TTL cleanup act on + collections this process did not create itself. """ - live_collections = {collection.name for collection in self.list_collections()} + collections = self.list_collections() + for collection in collections: + self._track_expiration(collection.name, _collection_expiration(collection)) + live_collections = {collection.name for collection in collections} for name in live_collections | set(list_summary_collections()): try: if name in live_collections: self._reconcile_collection(name) elif self.get_collection(name) is None: - clear_collection_summaries(name) + self._forget_collection(name) logger.info("Dropped summaries for a collection NeMo Retriever no longer holds") except NemoRetrieverError: logger.warning("Skipped summary reconciliation for one collection (NeMo Retriever unavailable)") @@ -510,6 +572,9 @@ def _reconcile_collection(self, collection_name: str) -> None: The store is read before NRL so that a document ingested mid-reconcile is treated as new rather than as an orphan: an extra idempotent write is harmless, a wrong delete is not. + + Every document NRL lists gets its filename mapped, because a delete can arrive for one that + is still ingesting. Only successfully ingested documents count as summarized. """ stored = {document.file_name for document in get_available_documents(collection_name)} documents = self.list_files(collection_name) @@ -517,6 +582,8 @@ def _reconcile_collection(self, collection_name: str) -> None: for document in documents: filename = document.file_name or document.file_id known.add(filename) + with self._tracking_lock: + self._document_id_to_filename[document.file_id] = filename if document.status != FileStatus.SUCCESS: continue if filename not in stored: @@ -524,9 +591,7 @@ def _reconcile_collection(self, collection_name: str) -> None: collection_name, document.status, document.file_id, filename, _PLACEHOLDER_SUMMARY ) else: - # This document is already in the summary store, so we need to update the filename and summarized set with self._tracking_lock: - self._document_id_to_filename[document.file_id] = filename self._summarized[collection_name].add(document.file_id) for orphan in stored - known: unregister_summary(collection_name, orphan) @@ -553,8 +618,9 @@ def create_collection( "expires_at": expires_at.isoformat(), }, ) - self._collection_expirations[name] = expires_at - return _collection_info(_wire(CollectionWire, payload, "create collection")) + info = _collection_info(_wire(CollectionWire, payload, "create collection")) + self._track_expiration(name, _collection_expiration(info) or expires_at) + return info def update_collection( self, @@ -577,7 +643,9 @@ def update_collection( operation="update collection", json=body, ) - return _collection_info(_wire(CollectionWire, payload, "update collection")) + info = _collection_info(_wire(CollectionWire, payload, "update collection")) + self._track_expiration(name, _collection_expiration(info) or expires_at) + return info def delete_collection(self, name: str) -> bool: payload = self._transport.request_json( @@ -587,9 +655,7 @@ def delete_collection(self, name: str) -> bool: params={"if_exists": "true"}, ) result = _wire(CollectionDeleteWire, payload, "delete collection") - clear_collection_summaries(name) - self._collection_expirations.pop(name, None) - self._summarized.pop(name, None) + self._forget_collection(name) return result.deleted or not result.existed or result.cleanup_pending def list_collections(self) -> list[CollectionInfo]: From c583fbfba30aa844cb9cefdff1fff106ad69b976 Mon Sep 17 00:00:00 2001 From: Peter Chang Date: Mon, 17 Aug 2026 16:51:58 -0400 Subject: [PATCH 6/7] fix tests Signed-off-by: Peter Chang --- tests/knowledge_layer_tests/test_nemo_retriever_adapter.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/knowledge_layer_tests/test_nemo_retriever_adapter.py b/tests/knowledge_layer_tests/test_nemo_retriever_adapter.py index 998defd99..68599eb81 100644 --- a/tests/knowledge_layer_tests/test_nemo_retriever_adapter.py +++ b/tests/knowledge_layer_tests/test_nemo_retriever_adapter.py @@ -283,6 +283,7 @@ def _adapter_config(handler: Any, *, token: str = "super-secret", retries: int = "max_retries": retries, "max_concurrency": 2, "_transport": transport, + "warm_start": False, } From d0f3ab81089ead356e678f35c0a7102bb02ee3e9 Mon Sep 17 00:00:00 2001 From: Peter Chang Date: Wed, 19 Aug 2026 10:34:05 -0400 Subject: [PATCH 7/7] PR comments Signed-off-by: Peter Chang --- .../src/nemo_retriever/adapter.py | 55 +++++++++++-------- src/aiq_agent/knowledge/factory.py | 6 +- src/aiq_agent/knowledge/summary_store.py | 13 +++-- .../test_summary_store.py | 9 +++ 4 files changed, 51 insertions(+), 32 deletions(-) diff --git a/sources/knowledge_layer/src/nemo_retriever/adapter.py b/sources/knowledge_layer/src/nemo_retriever/adapter.py index d4f2137e9..b6f97b8b7 100644 --- a/sources/knowledge_layer/src/nemo_retriever/adapter.py +++ b/sources/knowledge_layer/src/nemo_retriever/adapter.py @@ -510,22 +510,32 @@ def _warm_start(self) -> None: logger.exception("NeMo Retriever warm start did not complete") def _cleanup_expired_collections(self) -> None: - """Drop the summaries and cached state of collections whose NRL expiration has passed. + """Drop state only after NRL confirms a locally due collection is gone. - NRL expires the collection itself, so cleanup never issues a delete: it only retires the - state AI-Q keeps alongside it, which would otherwise keep offering agents documents that - can no longer be retrieved. + NRL expires the collection itself, so cleanup never issues a delete. A locally cached + deadline is only a signal to check NRL: the collection could have had its expiration + extended after the last create, update, or reconciliation. AI-Q drops its summaries and + cached state only once NRL no longer returns the collection. It also replaces the mixin's idle-time policy: NRL is given an absolute expiration at creation and enforces it, so inferring one from ``updated_at`` would push AI-Q's view of a collection past the deadline the service will actually act on. - - Each deadline is the one NRL last reported, recorded at create, update, or reconcile time. """ now = datetime.now(UTC) with self._tracking_lock: due = [name for name, expires_at in self._collection_expirations.items() if expires_at <= now] for name in due: + try: + collection = self.get_collection(name) + if collection is not None: + nrl_expires_at = _collection_expiration(collection) + if nrl_expires_at is None or nrl_expires_at > now: + self._track_expiration(name, nrl_expires_at) + continue + except NemoRetrieverError: + logger.warning("Skipped cleanup for a due collection because NeMo Retriever is unavailable") + continue + self._forget_collection(name) logger.info("Dropped summaries for an expired NeMo Retriever collection") @@ -546,7 +556,7 @@ def _forget_collection(self, name: str) -> None: self._document_id_to_filename.pop(document_id, None) def _reconcile_summaries(self) -> None: - """Make the summary store match the documents NRL actually holds. + """Update the summary store to match the in-scope collections and documents NRL holds. NRL owns document lifetime, including server-side collection expiration, so it is the authority here: documents it serves must have a summary row, and rows it no longer backs @@ -563,9 +573,8 @@ def _reconcile_summaries(self) -> None: try: if name in live_collections: self._reconcile_collection(name) - elif self.get_collection(name) is None: - self._forget_collection(name) - logger.info("Dropped summaries for a collection NeMo Retriever no longer holds") + # collections in the summary store that we don't find in NRL are left as-is + # because they may be owned by another scope except NemoRetrieverError: logger.warning("Skipped summary reconciliation for one collection (NeMo Retriever unavailable)") @@ -582,16 +591,14 @@ def _reconcile_collection(self, collection_name: str) -> None: documents = self.list_files(collection_name) known: set[str] = set() for document in documents: - filename = document.file_name or document.file_id + filename = document.file_name known.add(filename) with self._tracking_lock: self._document_id_to_filename[document.file_id] = filename if document.status != FileStatus.SUCCESS: continue if filename not in stored: - self._register_summary( - collection_name, document.status, document.file_id, filename, _PLACEHOLDER_SUMMARY - ) + self._register_summary(collection_name, document.status, document.file_id, filename, None) else: with self._tracking_lock: self._summarized[collection_name].add(document.file_id) @@ -908,13 +915,17 @@ def get_job_status(self, job_id: str) -> IngestionJobStatus: }.get(aggregate.status.lower(), JobState.PROCESSING) upstream_details: dict[str, FileProgress] = {} attempt_ids: dict[str, str] = {} + collection_name = aggregate.collection_name + if not collection_name: + with self._tracking_lock: + collection_name = self._job_collections.get(job_id, None) for item in documents: status = status_to_file_status(item.status) attempt_ids[item.document_id] = item.attempt_id # Always register at least the filename. We may want to gate this behind the generate_summary flag later. # TODO: Get the summary for the document self._register_summary( - aggregate.collection_name, + collection_name, status, item.document_id, item.filename, @@ -972,10 +983,6 @@ def get_job_status(self, job_id: str) -> IngestionJobStatus: if aggregate.status.lower() == "failed" or terminal >= aggregate.expected_documents else JobState.PROCESSING ) - collection_name = aggregate.collection_name - if not collection_name: - with self._tracking_lock: - collection_name = self._job_collections.get(job_id, "") error_message = None if upload_failures and state == JobState.FAILED: error_message = "NeMo Retriever rejected one or more document uploads" @@ -1152,18 +1159,20 @@ async def health_check(self) -> bool: def _register_summary( self, - collection_name: str, + collection_name: str | None, status: FileStatus, document_id: str, filename: str | None, summary: str | None = None, ) -> None: """Register a summary for a document if it has been successfully ingested.""" + if not filename or not collection_name: + return if status == FileStatus.SUCCESS and document_id not in self._summarized[collection_name]: + has_summary = summary is not None summary = summary or _PLACEHOLDER_SUMMARY - logger.info(f"registering summary for {filename or document_id}") - filename = filename or document_id + logger.info(f"registering summary for {filename}") with self._tracking_lock: self._document_id_to_filename[document_id] = filename self._summarized[collection_name].add(document_id) - register_summary(collection_name, filename, summary) + register_summary(collection_name, filename, summary, upsert=has_summary) diff --git a/src/aiq_agent/knowledge/factory.py b/src/aiq_agent/knowledge/factory.py index 4434a9dc7..512c7a5db 100644 --- a/src/aiq_agent/knowledge/factory.py +++ b/src/aiq_agent/knowledge/factory.py @@ -321,11 +321,11 @@ def _get_summary_store() -> "SummaryStore": return _summary_store -def register_summary(collection: str, filename: str, summary: str | None) -> None: - """Store summary in database.""" +def register_summary(collection: str, filename: str, summary: str | None, upsert: bool = True) -> None: + """Store a summary, optionally preserving an existing filename's summary.""" if not summary: return - _get_summary_store().register(collection, filename, summary) + _get_summary_store().register(collection, filename, summary, upsert=upsert) def get_available_documents(collection: str) -> list["AvailableDocument"]: diff --git a/src/aiq_agent/knowledge/summary_store.py b/src/aiq_agent/knowledge/summary_store.py index 0b604a035..c3c84b90f 100644 --- a/src/aiq_agent/knowledge/summary_store.py +++ b/src/aiq_agent/knowledge/summary_store.py @@ -233,29 +233,30 @@ async def _ensure_table_async(cls, db_url: str): cls._tables_initialized.add(db_url) logger.info("Created summaries table (async) in %s", _redact_db_url(db_url)) - def register(self, collection: str, filename: str, summary: str) -> None: - """Store a document summary (sync).""" + def register(self, collection: str, filename: str, summary: str, upsert: bool = True) -> None: + """Store a document summary, optionally preserving an existing row (sync).""" from sqlalchemy import text - # Use upsert pattern that works for both SQLite and PostgreSQL + # Use dialect-specific conflict handling for SQLite and PostgreSQL. is_postgres = self.db_url.startswith("postgres") try: with self._sync_engine.connect() as conn: if is_postgres: + conflict_action = "DO UPDATE SET summary = EXCLUDED.summary" if upsert else "DO NOTHING" conn.execute( text( "INSERT INTO summaries (collection, filename, summary) " "VALUES (:collection, :filename, :summary) " - "ON CONFLICT (collection, filename) DO UPDATE SET summary = EXCLUDED.summary" + f"ON CONFLICT (collection, filename) {conflict_action}" ), {"collection": collection, "filename": filename, "summary": summary}, ) else: - # SQLite uses INSERT OR REPLACE + sqlite_insert = "INSERT OR REPLACE" if upsert else "INSERT OR IGNORE" conn.execute( text( - "INSERT OR REPLACE INTO summaries (collection, filename, summary) " + f"{sqlite_insert} INTO summaries (collection, filename, summary) " "VALUES (:collection, :filename, :summary)" ), {"collection": collection, "filename": filename, "summary": summary}, diff --git a/tests/knowledge_layer_tests/test_summary_store.py b/tests/knowledge_layer_tests/test_summary_store.py index e3aef851f..3d6e7b55b 100644 --- a/tests/knowledge_layer_tests/test_summary_store.py +++ b/tests/knowledge_layer_tests/test_summary_store.py @@ -210,6 +210,15 @@ def test_register_updates_existing(self, store): assert len(docs) == 1 assert docs[0].summary == "Updated summary" + def test_register_preserves_existing_when_upsert_disabled(self, store): + """Test insert-only registration preserves an existing filename's summary.""" + store.register("collection", "doc.pdf", "Original summary") + store.register("collection", "doc.pdf", "Ignored summary", upsert=False) + + docs = store.get_all("collection") + assert len(docs) == 1 + assert docs[0].summary == "Original summary" + def test_get_all_empty_collection(self, store): """Test getting documents from empty collection returns empty list.""" docs = store.get_all("nonexistent_collection")