diff --git a/docs/source/customization/knowledge-layer.md b/docs/source/customization/knowledge-layer.md index 5f74c9302..3d9210ea6 100644 --- a/docs/source/customization/knowledge-layer.md +++ b/docs/source/customization/knowledge-layer.md @@ -350,6 +350,13 @@ writes. A 404/410 from version-probing job creation or immediate upload means the service contract is incompatible; a later polling 404/410 means the job is missing or expired. +`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 service baseline is the immutable NeMo Retriever integration head [`f3a0b418b7250fa8823ec44dea569b07e2b008cb`](https://github.com/NVIDIA/NeMo-Retriever/commit/f3a0b418b7250fa8823ec44dea569b07e2b008cb), which contains the collection-management fixes and TXT/HTML service-mode tokenizer support. See the @@ -607,6 +614,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 @@ -701,7 +712,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 79a4374ba..3b3f71f24 100644 --- a/sources/knowledge_layer/src/nemo_retriever/README.md +++ b/sources/knowledge_layer/src/nemo_retriever/README.md @@ -162,6 +162,34 @@ separate key for each endpoint. remote inference. Python 3.13, Intel macOS, local GPU inference, and shared multi-process data directories are outside the initial support target. +## 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, +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. + ## Upload format and batch contract AI-Q keeps its global upload allowlist at the common backend subset. To enable diff --git a/sources/knowledge_layer/src/nemo_retriever/adapter.py b/sources/knowledge_layer/src/nemo_retriever/adapter.py index 80987dfba..b6f97b8b7 100644 --- a/sources/knowledge_layer/src/nemo_retriever/adapter.py +++ b/sources/knowledge_layer/src/nemo_retriever/adapter.py @@ -10,6 +10,7 @@ import logging import os import threading +from collections import defaultdict from concurrent.futures import Future from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass @@ -32,10 +33,16 @@ 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 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 +from aiq_agent.knowledge import unregister_summary from aiq_agent.knowledge.base import IngestionBatchTooLargeError from aiq_agent.knowledge.base import IngestionCapacityError +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 @@ -67,6 +74,22 @@ _BACKEND_NAME = "nemo_retriever" _RESOURCE_PAGE_SIZE = 100 _JOB_PAGE_SIZE = 1000 +_PHYSICAL_STORAGE_KEYS = frozenset( + { + "database_uri", + "lance_uri", + "lancedb_uri", + "physical_table", + "table_name", + "table_path", + "vdb_uri", + } +) +_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")) _PUBLIC_DOCUMENT_ERROR = "NeMo Retriever document ingestion failed" _SERVICE_CONFIG_KEYS = frozenset( { @@ -98,6 +121,8 @@ class _Settings: verify_ssl: bool ca_bundle: str | None collection_ttl_hours: float + warm_start: bool + start_ttl_cleanup: bool @dataclass(frozen=True) @@ -185,6 +210,8 @@ def _settings(config: dict[str, Any]) -> _Settings: ), ca_bundle=(str(value) if (value := _config_value(config, "ca_bundle", "NRL_CA_BUNDLE")) is not None 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 +359,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( @@ -422,7 +461,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): @@ -434,6 +473,10 @@ 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 + self._document_id_to_filename: dict[str, str] = {} + self._summarized: defaultdict[str, set[str]] = defaultdict(set) + self._collection_expirations: dict[str, datetime] = {} self._upload_batches: dict[str, _UploadBatchState] = {} self._submission_condition = threading.Condition(self._tracking_lock) self._outstanding_uploads = 0 @@ -444,6 +487,123 @@ def __init__(self, config: dict[str, Any] | None = None): ) self._close_lock = threading.Lock() self._closed = False + 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.""" + thread = threading.Thread( + target=self._warm_start, + daemon=True, + name=f"{self.backend_name}-warm-start", + ) + thread.start() + + def _warm_start(self) -> None: + """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 state only after NRL confirms a locally due collection is gone. + + 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. + """ + 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") + + 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: + """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 + 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. The + expirations NRL reports are adopted as well, which is what lets TTL cleanup act on + collections this process did not create itself. + """ + 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) + # 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)") + + 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. + + 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) + known: set[str] = set() + for document in documents: + 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, None) + else: + with self._tracking_lock: + self._summarized[collection_name].add(document.file_id) + for orphan in stored - known: + unregister_summary(collection_name, orphan) def _begin_submission(self, requested: int) -> None: """Atomically reserve a complete batch before creating an upstream job.""" @@ -502,7 +662,34 @@ def create_collection( "expires_at": expires_at.isoformat(), }, ) - 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, + name: str, + *, + description: str | None = None, + metadata: dict[str, Any] | None = None, + expires_at: datetime | None = None, + ) -> CollectionInfo: + body: dict[str, Any] = {} + if description is not None: + body["description"] = description + if metadata is not None: + body["metadata"] = _scrub_metadata(metadata) + if expires_at is not None: + body["expires_at"] = expires_at.isoformat() + payload = self._transport.request_json( + "PATCH", + f"/v1/collections/{_resource_path(name)}", + operation="update collection", + json=body, + ) + 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( @@ -513,6 +700,7 @@ def delete_collection(self, name: str) -> bool: params={"if_exists": "true"}, ) result = _wire(CollectionDeleteWire, payload, "delete collection") + self._forget_collection(name) return result.deleted or not result.existed or result.cleanup_pending def list_collections(self) -> list[CollectionInfo]: @@ -727,9 +915,21 @@ 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( + collection_name, + status, + item.document_id, + item.filename, + ) upstream_details[item.document_id] = FileProgress( file_id=item.document_id, file_name=item.filename or item.document_id, @@ -783,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" @@ -884,6 +1080,12 @@ def delete_file(self, file_id: str, collection_name: str) -> bool: params={"if_exists": "true"}, ) result = _wire(DocumentDeleteWire, payload, "delete document") + 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]: @@ -954,3 +1156,23 @@ 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 | 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}") + 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, upsert=has_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 f7eca9558..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"]: @@ -338,6 +338,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..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}, @@ -314,6 +315,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 diff --git a/tests/knowledge_layer_tests/test_nemo_retriever_adapter.py b/tests/knowledge_layer_tests/test_nemo_retriever_adapter.py index 171840145..5a656b12f 100644 --- a/tests/knowledge_layer_tests/test_nemo_retriever_adapter.py +++ b/tests/knowledge_layer_tests/test_nemo_retriever_adapter.py @@ -292,6 +292,7 @@ def _adapter_config(handler: Any, *, token: str = "super-secret", retries: int = "max_concurrency": 2, "max_queued_uploads": 128, "_transport": transport, + "warm_start": False, } 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")