Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions autobot-backend/llc/api/companies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -300,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):
Expand Down
4 changes: 0 additions & 4 deletions autobot-backend/llc/api/sprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -66,7 +65,6 @@

_approval_svc = ApprovalService()
_autoclose_svc = SprintAutoCloseService(approval_service=_approval_svc)
_kb_manager = KbCollectionManager()


# ------------------------------------------------------------------ Schemas
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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


Expand Down
1 change: 0 additions & 1 deletion autobot-backend/llc/api/work_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
12 changes: 8 additions & 4 deletions autobot-backend/llc/kb/artifact_ingestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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:<id>`` 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])

Expand Down Expand Up @@ -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),
Expand Down
7 changes: 5 additions & 2 deletions autobot-backend/llc/kb/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
"""

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -134,7 +137,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,
)
Expand Down
12 changes: 4 additions & 8 deletions autobot-backend/llc/kb/sprint_summarizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 5 additions & 2 deletions autobot-backend/llc/kb/work_item_kb.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -168,7 +168,10 @@ async def _upsert(
# #19519: the KB client maps ``:`` to a ChromaDB-valid name; the raw
# client passes ``work_item:<id>`` 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],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,39 +100,20 @@ 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."""
ensure = AsyncMock()
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(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()
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)."""
Expand Down
54 changes: 54 additions & 0 deletions autobot-backend/llc/tests/test_kb_collections_lazy_19725.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 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_<id>`` 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_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"))]
assert offenders == [], "use company_collection(), project_collection() and the others in llc/kb/collections.py"
16 changes: 15 additions & 1 deletion autobot-backend/llc/tests/test_sprint_summarizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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."""
Expand Down
6 changes: 3 additions & 3 deletions scripts/python_file_size_known_large.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down