fleet-memory/hindsight-api-slim/tests/test_search_trace.py
Nicolò Boschi 15ea23d5d6
feat: introduce hindsight-api-slim and hindsight-all-slim packages (#560)
* feat: introduce hindsight-api-slim and hindsight-all-slim packages

Closes #552

- Move all source code from hindsight-api/ to new hindsight-api-slim/
- hindsight-api-slim has heavy ML deps (torch, sentence-transformers,
  transformers, einops, flashrank, mlx, mlx-lm, safetensors) and
  pg0-embedded as optional extras: [local-ml], [embedded-db], [all]
- hindsight-api becomes a zero-code meta-package depending on
  hindsight-api-slim[all] for full backward compatibility
- Add hindsight-all-slim meta-package: hindsight-api-slim + client + embed
- hindsight-all updated to depend on hindsight-api-slim[all]
- pg0.py: lazy-import pg0 with clear ImportError pointing to [embedded-db]
- Dockerfile: replace sed hack with proper uv sync --extra flags
- Update release.yml, test.yml, lint.sh, release.sh, CLAUDE.md and
  all path references throughout the repo

* refactor: rename hindsight/ directory to hindsight-all/

* docs: document hindsight-api-slim and hindsight-all-slim package variants

Add package variants table and extras explanation to installation.md

* docs: remove emojis from installation.md, use professional tone

* docs: link Docker slim variant to pip package variants section

* docs: consolidate Docker image variants into single table

* ci: fix working-directory paths after package restructure

- Replace all hindsight-api → hindsight-api-slim in test.yml
- Replace hindsight → hindsight-all in test.yml
- Add --extra embedded-db to test-embed API install step

* ci: add local-ml and embedded-db extras to API sync steps

These extras were previously implicit in the old hindsight-api package
(which bundled everything). Now that hindsight-api-slim uses optional
extras, we must explicitly request local-ml and embedded-db in CI.

* ci: add API install step with embedded-db to test-embed smoke test

The smoke test starts hindsight-api as a daemon, which requires pg0-embedded.
Add a dedicated install step for hindsight-api-slim with embedded-db extra
so the daemon can start successfully.

* ci: remove --no-install-project when using optional extras

When --no-install-project is combined with --extra, the optional deps
are not installed because extras require the project to be active.
Remove --no-install-project from steps that need local-ml or embedded-db.

* ci: fix ordering of uv sync steps to preserve optional extras

When uv sync runs for a different workspace member, it removes optional
extras installed for other members. Fix by always running extra-requiring
API sync last, after other workspace member syncs.

Also remove --no-install-project from embedded-db sync in test-embed,
as --no-install-project prevents optional extras from being active.

* ci: add local-ml extra to test-embed API install for smoke test

The smoke test starts the full API server which needs sentence-transformers
for local embeddings (default provider). Add local-ml extra to the install.

* ci: simplify extras with --all-extras and add slim pip smoke test

- Replace explicit --extra local-ml --extra embedded-db with --all-extras
  for cleaner, more maintainable sync steps
- Add test-pip-slim job: tests hindsight-api-slim[embedded-db] without
  local ML models, using Cohere for embeddings/reranking (mirrors Docker
  slim smoke test approach)

* ci: simplify slim smoke test to health check only (mirrors Docker test)
2026-03-13 13:50:03 +01:00

146 lines
5.7 KiB
Python

"""
Test search tracing functionality.
"""
import pytest
from hindsight_api.engine.memory_engine import Budget
from hindsight_api import SearchTrace, RequestContext
from datetime import datetime, timezone
@pytest.mark.asyncio
async def test_search_with_trace(memory, request_context):
"""Test that search with enable_trace=True returns a valid SearchTrace."""
# Generate a unique agent ID for this test
bank_id = f"test_trace_{datetime.now(timezone.utc).timestamp()}"
try:
# Store some test memories
await memory.retain_async(
bank_id=bank_id,
content="Alice works at Google in Mountain View",
context="test context",
request_context=request_context,
)
await memory.retain_async(
bank_id=bank_id,
content="Bob also works at Google but in New York",
context="test context",
request_context=request_context,
)
await memory.retain_async(
bank_id=bank_id,
content="Charlie founded a startup called TechCorp",
context="test context",
request_context=request_context,
)
# Search with tracing enabled
search_result = await memory.recall_async(
bank_id=bank_id,
query="Who works at Google?",
fact_type=["world"],
budget=Budget.LOW, # 20,
max_tokens=512,
enable_trace=True,
request_context=request_context,
)
# Verify results
assert len(search_result.results) > 0, "Should have search results"
# Verify trace object
assert search_result.trace is not None, "Trace should not be None when enable_trace=True"
# Trace is now a dict
trace = search_result.trace
# Verify query info
assert trace["query"]["query_text"] == "Who works at Google?"
assert trace["query"]["budget"] == 100 # Budget.LOW = 100
assert trace["query"]["max_tokens"] == 512
assert len(trace["query"]["query_embedding"]) > 0, "Query embedding should be populated"
# Verify entry points
assert len(trace["entry_points"]) > 0, "Should have entry points"
for ep in trace["entry_points"]:
assert ep["node_id"], "Entry point should have node_id"
assert ep["text"], "Entry point should have text"
assert 0.0 <= ep["similarity_score"] <= 1.0, "Similarity should be in [0, 1]"
# Verify visits
assert len(trace["visits"]) > 0, "Should have visited nodes"
for visit in trace["visits"]:
assert visit["node_id"], "Visit should have node_id"
assert visit["text"], "Visit should have text"
assert visit["weights"]["final_weight"] >= 0, "Weight should be non-negative"
# Entry points should have no parent
if visit["is_entry_point"]:
assert visit["parent_node_id"] is None
assert visit["link_type"] is None
else:
# Non-entry points should have parent info (unless they're isolated)
# But we allow None parent if the node was reached differently
pass
# Verify summary
assert trace["summary"]["total_nodes_visited"] == len(trace["visits"])
assert trace["summary"]["results_returned"] == len(search_result.results)
assert trace["summary"]["budget_used"] <= trace["query"]["budget"]
assert trace["summary"]["total_duration_seconds"] > 0
# Verify phase metrics
assert len(trace["summary"]["phase_metrics"]) > 0, "Should have phase metrics"
phase_names = {pm["phase_name"] for pm in trace["summary"]["phase_metrics"]}
assert "generate_query_embedding" in phase_names
assert "parallel_retrieval" in phase_names # New modular architecture
assert "rrf_merge" in phase_names # New modular architecture
assert "reranking" in phase_names # New modular architecture
print("\n✓ Search trace test passed!")
print(f" - Query: {trace['query']['query_text']}")
print(f" - Entry points: {len(trace['entry_points'])}")
print(f" - Nodes visited: {trace['summary']['total_nodes_visited']}")
print(f" - Nodes pruned: {trace['summary']['total_nodes_pruned']}")
print(f" - Results returned: {trace['summary']['results_returned']}")
print(f" - Duration: {trace['summary']['total_duration_seconds']:.3f}s")
finally:
# Cleanup
await memory.delete_bank(bank_id, request_context=request_context)
@pytest.mark.asyncio
async def test_search_without_trace(memory, request_context):
"""Test that search with enable_trace=False returns None for trace."""
bank_id = f"test_no_trace_{datetime.now(timezone.utc).timestamp()}"
try:
# Store a test memory
await memory.retain_async(
bank_id=bank_id,
content="Test memory without trace",
context="test",
request_context=request_context,
)
# Search without tracing
search_result = await memory.recall_async(
bank_id=bank_id,
query="test",
fact_type=["world"],
budget=Budget.LOW, # 10,
max_tokens=512,
enable_trace=False,
request_context=request_context,
)
# Verify trace is None
assert search_result.trace is None, "Trace should be None when enable_trace=False"
assert isinstance(search_result.results, list), "Results should still be a list"
print("\n✓ Search without trace test passed!")
finally:
# Cleanup
await memory.delete_bank(bank_id, request_context=request_context)