diff --git a/server/memory/app/entity_communities.py b/server/memory/app/entity_communities.py index 979c8fc483..8105c9780a 100644 --- a/server/memory/app/entity_communities.py +++ b/server/memory/app/entity_communities.py @@ -151,6 +151,8 @@ class EntityCommunitiesResult: # giant_share of the entities at hub_drop_max_fraction (written anyway). hub_fraction_used: dict[str, float] = field(default_factory=dict) giant: list[str] = field(default_factory=list) + # "org/ns" of each namespace whose read, partition or write raised; the pass carries on. + failed: list[str] = field(default_factory=list) # The graph reads that render communities for any namespace. @@ -326,33 +328,45 @@ async def run_entity_communities( now = naive_utc_now() for org, ns in await _namespaces_with_edges(ch, cfg): pass_context.check_stop() - raw = await _edges(ch, org, ns, cfg) - if len(raw) > cfg.max_edges_per_namespace: - # Keep the strongest max_edges pairs (the read is - # weight-descending), as the Graph page does. - raw = raw[: cfg.max_edges_per_namespace] - result.truncated[f"{org}/{ns}"] = True - log.info( - "entity_communities: %s/%s over %d pairs; strongest %d kept (min weight %s)", - org, - ns, - cfg.max_edges_per_namespace, - len(raw), - raw[-1]["w"] if raw else None, - ) - edges = [(str(r["entity_a"]), str(r["entity_b"]), float(r["w"] or 0)) for r in raw] - # Hub drop + propagation (escalated up to ~5 partitions) is seconds - # of CPU on a max_edges graph: run it in a thread so the loop keeps - # serving requests and other workers. Only this coroutine touches - # `result`, and it is suspended while the thread writes to it. - rows, comms = await asyncio.to_thread(_partition, org, ns, edges, cfg, result, now) - pass_context.check_stop() # the thread ran on past a lost lease - if not rows: + key = f"{org}/{ns}" + try: + raw = await _edges(ch, org, ns, cfg) + if len(raw) > cfg.max_edges_per_namespace: + # Keep the strongest max_edges pairs (the read is + # weight-descending), as the Graph page does. + raw = raw[: cfg.max_edges_per_namespace] + result.truncated[key] = True + log.info( + "entity_communities: %s/%s over %d pairs; strongest %d kept (min weight %s)", + org, + ns, + cfg.max_edges_per_namespace, + len(raw), + raw[-1]["w"] if raw else None, + ) + edges = [(str(r["entity_a"]), str(r["entity_b"]), float(r["w"] or 0)) for r in raw] + # Hub drop + propagation (escalated up to ~5 partitions) is seconds + # of CPU on a max_edges graph: run it in a thread so the loop keeps + # serving requests and other workers. Only this coroutine touches + # `result`, and it is suspended while the thread writes to it. + rows, comms = await asyncio.to_thread(_partition, org, ns, edges, cfg, result, now) + pass_context.check_stop() # the thread ran on past a lost lease + if not rows: + continue + await ch.insert(TABLE, rows, settings={"async_insert": 0, "wait_for_async_insert": 1}) + # PassStopped and a cancel are BaseExceptions: they still end the pass. + except Exception as e: # one namespace's failure must not skip the rest + # The result names a namespace that raised only in `failed`. + for recorded in (result.truncated, result.hubs_dropped, result.hub_fraction_used): + recorded.pop(key, None) + result.giant[:] = [g for g in result.giant if g != key] + result.failed.append(key) + log.warning("entity_communities: %s/%s failed", org, ns, exc_info=True) + pass_context.note_failure(e, key) continue - await ch.insert(TABLE, rows, settings={"async_insert": 0, "wait_for_async_insert": 1}) result.namespaces += 1 result.rows_written += len(rows) - result.per_namespace[f"{org}/{ns}"] = len(comms) + result.per_namespace[key] = len(comms) return result diff --git a/server/memory/workers/entity_communities.py b/server/memory/workers/entity_communities.py index e1a596fa8f..b6a4f5b1d6 100644 --- a/server/memory/workers/entity_communities.py +++ b/server/memory/workers/entity_communities.py @@ -44,13 +44,16 @@ async def run_pass() -> EntityCommunitiesResult: "truncated": len(result.truncated), "hub_escalated": len(result.hub_fraction_used), "giant": len(result.giant), + "failed": len(result.failed), } log.info( - "entity communities pass: namespaces=%d rows=%d truncated=%d escalated=%d giant=%d", + "entity communities pass: namespaces=%d rows=%d truncated=%d escalated=%d giant=%d " + "failed=%d", result.namespaces, result.rows_written, len(result.truncated), len(result.hub_fraction_used), len(result.giant), + len(result.failed), ) return result diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 3a288f0589..10408318e3 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -296,6 +296,7 @@ server/memory/app/embedder_calibration.py::calibrate_embedder::2 server/memory/app/embedder_calibration.py::get_namespace_calibration_stored_key::1 logged_only_nonanswer # the code_calibration worker's key check server/memory/app/embedder_calibration.py::publish_calibration::1 write server/memory/app/embedder_calibration.py::refresh_shared::1 logged_only_nonanswer +server/memory/app/entity_communities.py::run_entity_communities::1 logged_only_nonanswer server/memory/app/entity_resolution.py::resolve_entities_for_write::1 write server/memory/app/entity_resolution.py::resolve_entities_for_write::2 write server/memory/app/expiry.py::_after_expiry::1 write diff --git a/tests/unit/test_entity_communities.py b/tests/unit/test_entity_communities.py index 3da97000f1..db525c342e 100644 --- a/tests/unit/test_entity_communities.py +++ b/tests/unit/test_entity_communities.py @@ -5,19 +5,26 @@ from __future__ import annotations import asyncio +import contextlib +import dataclasses from datetime import datetime +from types import SimpleNamespace from typing import Any from unittest.mock import patch import pytest +from server.memory.app import entity_communities as ec from server.memory.app.entity_communities import ( EntityCommunitiesConfig, + EntityCommunitiesResult, label_propagation, rows_for_namespace, run_entity_communities, summarize_communities, ) +from server.workers import pass_context +from tests.unit.test_entity_communities_walked import _fused_graph def _clique(names: list[str], w: float = 1.0) -> list[tuple[str, str, float]]: @@ -129,9 +136,7 @@ async def test_worker_pass_partitions_off_the_event_loop() -> None: """Hub drop + label propagation is seconds of CPU on a 200k-edge namespace; run inline it stalls every request and worker sharing the loop. The partition must run in a thread with no running loop.""" - from server.memory.app import entity_communities as svc - - real = svc._partition + real = ec._partition seen: list[bool] = [] def spy(*args: Any, **kwargs: Any) -> Any: @@ -146,12 +151,96 @@ def spy(*args: Any, **kwargs: Any) -> Any: namespaces=[{"org": "o", "namespace": "n"}], edges={"n": [{"entity_a": "a", "entity_b": "b", "w": 2}]}, ) - with patch.object(svc, "_partition", spy): + with patch.object(ec, "_partition", spy): res = await run_entity_communities(EntityCommunitiesConfig(walked_days=0), ch=ch) assert seen == [False] assert res.rows_written == 2 +class _FailingCH(_StubCH): + """Raises on one namespace's edge read or on its write.""" + + def __init__(self, fail_ns: str, fail_at: str, **kw: Any) -> None: + super().__init__(**kw) + self.fail_ns, self.fail_at = fail_ns, fail_at + + async def query_all(self, sql, params=None): + if self.fail_at == "read" and "sum(co_occur)" in sql and params["ns"] == self.fail_ns: + raise RuntimeError("edge read failed") + return await super().query_all(sql, params) + + async def insert(self, table, rows, settings=None): + if self.fail_at == "write" and rows[0]["namespace"] == self.fail_ns: + raise RuntimeError("write failed") + await super().insert(table, rows, settings) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fail_at", ["read", "partition", "write"]) +async def test_a_failing_namespace_does_not_skip_the_rest_of_the_pass( + fail_at: str, monkeypatch +) -> None: + """The namespaces come in a stable order, so one whose edge read, partition or write + raises would end every pass before the namespaces after it. The failure is noted on + the pass, the later namespaces are still written, and the result names the failed + namespace only in `failed`: with that cleared, it equals a clean pass over the other + namespace alone.""" + namespaces = [{"org": "o", "namespace": "a"}, {"org": "o", "namespace": "b"}] + # `o/a` keeps its strongest pairs and is fused: a pass that writes it records its + # truncation, its dropped hub, its escalated fraction and its giant community. + edges = { + "a": [*_fused_graph(), {"entity_a": "x", "entity_b": "y", "w": 0}], + "b": [{"entity_a": "b1", "entity_b": "b2", "w": 1}], + } + cfg = EntityCommunitiesConfig( + walked_days=0, + max_edges_per_namespace=len(_fused_graph()), + hub_drop_fraction=0.02, + hub_drop_max_fraction=0.04, + ) + whole = await run_entity_communities(cfg, ch=_StubCH(namespaces=namespaces[:1], edges=edges)) + assert whole.truncated and whole.hubs_dropped and whole.hub_fraction_used + assert whole.giant == ["o/a"] + clean = await run_entity_communities(cfg, ch=_StubCH(namespaces=namespaces[1:], edges=edges)) + + real = ec._partition + + def partition(org, ns, edges, cfg, result, now): + out = real(org, ns, edges, cfg, result, now) + if fail_at == "partition" and ns == "a": + raise RuntimeError("partition failed") + return out + + monkeypatch.setattr(ec, "_partition", partition) + ch = _FailingCH("a", fail_at, namespaces=namespaces, edges=edges) + ctx = pass_context.begin("entity_communities") + try: + res = await run_entity_communities(cfg, ch=ch) + finally: + pass_context.clear() + assert [(t, sorted(r["entity"] for r in rows)) for t, rows in ch.inserted] == [ + ("loom.entity_communities", ["b1", "b2"]) + ] + assert res.failed == ["o/a"] + assert dataclasses.replace(res, failed=[]) == clean + assert ctx.count == 1 and ctx.failures[0][:2] == ("o/a", "RuntimeError") + + +@pytest.mark.asyncio +async def test_the_worker_outcome_counts_failed_namespaces(monkeypatch) -> None: + from server.memory.workers import entity_communities as worker + + rec = SimpleNamespace() + + async def run(cfg): + return EntityCommunitiesResult(namespaces=1, failed=["o/a"]) + + monkeypatch.setattr(worker, "record_pass", lambda name: contextlib.nullcontext(rec)) + monkeypatch.setattr(worker, "run_entity_communities", run) + await worker.run_pass() + assert rec.outcome["namespaces"] == 1 and rec.outcome["failed"] == 1 + + def test_worker_is_registered_default_off() -> None: from server.settings import settings from server.workers.registry import worker_meta