From a9185a872194c734b19838978b2c31d2b352095d Mon Sep 17 00:00:00 2001 From: mrveiss Date: Mon, 2 Nov 2026 17:01:06 +0200 Subject: [PATCH 1/2] fix(kb): a collection appears on its first write, not with its entity (#19725) --- autobot-backend/llc/api/companies.py | 8 ++-- autobot-backend/llc/api/sprints.py | 4 -- autobot-backend/llc/api/work_items.py | 1 - autobot-backend/llc/kb/collections.py | 2 +- ...mpany_create_kb_and_list_n1_12323_12325.py | 25 ++-------- .../tests/test_kb_collections_lazy_19725.py | 47 +++++++++++++++++++ scripts/python_file_size_known_large.py | 6 +-- 7 files changed, 57 insertions(+), 36 deletions(-) create mode 100644 autobot-backend/llc/tests/test_kb_collections_lazy_19725.py diff --git a/autobot-backend/llc/api/companies.py b/autobot-backend/llc/api/companies.py index 3b4c8f16b0..cccfc3ff33 100644 --- a/autobot-backend/llc/api/companies.py +++ b/autobot-backend/llc/api/companies.py @@ -194,16 +194,14 @@ async def _assert_may_create_under( async def _create_and_commit( svc: CompanyService, membership_svc: MembershipService, body: CompanyCreate, user_id: str ) -> CompanyRead: - """Insert, record the creator as OWNER, ensure the KB collections, THEN commit (GH#12323). + """Insert, record the creator as OWNER, THEN commit (GH#12323). - A failure in any step is rolled back by the route, so no committed-but-unreported row; - ``ensure_collection`` is idempotent, so a rollback leaves only reusable empty collections. + A failure in any step is rolled back by the route, so no committed-but-unreported row. + KB collections appear on their first write, so creating a company makes none (#19725). """ org = await svc.create(body) await membership_svc.add_member(svc.session, str(org.id), user_id, MembershipRole.OWNER) read = _to_read(org) - for suffix in (None, KbCollectionManager.AGENTS_SUFFIX, KbCollectionManager.DECISIONS_SUFFIX): - await _kb_manager.ensure_collection(KbCollectionManager.COMPANY_PREFIX, org.id, suffix) await svc.session.commit() return read diff --git a/autobot-backend/llc/api/sprints.py b/autobot-backend/llc/api/sprints.py index db501de975..cb983ca506 100644 --- a/autobot-backend/llc/api/sprints.py +++ b/autobot-backend/llc/api/sprints.py @@ -48,7 +48,6 @@ from llc.deps import load_owned_project as _load_owned_project from user_management.services import TenantContext -from ..kb.collections import KbCollectionManager from ..models.enums import ApprovalType, SprintStatus, WorkItemRelationType, WorkItemStatus from ..models.sprint import LLCPortfolio, LLCProgram, LLCProject, LLCSprint from ..models.work_item import LLCWorkItem, LLCWorkItemRelation @@ -66,7 +65,6 @@ _approval_svc = ApprovalService() _autoclose_svc = SprintAutoCloseService(approval_service=_approval_svc) -_kb_manager = KbCollectionManager() # ------------------------------------------------------------------ Schemas @@ -589,7 +587,6 @@ async def create_project( session.add(project) await session.commit() await session.refresh(project) - await _kb_manager.ensure_collection(KbCollectionManager.PROJECT_PREFIX, project.id) return project @@ -844,7 +841,6 @@ async def create_sprint( session.add(sprint) await session.commit() await session.refresh(sprint) - await _kb_manager.ensure_collection(KbCollectionManager.SPRINT_PREFIX, sprint.id) return sprint diff --git a/autobot-backend/llc/api/work_items.py b/autobot-backend/llc/api/work_items.py index 56c43834bd..f8d27ea6f3 100644 --- a/autobot-backend/llc/api/work_items.py +++ b/autobot-backend/llc/api/work_items.py @@ -425,7 +425,6 @@ async def create_work_item( except ValueError as exc: # e.g. unknown approval category (GH#11206) raise HTTPException(status_code=400, detail=str(exc)) await session.commit() - await _kb_manager.ensure_collection(KbCollectionManager.WORK_ITEM_PREFIX, item.id) return await _item_to_dict(item, session) diff --git a/autobot-backend/llc/kb/collections.py b/autobot-backend/llc/kb/collections.py index 5afd1ca14e..98d2758565 100644 --- a/autobot-backend/llc/kb/collections.py +++ b/autobot-backend/llc/kb/collections.py @@ -134,7 +134,7 @@ async def archive_collection( try: original = await kb._async_chroma_client.get_collection(original_name) except Exception: - logger.warning( + logger.debug( # the usual case: a collection appears only on its first write (#19725) "Collection %s does not exist; nothing to archive", original_name, ) diff --git a/autobot-backend/llc/tests/test_company_create_kb_and_list_n1_12323_12325.py b/autobot-backend/llc/tests/test_company_create_kb_and_list_n1_12323_12325.py index 6776d6cb15..873291b5df 100644 --- a/autobot-backend/llc/tests/test_company_create_kb_and_list_n1_12323_12325.py +++ b/autobot-backend/llc/tests/test_company_create_kb_and_list_n1_12323_12325.py @@ -100,8 +100,8 @@ def _membership() -> MagicMock: @pytest.mark.asyncio -async def test_create_commits_after_kb_and_serialize(monkeypatch): - """Happy path: KB ensured + response serialized, then exactly one commit.""" +async def test_create_commits_once_and_makes_no_kb_collection(monkeypatch): + """Happy path: response serialized, one commit, and no empty collections (#19725).""" ensure = AsyncMock() monkeypatch.setattr(companies.KbCollectionManager, "ensure_collection", ensure) svc = _create_svc() @@ -109,30 +109,11 @@ async def test_create_commits_after_kb_and_serialize(monkeypatch): async with _client(_app(svc, membership)) as client: resp = await client.post("/api/llc/companies/", json={"name": "NewCo"}) assert resp.status_code == 201, resp.text - # KB collections created for the 3 canonical suffixes. - assert ensure.await_count == 3 + ensure.assert_not_awaited() svc.session.commit.assert_awaited_once() svc.session.rollback.assert_not_called() -@pytest.mark.asyncio -async def test_create_kb_failure_rolls_back_no_commit(monkeypatch): - """A KB failure must roll the INSERT back and never commit (#12323).""" - monkeypatch.setattr( - companies.KbCollectionManager, - "ensure_collection", - AsyncMock(side_effect=RuntimeError("chroma down")), - ) - svc = _create_svc() - membership = _membership() - async with _client(_app(svc, membership)) as client: - resp = await client.post("/api/llc/companies/", json={"name": "NewCo"}) - assert resp.status_code == 500 - # The company INSERT is rolled back and never committed → no committed-but-500 row. - svc.session.commit.assert_not_called() - svc.session.rollback.assert_awaited() - - @pytest.mark.asyncio async def test_create_serialize_failure_rolls_back_no_commit(monkeypatch): """A serialization failure before commit also rolls back (#12323).""" diff --git a/autobot-backend/llc/tests/test_kb_collections_lazy_19725.py b/autobot-backend/llc/tests/test_kb_collections_lazy_19725.py new file mode 100644 index 0000000000..e78239b8d5 --- /dev/null +++ b/autobot-backend/llc/tests/test_kb_collections_lazy_19725.py @@ -0,0 +1,47 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""#19725: a collection appears on its first write, under the one name builder (#19519). + +55 of 65 collections on a node were empty because every new work item, company and sprint made +its own. Stored names read ``work_item_`` only because the KB client maps ``:`` to ``_``; code +must never build that form itself. +""" + +from __future__ import annotations + +import ast +import re +from pathlib import Path + +_LLC = Path(__file__).resolve().parents[1] +_HAND_BUILT_NAME = re.compile(r"""f["'](?:work_item|company|project|sprint|agent)_\{[^}]*\}(?:_\w+)?["']""") +_NAME_BUILDER = _LLC / "kb" / "collections.py" + + +def _sources() -> list[Path]: + return [p for p in _LLC.rglob("*.py") if "tests" not in p.parts and not p.name.endswith("_test.py")] + + +def _ensure_calls(source: str) -> int: + calls = [n for n in ast.walk(ast.parse(source)) if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)] + return sum(call.func.attr == "ensure_collection" for call in calls) + + +def test_the_scan_sees_the_llc_package() -> None: + assert len(_sources()) > 50, "the guard would be judging almost nothing" + assert _ensure_calls("async def f(m):\n await m.ensure_collection('a', 'b')\n") == 1 + assert _HAND_BUILT_NAME.search('x = f"work_item_{item_id}"') + assert not _HAND_BUILT_NAME.search('x = f"company_{company_id}_template.json"'), "a download name isn't one" + + +def test_creating_an_entity_creates_no_collection() -> None: + offenders = [str(p) for p in _sources() if _ensure_calls(p.read_text(encoding="utf-8"))] + assert offenders == [], "a collection is created by its first write, not when the entity is" + + +def test_no_collection_name_is_built_by_hand() -> None: + sources = [p for p in _sources() if p != _NAME_BUILDER] + offenders = [str(p) for p in sources if _HAND_BUILT_NAME.search(p.read_text(encoding="utf-8"))] + assert offenders == [], "use company_collection(), project_collection() and the others in llc/kb/collections.py" diff --git a/scripts/python_file_size_known_large.py b/scripts/python_file_size_known_large.py index f097d7d38a..d2dab62891 100644 --- a/scripts/python_file_size_known_large.py +++ b/scripts/python_file_size_known_large.py @@ -234,10 +234,10 @@ "autobot-backend/knowledge/tags.py": 834, "autobot-backend/knowledge_sync_incremental.py": 867, "autobot-backend/llc/adapters/tests/test_claude_code_adapter.py": 602, - "autobot-backend/llc/api/companies.py": 1611, + "autobot-backend/llc/api/companies.py": 1609, "autobot-backend/llc/api/roles.py": 713, - "autobot-backend/llc/api/sprints.py": 1220, - "autobot-backend/llc/api/work_items.py": 1303, # #19582: comment wake moved into the service + "autobot-backend/llc/api/sprints.py": 1216, + "autobot-backend/llc/api/work_items.py": 1302, # #19582: comment wake moved into the service "autobot-backend/llc/scheduler/heartbeat_scheduler.py": 994, # #19240 (run key moved out) "autobot-backend/llc/services/template.py": 643, "autobot-backend/llc/services/work_item_service.py": 1023, # #20102: completion effects moved out From a42688e925df09d08a598ea3c5ef70e4c6d3c9dd Mon Sep 17 00:00:00 2001 From: mrveiss Date: Mon, 2 Nov 2026 17:12:56 +0200 Subject: [PATCH 2/2] fix(kb): a sprint with no collection still closes, and writers keep the metadata (#19725) --- autobot-backend/llc/api/companies.py | 4 ++-- autobot-backend/llc/kb/artifact_ingestor.py | 12 ++++++++---- autobot-backend/llc/kb/collections.py | 5 ++++- autobot-backend/llc/kb/sprint_summarizer.py | 12 ++++-------- autobot-backend/llc/kb/work_item_kb.py | 7 +++++-- ..._company_create_kb_and_list_n1_12323_12325.py | 2 +- .../llc/tests/test_kb_collections_lazy_19725.py | 7 +++++++ .../llc/tests/test_sprint_summarizer.py | 16 +++++++++++++++- 8 files changed, 46 insertions(+), 19 deletions(-) diff --git a/autobot-backend/llc/api/companies.py b/autobot-backend/llc/api/companies.py index cccfc3ff33..ac746b23e8 100644 --- a/autobot-backend/llc/api/companies.py +++ b/autobot-backend/llc/api/companies.py @@ -298,8 +298,8 @@ async def delete_company( try: await svc.delete(company_id) await svc.session.commit() - # #13920: drop the three collections create_company's ensure_collection - # loop makes (base, agents, decisions). Derived from the same constants + # #13920: drop the three collections a company's writes can make + # (base, agents, decisions). Derived from the same constants # rather than restated, so a fourth suffix cannot be created and then # silently never cleaned up. for suffix in (None, KbCollectionManager.AGENTS_SUFFIX, KbCollectionManager.DECISIONS_SUFFIX): diff --git a/autobot-backend/llc/kb/artifact_ingestor.py b/autobot-backend/llc/kb/artifact_ingestor.py index a2dfd9b761..6b349e3ab7 100644 --- a/autobot-backend/llc/kb/artifact_ingestor.py +++ b/autobot-backend/llc/kb/artifact_ingestor.py @@ -28,7 +28,7 @@ from ..models.work_product import LLCWorkProduct from ..storage_root import llc_local_storage_root -from .collections import kb_chroma_client, project_collection +from .collections import KbCollectionManager, kb_chroma_client, project_collection from .write_guard import assert_not_writing_to_ancestor_kb logger = logging.getLogger(__name__) @@ -95,12 +95,16 @@ def _split_text(text: str) -> List[str]: return chunks -async def _upsert_chunks(collection_name: str, product_id: str, chunks: List[str], meta: Dict[str, Any]) -> None: +async def _upsert_chunks( + collection_name: str, project_id: str, product_id: str, chunks: List[str], meta: Dict[str, Any] +) -> None: """Upsert one work product's chunks into its project collection (ArtifactIngestor.ingest).""" # #19519: the KB client maps ``:`` to a ChromaDB-valid name; the raw # client passes ``project:`` through and ChromaDB rejects it. client = await kb_chroma_client() - collection = await client.get_or_create_collection(collection_name) + collection = await client.get_or_create_collection( + collection_name, metadata={"entity_type": KbCollectionManager.PROJECT_PREFIX, "entity_id": project_id} + ) ids = [f"wp:{product_id}:chunk:{i}" for i in range(len(chunks))] await collection.upsert(ids=ids, documents=chunks, metadatas=[meta.copy() for _ in chunks]) @@ -186,7 +190,7 @@ async def ingest( } try: - await _upsert_chunks(collection_name, str(product.id), chunks, meta) + await _upsert_chunks(collection_name, project_id, str(product.id), chunks, meta) logger.info( "ArtifactIngestor: indexed %d chunk(s) for work product %s into %s", len(chunks), diff --git a/autobot-backend/llc/kb/collections.py b/autobot-backend/llc/kb/collections.py index 98d2758565..ea6721868b 100644 --- a/autobot-backend/llc/kb/collections.py +++ b/autobot-backend/llc/kb/collections.py @@ -5,7 +5,7 @@ """KB collection lifecycle manager (GH#8235). Canonical naming and lifecycle for ChromaDB collections across all LLC entities. -Collections are created on entity creation and archived on entity deletion, +Collections are created by their first write (#19725) and archived on entity deletion, with document merging support for ephemeral entities (sprints, work items). """ @@ -73,6 +73,9 @@ async def ensure_collection( ) -> str: """Create ChromaDB collection if not exists; idempotent. + No production caller since entities stopped creating one (#19725); that issue's + health-scan proposal is its next caller. + Args: entity_type: Type of entity entity_id: Unique identifier for the entity diff --git a/autobot-backend/llc/kb/sprint_summarizer.py b/autobot-backend/llc/kb/sprint_summarizer.py index 3ae75bc5cc..4dd92c9d78 100644 --- a/autobot-backend/llc/kb/sprint_summarizer.py +++ b/autobot-backend/llc/kb/sprint_summarizer.py @@ -209,16 +209,12 @@ async def _fetch_documents(self, collection_name: str) -> List[Dict[str, Any]]: try: kb = await get_knowledge_base() - col = await kb._async_chroma_client.get_collection(collection_name) + # #19725: a sprint with no KB writes has no collection, and that's an empty sprint, not a failure. + col = await kb._async_chroma_client.get_collection_or_none(collection_name) + if col is None: + return [] raw = await col.get(include=["documents", "metadatas", "embeddings"]) except Exception as exc: - exc_msg = str(exc).lower() - if "not found" in exc_msg or "does not exist" in exc_msg: - logger.info( - "Collection %s does not exist; treating as empty", - collection_name, - ) - return [] logger.error( "Failed to fetch documents from %s: %s — archive will be skipped", collection_name, diff --git a/autobot-backend/llc/kb/work_item_kb.py b/autobot-backend/llc/kb/work_item_kb.py index 7ff603eb19..ac57e28609 100644 --- a/autobot-backend/llc/kb/work_item_kb.py +++ b/autobot-backend/llc/kb/work_item_kb.py @@ -17,7 +17,7 @@ from utils.file_types import TEXT_FILE_EXTENSIONS -from .collections import kb_chroma_client, work_item_collection +from .collections import KbCollectionManager, kb_chroma_client, work_item_collection logger = logging.getLogger(__name__) @@ -168,7 +168,10 @@ async def _upsert( # #19519: the KB client maps ``:`` to a ChromaDB-valid name; the raw # client passes ``work_item:`` through and ChromaDB rejects it. client = await kb_chroma_client() - collection = await client.get_or_create_collection(_collection_name(work_item_id)) + collection = await client.get_or_create_collection( + _collection_name(work_item_id), + metadata={"entity_type": KbCollectionManager.WORK_ITEM_PREFIX, "entity_id": str(work_item_id)}, + ) await collection.upsert( ids=[doc_id], documents=[content], diff --git a/autobot-backend/llc/tests/test_company_create_kb_and_list_n1_12323_12325.py b/autobot-backend/llc/tests/test_company_create_kb_and_list_n1_12323_12325.py index 873291b5df..c7f66b2815 100644 --- a/autobot-backend/llc/tests/test_company_create_kb_and_list_n1_12323_12325.py +++ b/autobot-backend/llc/tests/test_company_create_kb_and_list_n1_12323_12325.py @@ -102,7 +102,7 @@ def _membership() -> MagicMock: @pytest.mark.asyncio async def test_create_commits_once_and_makes_no_kb_collection(monkeypatch): """Happy path: response serialized, one commit, and no empty collections (#19725).""" - ensure = AsyncMock() + ensure = AsyncMock(side_effect=RuntimeError("chroma down")) # creating a company doesn't depend on it monkeypatch.setattr(companies.KbCollectionManager, "ensure_collection", ensure) svc = _create_svc() membership = _membership() diff --git a/autobot-backend/llc/tests/test_kb_collections_lazy_19725.py b/autobot-backend/llc/tests/test_kb_collections_lazy_19725.py index e78239b8d5..dc330a3c2d 100644 --- a/autobot-backend/llc/tests/test_kb_collections_lazy_19725.py +++ b/autobot-backend/llc/tests/test_kb_collections_lazy_19725.py @@ -41,6 +41,13 @@ def test_creating_an_entity_creates_no_collection() -> None: assert offenders == [], "a collection is created by its first write, not when the entity is" +def test_a_route_handler_doesnt_create_a_collection_directly() -> None: + routes = [p for p in (_LLC / "api").rglob("*.py") if not p.name.endswith("_test.py")] + assert routes, "the guard would be judging nothing" + offenders = [str(p) for p in routes if "get_or_create_collection" in p.read_text(encoding="utf-8")] + assert offenders == [], "a collection is created by the KB code that writes to it" + + def test_no_collection_name_is_built_by_hand() -> None: sources = [p for p in _sources() if p != _NAME_BUILDER] offenders = [str(p) for p in sources if _HAND_BUILT_NAME.search(p.read_text(encoding="utf-8"))] diff --git a/autobot-backend/llc/tests/test_sprint_summarizer.py b/autobot-backend/llc/tests/test_sprint_summarizer.py index efd27a507c..8a090ddeea 100644 --- a/autobot-backend/llc/tests/test_sprint_summarizer.py +++ b/autobot-backend/llc/tests/test_sprint_summarizer.py @@ -229,7 +229,7 @@ async def test_fetch_documents_reraises_non_notfound_exception(summarizer, km_mo """Fix 2: transient ChromaDB errors must propagate, not silently return [].""" kb_mock = AsyncMock() kb_mock._async_chroma_client = AsyncMock() - kb_mock._async_chroma_client.get_collection = AsyncMock(side_effect=RuntimeError("connection refused")) + kb_mock._async_chroma_client.get_collection_or_none = AsyncMock(side_effect=RuntimeError("connection refused")) import sys @@ -240,6 +240,20 @@ async def test_fetch_documents_reraises_non_notfound_exception(summarizer, km_mo await summarizer._fetch_documents("sprint:xxx") +@pytest.mark.asyncio +async def test_a_sprint_with_no_collection_reads_as_empty(summarizer, km_mock): + """#19725: collections appear on first write, so closing a sprint that never wrote must still work.""" + import sys + + kb_mock = AsyncMock() + kb_mock._async_chroma_client = AsyncMock() + kb_mock._async_chroma_client.get_collection_or_none = AsyncMock(return_value=None) + fake_kb_module = MagicMock() + fake_kb_module.get_knowledge_base = AsyncMock(return_value=kb_mock) + with patch.dict(sys.modules, {"knowledge": fake_kb_module}): + assert await summarizer._fetch_documents("sprint:xxx") == [] + + @pytest.mark.asyncio async def test_no_session_skips_load_sprint_context(summarizer, km_mock): """Fix 3: calling without session must skip _load_sprint_context and archive."""