from app.db import Base, create_database_engine, create_session_factory from app.models.task import TaskManager from app.services import graph_builder from app.services.identity import IdentityRepository def test_graph_builder_async_task_keeps_organization_scope(monkeypatch): engine = create_database_engine("sqlite+pysqlite:///:memory:") Base.metadata.create_all(engine) factory = create_session_factory(engine) class FakeZep: def __init__(self, api_key): self.api_key = api_key class FakeThread: def __init__(self, *, target, args): self.target = target self.args = args self.daemon = False def start(self): return None monkeypatch.setattr(graph_builder, "Zep", FakeZep) monkeypatch.setattr(graph_builder.threading, "Thread", FakeThread) try: with factory() as session: organization = IdentityRepository(session).create_organization( name="Graph Builder Tests", slug="graph-builder-tests" ) session.commit() builder = graph_builder.GraphBuilderService( api_key="unit-test-placeholder", organization_id=organization.id, session_factory=factory, ) task_id = builder.build_graph_async("seed text", {"entity_types": []}) task = TaskManager(session_factory=factory).get_task( task_id, organization_id=organization.id ) assert task is not None assert task.metadata["organization_id"] == organization.id finally: TaskManager.configure(None) engine.dispose()