Skip to content

Commit b875a06

Browse files
fix(api): defer client errors past request span
Caller-visible 400/409 responses no longer exit the Logfire request span as exceptions, keeping locator content out of span exception telemetry. Unexpected 5xx failures remain in-span failures. Signed-off-by: Steven Huang <[email protected]>
1 parent 785cb55 commit b875a06

2 files changed

Lines changed: 87 additions & 57 deletions

File tree

‎src/basic_memory/api/v2/routers/memory_router.py‎

Lines changed: 65 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,56 @@ async def get_memory_context(
180180
Returns:
181181
GraphContext with the entity and its related context
182182
"""
183+
deferred_http_error: tuple[int, str, BaseException] | None = None
184+
result: GraphContext | None = None
185+
186+
async def _build_context() -> GraphContext | None:
187+
nonlocal deferred_http_error
188+
since = parse_timeframe(timeframe) if timeframe else None
189+
limit = page_size
190+
offset = (page - 1) * page_size
191+
192+
with logfire.span(
193+
"api.memory.build_context.build_context",
194+
domain="memory",
195+
action="build_context",
196+
phase="build_context",
197+
page=page,
198+
page_size=page_size,
199+
):
200+
try:
201+
context = await context_service.build_context(
202+
memory_url,
203+
depth=depth,
204+
since=since,
205+
limit=limit,
206+
offset=offset,
207+
max_related=max_related,
208+
include_observations=include_observations,
209+
)
210+
except AmbiguousIdentifierError as exc:
211+
# A title URL that names several notes has no single context to build.
212+
# Defer the caller-visible 409 past this span so Logfire does not
213+
# record the locator content as an exception.
214+
deferred_http_error = (status.HTTP_409_CONFLICT, str(exc), exc)
215+
return None
216+
217+
with logfire.span(
218+
"api.memory.build_context.shape_response",
219+
domain="memory",
220+
action="build_context",
221+
phase="shape_response",
222+
result_count=len(context.results),
223+
):
224+
async with db.scoped_session(session_maker) as session:
225+
return await to_graph_context(
226+
context,
227+
entity_repository=entity_repository,
228+
session=session,
229+
page=page,
230+
page_size=page_size,
231+
)
232+
183233
with logfire.span(
184234
"api.request.memory.build_context",
185235
entrypoint="api",
@@ -200,57 +250,12 @@ async def get_memory_context(
200250
# Why: normalize_memory_url raises ValueError for caller input; letting
201251
# it escape reported a client mistake as an internal server error (#1879).
202252
# Outcome: a bounded 400 with the normalizer's specific reason before
203-
# any context traversal.
204-
raise HTTPException(
205-
status_code=status.HTTP_400_BAD_REQUEST,
206-
detail=str(exc),
207-
) from exc
208-
209-
since = parse_timeframe(timeframe) if timeframe else None
210-
limit = page_size
211-
offset = (page - 1) * page_size
212-
213-
with logfire.span(
214-
"api.memory.build_context.build_context",
215-
domain="memory",
216-
action="build_context",
217-
phase="build_context",
218-
page=page,
219-
page_size=page_size,
220-
):
221-
try:
222-
context = await context_service.build_context(
223-
memory_url,
224-
depth=depth,
225-
since=since,
226-
limit=limit,
227-
offset=offset,
228-
max_related=max_related,
229-
include_observations=include_observations,
230-
)
231-
except AmbiguousIdentifierError as exc:
232-
# A title URL that names several notes has no single context to build.
233-
raise HTTPException(
234-
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
235-
) from exc
236-
with logfire.span(
237-
"api.memory.build_context.shape_response",
238-
domain="memory",
239-
action="build_context",
240-
phase="shape_response",
241-
result_count=len(context.results),
242-
):
243-
async with db.scoped_session(session_maker) as session:
244-
result = await to_graph_context(
245-
context,
246-
entity_repository=entity_repository,
247-
session=session,
248-
page=page,
249-
page_size=page_size,
250-
)
253+
# any context traversal or span exception.
254+
deferred_http_error = (status.HTTP_400_BAD_REQUEST, str(exc), exc)
255+
else:
256+
result = await _build_context()
251257
except HTTPException as exc:
252-
# Malformed input (400) and ambiguous titles (409) are both caller-visible
253-
# outcomes; only a server-side status would be a failure.
258+
# Unexpected HTTP errors keep the original in-span outcome handling.
254259
span.set_attribute(
255260
"outcome",
256261
"input_rejected" if exc.status_code < 500 else "failed",
@@ -264,5 +269,13 @@ async def get_memory_context(
264269
span.set_attribute("outcome", "failed")
265270
raise
266271

267-
span.set_attribute("outcome", "success")
268-
return result
272+
span.set_attribute(
273+
"outcome",
274+
"input_rejected" if deferred_http_error is not None else "success",
275+
)
276+
277+
if deferred_http_error is not None:
278+
status_code, detail, cause = deferred_http_error
279+
raise HTTPException(status_code=status_code, detail=detail) from cause
280+
assert result is not None
281+
return result

‎tests/api/v2/test_memory_router.py‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,12 @@
2525

2626

2727
class _RecordingSpan:
28-
"""Capture the attributes the memory router ships on its root span."""
28+
"""Capture span attributes and whether the span exited with an exception."""
2929

3030
def __init__(self, name: str, attributes: dict[str, Any]) -> None:
3131
self.name = name
3232
self.attributes = attributes
33+
self.exited_with: BaseException | None = None
3334

3435
def set_attribute(self, key: str, value: Any) -> None:
3536
self.attributes[key] = value
@@ -40,7 +41,13 @@ def set_attributes(self, values: dict[str, Any]) -> None:
4041
def __enter__(self) -> "_RecordingSpan":
4142
return self
4243

43-
def __exit__(self, *exc_info: object) -> None:
44+
def __exit__(
45+
self,
46+
_exc_type: type[BaseException] | None,
47+
exc: BaseException | None,
48+
_traceback: object,
49+
) -> None:
50+
self.exited_with = exc
4451
return None
4552

4653

@@ -591,6 +598,7 @@ async def test_get_memory_context_records_input_rejected_outcome(
591598
assert root_span.attributes["outcome"] == "input_rejected"
592599
# The span carries a bounded outcome, not the caller's uploaded locator content.
593600
assert "example.invalid" not in repr(root_span.attributes)
601+
assert root_span.exited_with is None
594602

595603

596604
@pytest.mark.asyncio
@@ -604,7 +612,9 @@ async def test_get_memory_context_records_success_outcome(
604612
response = await client.get(f"{v2_project_url}/memory/test/root")
605613

606614
assert response.status_code == 200
607-
assert _root_memory_span(spans).attributes["outcome"] == "success"
615+
root_span = _root_memory_span(spans)
616+
assert root_span.attributes["outcome"] == "success"
617+
assert root_span.exited_with is None
608618

609619

610620
@pytest.mark.asyncio
@@ -626,21 +636,28 @@ async def test_get_memory_context_keeps_service_failures_as_server_errors(
626636
app.dependency_overrides.pop(get_context_service_v2_external, None)
627637

628638
assert response.status_code == 500
629-
assert _root_memory_span(spans).attributes["outcome"] == "failed"
639+
root_span = _root_memory_span(spans)
640+
assert root_span.attributes["outcome"] == "failed"
641+
assert isinstance(root_span.exited_with, RuntimeError)
630642

631643

632644
@pytest.mark.asyncio
633645
async def test_get_memory_context_preserves_ambiguous_identifier_conflict(
634646
app: FastAPI,
635647
client: AsyncClient,
636648
v2_project_url: str,
649+
monkeypatch,
637650
):
638651
"""Ambiguous identifiers keep their existing 409 conflict response."""
639652
app.dependency_overrides[get_context_service_v2_external] = lambda: _AmbiguousContextService()
640653
try:
641-
response = await client.get(f"{v2_project_url}/memory/Bean%20Origins")
654+
with _record_memory_router_spans(monkeypatch) as spans:
655+
response = await client.get(f"{v2_project_url}/memory/Bean%20Origins")
642656
finally:
643657
app.dependency_overrides.pop(get_context_service_v2_external, None)
644658

645659
assert response.status_code == 409
646660
assert "Ambiguous identifier 'Bean Origins'" in response.json()["detail"]
661+
root_span = _root_memory_span(spans)
662+
assert root_span.attributes["outcome"] == "input_rejected"
663+
assert all(span.exited_with is None for span in spans)

0 commit comments

Comments
 (0)