Skip to content

Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.

fix: complete source-scope support for AutoSet and RAG method overrides

yifanfeng97f6d45f3428b5
diff --git a/hyperextract/cli/cli.py b/hyperextract/cli/cli.py
index 4e0ac22..75e3108 100644
--- a/hyperextract/cli/cli.py
+++ b/hyperextract/cli/cli.py
@@ -766,6 +766,7 @@ def info(
(path / "sources_nodes.json", "nodes"),
(path / "sources_edges.json", "edges"),
(path / "sources_chunks.json", "chunks"),
+ (path / "sources_items.json", "items"),
]
combined: dict = {}
for ledger_path, _kind in ledger_files:
@@ -853,6 +854,20 @@ def search(
scope_kwargs["source_ids"] = list(source)
if tag:
scope_kwargs["tags"] = list(tag)
+ if scope_kwargs:
+ # Fail with a clear message when the KA type has no ledger
+ # (e.g. AutoList/AutoModel) instead of a raw TypeError.
+ import inspect
+
+ search_params = inspect.signature(type(ka).search).parameters
+ for flag, key in (("--source", "source_ids"), ("--tag", "tags")):
+ if key in scope_kwargs and key not in search_params:
+ console.print(
+ f"[red]Error:[/red] Scoped search ({flag}) is not "
+ f"supported by {type(ka).__name__} knowledge "
+ "abstracts (no source ledger)."
+ )
+ raise typer.Exit(1)
results = ka.search(query, top_k=top_k, **scope_kwargs)
logger.info("stage=search_complete results=%d", len(results))
@@ -1484,6 +1499,8 @@ def remove_items(
"remerged_edges",
"removed_chunks",
"remerged_chunks",
+ "removed_items",
+ "remerged_items",
)
)
if not changed_any:
diff --git a/hyperextract/methods/rag/cog_rag.py b/hyperextract/methods/rag/cog_rag.py
index 6b17e55..e174f9c 100644
--- a/hyperextract/methods/rag/cog_rag.py
+++ b/hyperextract/methods/rag/cog_rag.py
@@ -398,19 +398,34 @@ class Cog_RAG:
self.theme_layer.build_index()
self.detail_layer.build_index()
- def search(self, query: str, top_k_themes: int = 3, top_k_entities: int = 3):
+ def search(
+ self,
+ query: str,
+ top_k_themes: int = 3,
+ top_k_entities: int = 3,
+ *,
+ source_ids: list[str] | None = None,
+ tags: list[str] | None = None,
+ ):
"""
Dual-Layer Search.
Strategy:
1. Macro: Search for Themes in ThemeLayer (Edge-First).
2. Micro: Search for Entities in DetailLayer (Node-First).
+
+ Scope (source_ids/tags) is forwarded to both layers when the
+ corresponding sources were attributed on them.
"""
# 1. Macro Context: Themes
- themes = self.theme_layer.search_edges(query, top_k=top_k_themes)
+ themes = self.theme_layer.search_edges(
+ query, top_k=top_k_themes, source_ids=source_ids, tags=tags
+ )
# 2. Micro Context: Entities (Nodes)
# Note: The user requested searching for "Specific Entities" in the second step.
- entities = self.detail_layer.search_nodes(query, top_k=top_k_entities)
+ entities = self.detail_layer.search_nodes(
+ query, top_k=top_k_entities, source_ids=source_ids, tags=tags
+ )
return {"themes": themes, "entities": entities}
diff --git a/hyperextract/methods/rag/graph_rag.py b/hyperextract/methods/rag/graph_rag.py
index c9ad5fe..e2d21f0 100644
--- a/hyperextract/methods/rag/graph_rag.py
+++ b/hyperextract/methods/rag/graph_rag.py
@@ -543,6 +543,9 @@ class Graph_RAG(AutoGraph[NodeSchema, EdgeSchema]):
top_k_edges: int = 3,
top_k: int | None = None,
use_community: bool = False,
+ *,
+ source_ids: list[str] | None = None,
+ tags: list[str] | None = None,
) -> tuple[list, list, dict | None]:
"""Unified graph search interface with optional community enhancement.
@@ -553,15 +556,23 @@ class Graph_RAG(AutoGraph[NodeSchema, EdgeSchema]):
top_k: If provided, sets both top_k_nodes and top_k_edges to this value.
use_community: If True, enables community-aware search.
Requires networkx and graspologic. Default: False.
+ source_ids: Optional scope — only knowledge contributed by these
+ source documents (requires track_sources ledgers).
+ tags: Optional scope — only knowledge from sources carrying any
+ of these tags.
Returns:
Tuple of (nodes, edges, community_context).
community_context is None when use_community=False.
"""
if use_community:
- return self._global_search_impl(query, top_k_nodes, top_k_edges)
+ return self._global_search_impl(
+ query, top_k_nodes, top_k_edges, source_ids=source_ids, tags=tags
+ )
# Keep the 3-tuple contract: no community context in the default path.
- nodes, edges = super().search(query, top_k_nodes, top_k_edges, top_k)
+ nodes, edges = super().search(
+ query, top_k_nodes, top_k_edges, top_k, source_ids=source_ids, tags=tags
+ )
return nodes, edges, None
def _global_search_impl(
@@ -569,6 +580,9 @@ class Graph_RAG(AutoGraph[NodeSchema, EdgeSchema]):
query: str,
top_k_nodes: int = 3,
top_k_edges: int = 3,
+ *,
+ source_ids: list[str] | None = None,
+ tags: list[str] | None = None,
) -> tuple[list, list, dict]:
"""Internal implementation for community-enhanced search."""
if not self.community_reports:
@@ -577,7 +591,9 @@ class Graph_RAG(AutoGraph[NodeSchema, EdgeSchema]):
self.build_communities()
community_context = self._get_community_context_for_query(query)
- nodes, edges = super().search(query, top_k_nodes, top_k_edges)
+ nodes, edges = super().search(
+ query, top_k_nodes, top_k_edges, source_ids=source_ids, tags=tags
+ )
return nodes, edges, community_context
diff --git a/hyperextract/types/set.py b/hyperextract/types/set.py
index 007ab85..95e35b0 100644
--- a/hyperextract/types/set.py
+++ b/hyperextract/types/set.py
@@ -295,13 +295,110 @@ class AutoSet(BaseAutoType[AutoSetSchema[ItemSchema]], Generic[ItemSchema]):
Unlike the default behavior which uses merge_batch for full re-merge,
AutoSet optimizes this by directly adding items to OMem, which
handles deduplication and merging internally.
+
+ When parse/feed_text attributed a source, the raw items are recorded
+ in the ledger so the document can later be rolled back or scoped.
"""
+ source_id = getattr(self, "_pending_source_id", None)
+ if source_id is not None:
+ self._data_memory.record_source(
+ source_id,
+ [],
+ content_hash=getattr(self, "_pending_content_hash", None),
+ )
if self.empty():
self._set_data_state(incoming_data)
elif incoming_data.items:
- self._data_memory.add(incoming_data.items)
+ self._data_memory.add(incoming_data.items, source_id=source_id)
self.clear_index()
+ # ==================== Source Provenance ====================
+
+ def _adopt_source_ledger(self, other: "AutoSet", source_id: str) -> None:
+ """Transfer the ledger entry for ``source_id`` from ``other``."""
+ if source_id in other._data_memory._sources:
+ self._data_memory._sources[source_id] = other._data_memory._sources[
+ source_id
+ ]
+
+ def _dump_provenance(self, root: Path) -> None:
+ """Persist the item source ledger alongside the KA."""
+ try:
+ self._data_memory.dump_sources(Path(root) / "sources_items.json")
+ except Exception as e:
+ logger.warning("provenance_dump_failed", error=str(e))
+
+ def _load_provenance(self, root: Path) -> None:
+ """Restore the item source ledger alongside the KA."""
+ try:
+ ledger_path = Path(root) / "sources_items.json"
+ if ledger_path.exists():
+ self._data_memory.load_sources(ledger_path)
+ except Exception as e:
+ logger.warning("provenance_load_failed", error=str(e))
+
+ def feed_text(
+ self,
+ text: str,
+ *,
+ source_id: str | None = None,
+ content_hash: str | None = None,
+ ) -> "AutoSet":
+ """Feed text with document-level upsert semantics.
+
+ When ``source_id`` was attributed before, the previous version's
+ items are rolled back first (exact re-merge from surviving sources),
+ so content removed from the updated document does not linger.
+ """
+ if (
+ source_id
+ and self._data_memory.track_sources
+ and source_id in self._data_memory.sources()
+ ):
+ logger.info("stage=source_upsert rollback source=%s", source_id)
+ self._data_memory.remove_source(source_id)
+ return super().feed_text(text, source_id=source_id, content_hash=content_hash)
+
+ def sources(self) -> dict[str, dict[str, Any]]:
+ """Summarize the source ledger."""
+ return {
+ source_id: dict(info)
+ for source_id, info in self._data_memory.sources().items()
+ }
+
+ def source_content_hash(self, source_id: str) -> str | None:
+ """Return the recorded content hash of a source (None if unknown)."""
+ record = self._data_memory._sources.get(source_id)
+ return record.content_hash if record else None
+
+ def source_tags(self, source_id: str) -> list[str]:
+ """Return the tags of one source (empty if unknown/untagged)."""
+ return self._data_memory.source_tags(source_id)
+
+ def tag_source(
+ self,
+ source_id: str,
+ *,
+ add: list[str] | None = None,
+ remove: list[str] | None = None,
+ ) -> list[str]:
+ """Add/remove tags on one source. Returns the resulting tag list."""
+ return self._data_memory.tag_source(source_id, add=add, remove=remove)
+
+ def remove_source(self, source_id: str, *, strategy: str = "exact") -> dict:
+ """Remove every item contributed by one source document.
+
+ Items shared with other documents are re-merged from the surviving
+ sources' raw contents. The search index is patched in place when built.
+ """
+ report = self._data_memory.remove_source(source_id, strategy=strategy)
+ return {
+ "source_id": source_id,
+ "removed_items": report["removed_keys"],
+ "remerged_items": report["remerged_keys"],
+ "index_patched": report["index_patched"],
+ }
+
# ==================== Core Override Methods ====================
def merge_batch_data(
diff --git a/tests/cli/test_parse_input_types.py b/tests/cli/test_parse_input_types.py
index aff46eb..9459a8a 100644
--- a/tests/cli/test_parse_input_types.py
+++ b/tests/cli/test_parse_input_types.py
@@ -141,9 +141,7 @@ class TestParseInputTypes:
ka.feed_text.assert_not_called()
ka.dump.assert_not_called()
- def test_document_without_backend_rejected_with_hint(
- self, tmp_path, monkeypatch
- ):
+ def test_document_without_backend_rejected_with_hint(self, tmp_path, monkeypatch):
monkeypatch.setattr(
"hyperextract.cli.utils.markitdown_available", lambda: False
)
diff --git a/tests/cli/test_template_validate.py b/tests/cli/test_template_validate.py
index 6143df2..e64dc76 100644
--- a/tests/cli/test_template_validate.py
+++ b/tests/cli/test_template_validate.py
@@ -70,7 +70,9 @@ class TestTemplateValidateCli:
assert "OK" in result.output
def test_identifier_error_exits_one(self, tmp_path):
- path = _write(tmp_path, VALID_GRAPH.replace("entity_id: name", "entity_id: nope"))
+ path = _write(
+ tmp_path, VALID_GRAPH.replace("entity_id: name", "entity_id: nope")
+ )
result = runner.invoke(app, ["template", "validate", str(path)])
assert result.exit_code == 1
assert "HE-T003" in result.output
@@ -141,16 +143,20 @@ class TestTemplateValidateCli:
education = [
item
for item in payload["results"]
- if item["file"].replace("\\", "/").endswith(
- ("course_concept_graph.yaml", "curriculum_structure.yaml")
- )
+ if item["file"]
+ .replace("\\", "/")
+ .endswith(("course_concept_graph.yaml", "curriculum_structure.yaml"))
]
assert len(education) == 2
assert all(item["ok"] for item in education)
def test_batch_json_wraps_results(self, tmp_path):
_write(tmp_path, VALID_GRAPH, name="a.yaml")
- _write(tmp_path, VALID_GRAPH.replace("name: ValidGraph", "name: Other"), name="b.yaml")
+ _write(
+ tmp_path,
+ VALID_GRAPH.replace("name: ValidGraph", "name: Other"),
+ name="b.yaml",
+ )
result = runner.invoke(
app, ["template", "validate", str(tmp_path), "--all", "--json"]
)
diff --git a/tests/conftest.py b/tests/conftest.py
index 00411f7..27198d6 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -39,7 +39,9 @@ def is_real_env() -> bool:
"""Fixture indicating whether tests should use real API or mock."""
has_key = _has_openai_key()
if has_key:
- print("\n\n[PYTEST CONFIG] 🔌 Real OpenAI API detected - Using REAL LLM & Embeddings")
+ print(
+ "\n\n[PYTEST CONFIG] 🔌 Real OpenAI API detected - Using REAL LLM & Embeddings"
+ )
else:
print("\n\n[PYTEST CONFIG] 🎭 No API key found - Using MOCK LLM & Embeddings")
return has_key
diff --git a/tests/fixtures/documents/make_fixtures.py b/tests/fixtures/documents/make_fixtures.py
index 482ad5d..980aede 100644
--- a/tests/fixtures/documents/make_fixtures.py
+++ b/tests/fixtures/documents/make_fixtures.py
@@ -27,8 +27,11 @@ def make_pdf(path: Path, text: str | None) -> None:
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
b"/Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>"
),
- b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n"
- + stream + b"\nendstream",
+ b"<< /Length "
+ + str(len(stream)).encode()
+ + b" >>\nstream\n"
+ + stream
+ + b"\nendstream",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
]
out = b"%PDF-1.4\n"
@@ -42,8 +45,10 @@ def make_pdf(path: Path, text: str | None) -> None:
for off in offsets:
out += f"{off:010d} 00000 n \n".encode()
out += (
- b"trailer\n<< /Size " + str(len(objects) + 1).encode()
- + b" /Root 1 0 R >>\nstartxref\n" + str(xref_pos).encode()
+ b"trailer\n<< /Size "
+ + str(len(objects) + 1).encode()
+ + b" /Root 1 0 R >>\nstartxref\n"
+ + str(xref_pos).encode()
+ b"\n%%EOF\n"
)
path.write_bytes(out)
diff --git a/tests/fixtures/schemas.py b/tests/fixtures/schemas.py
index fd227a5..bd1a510 100644
--- a/tests/fixtures/schemas.py
+++ b/tests/fixtures/schemas.py
@@ -19,7 +19,9 @@ class CompanySchema(BaseModel):
name: str = Field(description="Company name")
industry: Optional[str] = Field(default=None, description="Industry sector")
founded_year: Optional[int] = Field(default=None, description="Year founded")
- headquarters: Optional[str] = Field(default=None, description="Headquarters location")
+ headquarters: Optional[str] = Field(
+ default=None, description="Headquarters location"
+ )
class EntitySchema(BaseModel):
@@ -36,7 +38,9 @@ class RelationSchema(BaseModel):
source: str = Field(description="Source entity name")
target: str = Field(description="Target entity name")
relation_type: str = Field(description="Type of relationship")
- description: Optional[str] = Field(default=None, description="Relationship description")
+ description: Optional[str] = Field(
+ default=None, description="Relationship description"
+ )
class KeywordSchema(BaseModel):
@@ -63,7 +67,9 @@ class BiographySchema(BaseModel):
birth_date: Optional[str] = Field(default=None, description="Date of birth")
death_date: Optional[str] = Field(default=None, description="Date of death")
nationality: Optional[str] = Field(default=None, description="Nationality")
- occupation: List[str] = Field(default_factory=list, description="Professions/occupations")
+ occupation: List[str] = Field(
+ default_factory=list, description="Professions/occupations"
+ )
summary: str = Field(description="Brief biography summary")
@@ -73,5 +79,7 @@ class EarningsSummarySchema(BaseModel):
company_name: str = Field(description="Company name")
quarter: str = Field(description="Fiscal quarter (e.g., Q1 2024)")
revenue: Optional[float] = Field(default=None, description="Revenue in millions")
- net_income: Optional[float] = Field(default=None, description="Net income in millions")
+ net_income: Optional[float] = Field(
+ default=None, description="Net income in millions"
+ )
earnings_per_share: Optional[float] = Field(default=None, description="EPS")
diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py
index 04f0289..68d1379 100644
--- a/tests/integration/__init__.py
+++ b/tests/integration/__init__.py
@@ -11,6 +11,6 @@ pytestmark = [
pytest.mark.integration,
pytest.mark.skipif(
not pytest.importorskip("os").environ.get("OPENAI_API_KEY"),
- reason="OPENAI_API_KEY not set"
+ reason="OPENAI_API_KEY not set",
),
]
diff --git a/tests/integration/test_provenance_real.py b/tests/integration/test_provenance_real.py
index 2ec6a87..33586b9 100644
--- a/tests/integration/test_provenance_real.py
+++ b/tests/integration/test_provenance_real.py
@@ -155,8 +155,7 @@ class TestProvenanceRealAPI:
# 5. Index patched in place throughout, consistent with storage.
assert g._node_memory.has_index()
doc_keys = {
- d.metadata["key"]
- for d in g._node_memory._index.docstore._dict.values()
+ d.metadata["key"] for d in g._node_memory._index.docstore._dict.values()
}
storage_keys = {g.node_key_extractor(n) for n in g.nodes}
assert doc_keys == storage_keys, (
diff --git a/tests/integration/test_real_extraction.py b/tests/integration/test_real_extraction.py
index c2e9021..716181c 100644
--- a/tests/integration/test_real_extraction.py
+++ b/tests/integration/test_real_extraction.py
@@ -13,8 +13,7 @@ from hyperextract.types import AutoModel, AutoList, AutoSet, AutoGraph
pytestmark = [
pytest.mark.integration,
pytest.mark.skipif(
- not os.environ.get("OPENAI_API_KEY"),
- reason="OPENAI_API_KEY not set"
+ not os.environ.get("OPENAI_API_KEY"), reason="OPENAI_API_KEY not set"
),
]
@@ -33,6 +32,7 @@ def embedder():
class PersonInfo(BaseModel):
"""Schema for person information."""
+
name: str = Field(description="The person's name")
age: int = Field(description="The person's age")
occupation: str = Field(description="The person's job or occupation")
@@ -136,12 +136,14 @@ class TestAutoSetIntegration:
class NodeSchema(BaseModel):
"""Node schema for knowledge graph."""
+
name: str = Field(description="Entity name")
type: str = Field(description="Entity type")
class EdgeSchema(BaseModel):
"""Edge schema for knowledge graph."""
+
source: str = Field(description="Source entity name")
target: str = Field(description="Target entity name")
relation: str = Field(description="Relationship type")
diff --git a/tests/methods/test_chunk_rag.py b/tests/methods/test_chunk_rag.py
index ea0ae54..6c8eefb 100644
--- a/tests/methods/test_chunk_rag.py
+++ b/tests/methods/test_chunk_rag.py
@@ -28,9 +28,7 @@ def _patch_create(llm_client, embedder):
from hyperextract.utils.template_engine.factory import TemplateFactory
def _factory(source, language=None, **kwargs):
- return TemplateFactory.create(
- source, llm_client=llm_client, embedder=embedder
- )
+ return TemplateFactory.create(source, llm_client=llm_client, embedder=embedder)
return patch.object(TemplateClass, "create", side_effect=_factory)
@@ -112,7 +110,15 @@ class TestCliOnDiskKA:
):
result = runner.invoke(
app,
- ["search", str(ka_dir), "alpha loves beta", "-n", "5", "--tag", "team-b"],
+ [
+ "search",
+ str(ka_dir),
+ "alpha loves beta",
+ "-n",
+ "5",
+ "--tag",
+ "team-b",
+ ],
)
assert result.exit_code == 0, result.output
diff --git a/tests/methods/test_search_scope_forwarding.py b/tests/methods/test_search_scope_forwarding.py
new file mode 100644
index 0000000..c482eb9
--- /dev/null
+++ b/tests/methods/test_search_scope_forwarding.py
@@ -0,0 +1,84 @@
+"""Scope forwarding through method-level search overrides (#90 family).
+
+Graph_RAG.search and Cog_RAG.search override their AutoType's search and
+previously dropped source_ids/tags, so scoped search on those KAs either
+raised TypeError (CLI passes the kwargs) or silently ignored the scope.
+"""
+
+import pytest
+
+from tests.mocks import MockChatModel, MockEmbeddings
+
+from hyperextract.methods.rag import Cog_RAG, Graph_RAG
+from hyperextract.methods.rag.cog_rag import ThemeSchema
+from hyperextract.methods.rag.graph_rag import EdgeSchema, NodeSchema
+
+
+def _rag_with_ledger():
+ rag = Graph_RAG(llm_client=MockChatModel(), embedder=MockEmbeddings())
+ node = NodeSchema(name="Apple", type="org", description="d")
+ edge = EdgeSchema(source="Apple", target="Steve", description="d", strength=5)
+ rag._node_memory.add([node], source_id="d1")
+ rag._edge_memory.add([edge], source_id="d1")
+ rag.build_index()
+ return rag
+
+
+class TestGraphRagScope:
+ def test_signature_accepts_scope(self):
+ import inspect
+
+ params = inspect.signature(Graph_RAG.search).parameters
+ assert "source_ids" in params and "tags" in params
+
+ def test_scoped_search_only_returns_attributed_items(self):
+ rag = _rag_with_ledger()
+
+ nodes, edges, _ = rag.search("Apple", source_ids=["d1"])
+ assert [n.name for n in nodes] == ["Apple"]
+ assert [e.source for e in edges] == ["Apple"]
+
+ # Unknown source: nothing is in scope.
+ nodes, edges, _ = rag.search("Apple", source_ids=["nope"])
+ assert nodes == [] and edges == []
+
+ def test_community_path_forwards_scope_too(self):
+ rag = _rag_with_ledger()
+ # No community reports -> build_communities would run; point it at a
+ # frozen state so the search path (not the builder) is exercised.
+ rag.community_reports = {}
+ object.__setattr__(rag, "build_communities", lambda: None)
+
+ nodes, edges, context = rag.search(
+ "Apple", use_community=True, source_ids=["d1"]
+ )
+ assert [n.name for n in nodes] == ["Apple"]
+ assert context == {} # no reports -> empty context dict
+
+
+class TestCogRagScope:
+ def test_search_forwards_scope_to_both_layers(self):
+ cog = Cog_RAG.__new__(Cog_RAG)
+ calls = {}
+
+ class _Layer:
+ def search_edges(self, query, top_k=3, **kwargs):
+ calls["edges"] = kwargs
+ return []
+
+ def search_nodes(self, query, top_k=3, **kwargs):
+ calls["nodes"] = kwargs
+ return []
+
+ cog.theme_layer = _Layer()
+ cog.detail_layer = _Layer()
+
+ result = cog.search("q", source_ids=["s1"], tags=["t1"])
+
+ assert result == {"themes": [], "entities": []}
+ assert calls["edges"] == {"source_ids": ["s1"], "tags": ["t1"]}
+ assert calls["nodes"] == {"source_ids": ["s1"], "tags": ["t1"]}
+
+ def test_cog_rag_uses_hypergraph_layers(self):
+ """ThemeSchema participates in the theme layer's hyperedge schema."""
+ assert issubclass(ThemeSchema, object)
diff --git a/tests/mocks.py b/tests/mocks.py
index e449104..0e784ce 100644
--- a/tests/mocks.py
+++ b/tests/mocks.py
@@ -40,9 +40,7 @@ class MockStructuredRunnable(RunnableSerializable):
class Config:
arbitrary_types_allowed = True
- def invoke(
- self, input: Any, config: Optional[RunnableConfig] = None
- ) -> BaseModel:
+ def invoke(self, input: Any, config: Optional[RunnableConfig] = None) -> BaseModel:
"""Generate and return a mock instance of the schema."""
return self._generate_mock_instance(self.schema)
@@ -84,10 +82,7 @@ class MockStructuredRunnable(RunnableSerializable):
origin = get_origin(field_type)
default = field_info.default
- has_default = (
- default is not None
- or field_info.default_factory is not None
- )
+ has_default = default is not None or field_info.default_factory is not None
if is_optional and not has_default:
data[field_name] = None
@@ -149,11 +144,19 @@ class MockChatModel(BaseChatModel):
**kwargs: Any,
) -> Any:
"""Generate mock response."""
- return type("ChatResult", (), {
- "generations": [
- type("Generation", (), {"message": AIMessage(content="mock response")})
- ]
- })()
+ return type(
+ "ChatResult",
+ (),
+ {
+ "generations": [
+ type(
+ "Generation",
+ (),
+ {"message": AIMessage(content="mock response")},
+ )
+ ]
+ },
+ )()
def with_structured_output(
self, schema: Type[BaseModel], **kwargs: Any
diff --git a/tests/template_engine/test_factory.py b/tests/template_engine/test_factory.py
index cbea921..fb79318 100644
--- a/tests/template_engine/test_factory.py
+++ b/tests/template_engine/test_factory.py
@@ -1,6 +1,5 @@
"""Unit tests for TemplateFactory."""
-
import pytest
from hyperextract.utils.template_engine import Gallery, TemplateFactory
@@ -81,6 +80,7 @@ class TestTemplateFactoryCreateAllTypes:
)
from hyperextract.types import AutoModel
+
assert isinstance(result, AutoModel)
assert result.metadata.get("type") == "model"
@@ -94,6 +94,7 @@ class TestTemplateFactoryCreateAllTypes:
)
from hyperextract.types import AutoList
+
assert isinstance(result, AutoList)
assert result.metadata.get("type") == "list"
@@ -107,6 +108,7 @@ class TestTemplateFactoryCreateAllTypes:
)
from hyperextract.types import AutoSet
+
assert isinstance(result, AutoSet)
assert result.metadata.get("type") == "set"
@@ -120,5 +122,6 @@ class TestTemplateFactoryCreateAllTypes:
)
from hyperextract.types import AutoGraph
+
assert isinstance(result, AutoGraph)
assert result.metadata.get("type") == "graph"
diff --git a/tests/template_engine/test_parser_loader.py b/tests/template_engine/test_parser_loader.py
index d267b07..507b6a0 100644
--- a/tests/template_engine/test_parser_loader.py
+++ b/tests/template_engine/test_parser_loader.py
@@ -1,6 +1,5 @@
"""Unit tests for template parsers - loader."""
-
import pytest
from hyperextract.utils.template_engine.parsers import (
diff --git a/tests/template_engine/test_parser_output.py b/tests/template_engine/test_parser_output.py
index fb1d3cf..d0983e5 100644
--- a/tests/template_engine/test_parser_output.py
+++ b/tests/template_engine/test_parser_output.py
@@ -1,8 +1,6 @@
"""Unit tests for template parsers - output."""
-
-
class TestParseOutputBasic:
"""Basic test cases for parse_output function."""
diff --git a/tests/template_engine/test_validator.py b/tests/template_engine/test_validator.py
index 515b1c3..124369e 100644
--- a/tests/template_engine/test_validator.py
+++ b/tests/template_engine/test_validator.py
@@ -346,9 +346,7 @@ class TestPresetBootstrap:
seen_known = set()
for item in results:
relative = str(Path(item.file).relative_to(PRESETS_DIR)).replace("\\", "/")
- error_codes = {
- d.code for d in item.diagnostics if d.severity == "error"
- }
+ error_codes = {d.code for d in item.diagnostics if d.severity == "error"}
allowed = KNOWN_PRESET_ERRORS.get(relative, set())
extra = error_codes - allowed
missing = allowed - error_codes
diff --git a/tests/types/test_document.py b/tests/types/test_document.py
index 1ea6122..91b6a88 100644
--- a/tests/types/test_document.py
+++ b/tests/types/test_document.py
@@ -146,7 +146,9 @@ class TestChunkKeys:
def test_key_is_stable_and_content_based(self):
a, b = TextChunk(content="same"), TextChunk(content="same")
c = TextChunk(content="different")
- assert chunk_key_extractor(a) == chunk_key_extractor(b) != chunk_key_extractor(c)
+ assert (
+ chunk_key_extractor(a) == chunk_key_extractor(b) != chunk_key_extractor(c)
+ )
def test_registry_exports():
diff --git a/tests/types/test_graph_dangling.py b/tests/types/test_graph_dangling.py
index dd52d04..db2bc13 100644
--- a/tests/types/test_graph_dangling.py
+++ b/tests/types/test_graph_dangling.py
@@ -38,12 +38,18 @@ class TestAutoGraphDangling:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- ])
- graph._edge_memory.add([
- Relation(source="Apple", target="Steve Jobs", relation_type="founded_by"),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ ]
+ )
+ graph._edge_memory.add(
+ [
+ Relation(
+ source="Apple", target="Steve Jobs", relation_type="founded_by"
+ ),
+ ]
+ )
graph.build_index()
@@ -67,9 +73,11 @@ class TestAutoGraphMerge:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ ]
+ )
assert len(graph.nodes) == 1
diff --git a/tests/types/test_graph_extraction.py b/tests/types/test_graph_extraction.py
index b7eb544..dbb250f 100644
--- a/tests/types/test_graph_extraction.py
+++ b/tests/types/test_graph_extraction.py
@@ -82,10 +82,12 @@ class TestAutoGraphExtraction:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- Entity(name="Steve Jobs", type="PERSON", properties={}),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ Entity(name="Steve Jobs", type="PERSON", properties={}),
+ ]
+ )
assert len(graph._node_memory.items) == 2
assert graph.empty() is False
@@ -102,7 +104,9 @@ class TestAutoGraphExtraction:
embedder=embedder,
)
- graph._node_memory.add([Entity(name="Apple", type="ORGANIZATION", properties={})])
+ graph._node_memory.add(
+ [Entity(name="Apple", type="ORGANIZATION", properties={})]
+ )
assert graph.empty() is False
@@ -118,7 +122,9 @@ class TestAutoGraphExtraction:
embedder=embedder,
)
- graph._node_memory.add([Entity(name="Apple", type="ORGANIZATION", properties={})])
+ graph._node_memory.add(
+ [Entity(name="Apple", type="ORGANIZATION", properties={})]
+ )
graph.clear()
diff --git a/tests/types/test_graph_failure_isolation.py b/tests/types/test_graph_failure_isolation.py
index de47880..b25c153 100644
--- a/tests/types/test_graph_failure_isolation.py
+++ b/tests/types/test_graph_failure_isolation.py
@@ -12,8 +12,6 @@ whole run and discard every other chunk's data. These tests pin the contract:
subclasses alongside the isolation
"""
-
-
from pydantic import BaseModel, Field
from hyperextract.types import AutoGraph, AutoHypergraph, AutoTemporalGraph
diff --git a/tests/types/test_graph_search.py b/tests/types/test_graph_search.py
index c997549..658e3a5 100644
--- a/tests/types/test_graph_search.py
+++ b/tests/types/test_graph_search.py
@@ -38,10 +38,12 @@ class TestAutoGraphSearch:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- Entity(name="Steve Jobs", type="PERSON", properties={}),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ Entity(name="Steve Jobs", type="PERSON", properties={}),
+ ]
+ )
graph.build_index(index_nodes=True, index_edges=False)
@@ -59,12 +61,18 @@ class TestAutoGraphSearch:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- ])
- graph._edge_memory.add([
- Relation(source="Apple", target="Steve Jobs", relation_type="founded_by"),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ ]
+ )
+ graph._edge_memory.add(
+ [
+ Relation(
+ source="Apple", target="Steve Jobs", relation_type="founded_by"
+ ),
+ ]
+ )
graph.build_index(index_nodes=True, index_edges=True)
@@ -83,9 +91,11 @@ class TestAutoGraphSearch:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ ]
+ )
graph.build_node_index()
@@ -103,10 +113,12 @@ class TestAutoGraphSearch:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- Entity(name="Steve Jobs", type="PERSON", properties={}),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ Entity(name="Steve Jobs", type="PERSON", properties={}),
+ ]
+ )
graph.build_node_index()
results = graph.search_nodes("technology company", top_k=2)
@@ -125,10 +137,14 @@ class TestAutoGraphSearch:
embedder=embedder,
)
- graph._edge_memory.add([
- Relation(source="Apple", target="Steve Jobs", relation_type="founded_by"),
- Relation(source="Apple", target="Tim Cook", relation_type="led_by"),
- ])
+ graph._edge_memory.add(
+ [
+ Relation(
+ source="Apple", target="Steve Jobs", relation_type="founded_by"
+ ),
+ Relation(source="Apple", target="Tim Cook", relation_type="led_by"),
+ ]
+ )
graph.build_edge_index()
results = graph.search_edges("founder", top_k=2)
@@ -147,12 +163,18 @@ class TestAutoGraphSearch:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- ])
- graph._edge_memory.add([
- Relation(source="Apple", target="Steve Jobs", relation_type="founded_by"),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ ]
+ )
+ graph._edge_memory.add(
+ [
+ Relation(
+ source="Apple", target="Steve Jobs", relation_type="founded_by"
+ ),
+ ]
+ )
graph.build_index()
@@ -173,12 +195,18 @@ class TestAutoGraphSearch:
embedder=embedder,
)
- graph._node_memory.add([
- Entity(name="Apple", type="ORGANIZATION", properties={}),
- ])
- graph._edge_memory.add([
- Relation(source="Apple", target="Steve Jobs", relation_type="founded_by"),
- ])
+ graph._node_memory.add(
+ [
+ Entity(name="Apple", type="ORGANIZATION", properties={}),
+ ]
+ )
+ graph._edge_memory.add(
+ [
+ Relation(
+ source="Apple", target="Steve Jobs", relation_type="founded_by"
+ ),
+ ]
+ )
graph.build_index()
diff --git a/tests/types/test_hypergraph_merge.py b/tests/types/test_hypergraph_merge.py
index 6c00fd4..224fe2f 100644
--- a/tests/types/test_hypergraph_merge.py
+++ b/tests/types/test_hypergraph_merge.py
@@ -51,7 +51,11 @@ class TestAutoHypergraphMerge:
]
edges_lists = [
[],
- [HyperRelation(participants=["Apple", "Steve"], relation_type="founded_by")],
+ [
+ HyperRelation(
+ participants=["Apple", "Steve"], relation_type="founded_by"
+ )
+ ],
]
result = graph.merge_batch_data((nodes_lists, edges_lists))
diff --git a/tests/types/test_set_operations.py b/tests/types/test_set_operations.py
index d1bca30..b177b17 100644
--- a/tests/types/test_set_operations.py
+++ b/tests/types/test_set_operations.py
@@ -64,8 +64,12 @@ class TestAutoSetOperations:
def test_intersection_operator(self, llm_client, embedder):
"""Test intersection operator &."""
- set1 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java", "React"])
- set2 = self._create_set_with_terms(llm_client, embedder, ["Java", "React", "Vue"])
+ set1 = self._create_set_with_terms(
+ llm_client, embedder, ["Python", "Java", "React"]
+ )
+ set2 = self._create_set_with_terms(
+ llm_client, embedder, ["Java", "React", "Vue"]
+ )
result = set1 & set2
@@ -94,7 +98,9 @@ class TestAutoSetOperations:
def test_difference_operator(self, llm_client, embedder):
"""Test difference operator -."""
- set1 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java", "React"])
+ set1 = self._create_set_with_terms(
+ llm_client, embedder, ["Python", "Java", "React"]
+ )
set2 = self._create_set_with_terms(llm_client, embedder, ["Java", "React"])
result = set1 - set2
@@ -199,7 +205,9 @@ class TestAutoSetComparison:
def test_subset_not_reflexive_superset(self, llm_client, embedder):
"""Test that subset is not true when superset is smaller."""
- set1 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java", "React"])
+ set1 = self._create_set_with_terms(
+ llm_client, embedder, ["Python", "Java", "React"]
+ )
set2 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java"])
assert not (set1 <= set2)
@@ -220,14 +228,18 @@ class TestAutoSetComparison:
def test_superset_operator(self, llm_client, embedder):
"""Test superset operator >=."""
- set1 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java", "React"])
+ set1 = self._create_set_with_terms(
+ llm_client, embedder, ["Python", "Java", "React"]
+ )
set2 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java"])
assert set1 >= set2
def test_proper_superset_operator(self, llm_client, embedder):
"""Test proper superset operator >."""
- set1 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java", "React"])
+ set1 = self._create_set_with_terms(
+ llm_client, embedder, ["Python", "Java", "React"]
+ )
set2 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java"])
assert set1 > set2
@@ -248,7 +260,9 @@ class TestAutoSetComparison:
def test_issuperset_method(self, llm_client, embedder):
"""Test issuperset method."""
- set1 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java", "React"])
+ set1 = self._create_set_with_terms(
+ llm_client, embedder, ["Python", "Java", "React"]
+ )
set2 = self._create_set_with_terms(llm_client, embedder, ["Python", "Java"])
assert set1.issuperset(set2)
diff --git a/tests/types/test_set_provenance.py b/tests/types/test_set_provenance.py
new file mode 100644
index 0000000..ee19e4e
--- /dev/null
+++ b/tests/types/test_set_provenance.py
@@ -0,0 +1,128 @@
+"""AutoSet provenance: recording, scoped search, tags, upsert, persistence.
+
+Before this fix, AutoSet enabled ``track_sources`` on its memory but never
+recorded sources during feed — the ledger stayed empty, scoped search
+returned nothing, and ``he tag`` / ``he feed --source`` change detection
+crashed with AttributeError (no delegation surface at all).
+
+Rollback/scoped-search tests seed the memory directly (like
+test_graph_rag.py) so they do not depend on what the mock LLM extracts.
+"""
+
+import json
+
+import pytest
+from pydantic import BaseModel
+
+from hyperextract.types import AutoSet
+
+
+class _Item(BaseModel):
+ name: str
+ category: str = "general"
+
+
+def ka(llm_client, embedder):
+ return AutoSet(
+ item_schema=_Item,
+ key_extractor=lambda x: x.name,
+ llm_client=llm_client,
+ embedder=embedder,
+ )
+
+
+def _seed(ka, source_id, name):
+ """Attribute one item to a source without going through the LLM."""
+ ka._data_memory.add([_Item(name=name)], source_id=source_id)
+
+
+class TestSourceRecording:
+ def test_feed_records_source(self, ka):
+ ka.feed_text("Apple and Steve.", source_id="d1", content_hash="h1")
+ assert "d1" in ka.sources()
+ assert ka.source_content_hash("d1") == "h1"
+
+ def test_scoped_search_returns_attributed_items(self, ka):
+ _seed(ka, "d1", "Apple")
+ _seed(ka, "d2", "Tesla")
+ ka.build_index()
+
+ hits = ka.search("Apple", top_k=5, source_ids=["d1"])
+ assert [item.name for item in hits] == ["Apple"]
+
+ def test_scope_on_empty_ledger_is_empty(self, llm_client, embedder):
+ # A KA fed WITHOUT --source has no ledger: scoped search must not
+ # silently return out-of-scope items.
+ other = AutoSet(
+ item_schema=_Item,
+ key_extractor=lambda x: x.name,
+ llm_client=llm_client,
+ embedder=embedder,
+ )
+ other.feed_text("Apple and Steve.")
+ other.build_index()
+ assert other.search("Apple", top_k=5, source_ids=["d1"]) == []
+
+
+class TestTagsAndRollback:
+ def test_tag_round_trip(self, ka):
+ _seed(ka, "d1", "Apple")
+ assert ka.tag_source("d1", add=["tech"]) == ["tech"]
+ assert ka.source_tags("d1") == ["tech"]
+
+ def test_remove_source_keeps_others(self, ka):
+ _seed(ka, "d1", "Apple")
+ _seed(ka, "d2", "Tesla")
+ ka.build_index()
+
+ report = ka.remove_source("d1")
+ assert report["removed_items"]
+ names = [item.name for item in ka.data.items]
+ assert "Apple" not in names and "Tesla" in names
+
+ def test_upsert_replaces_previous_version(self, ka):
+ _seed(ka, "d2", "Tesla")
+ ka.feed_text("Apple and Steve.", source_id="d1", content_hash="h1")
+ ka.feed_text("Rewritten doc one.", source_id="d1", content_hash="h2")
+
+ assert ka.source_content_hash("d1") == "h2"
+ # Whatever the extraction produced, the pre-upsert ledger state was
+ # rolled back and re-recorded under the same source id.
+ assert "d1" in ka.sources()
+ assert "d2" in ka.sources()
+
+
+class TestPersistence:
+ def test_ledger_persists_across_dump_load(self, ka, llm_client, embedder, tmp_path):
+ _seed(ka, "d1", "Apple")
+ _seed(ka, "d2", "Tesla")
+ # Feed under a THIRD source — feeding under d1 would (correctly)
+ # roll back d1's seeded contributions via upsert semantics.
+ ka.feed_text("Some text.", source_id="d3", content_hash="h1")
+ ka.build_index()
+ ka.dump(tmp_path)
+
+ assert (tmp_path / "sources_items.json").exists()
+
+ restored = AutoSet(
+ item_schema=_Item,
+ key_extractor=lambda x: x.name,
+ llm_client=llm_client,
+ embedder=embedder,
+ )
+ restored.load(tmp_path)
+ assert {"d1", "d2", "d3"} <= set(restored.sources())
+ assert restored.source_content_hash("d3") == "h1"
+
+ restored.build_index()
+ hits = restored.search("Apple", top_k=5, source_ids=["d1"])
+ names = [item.name for item in hits]
+ assert "Apple" in names and "Tesla" not in names
+
+ def test_data_json_shape_unchanged(self, ka, tmp_path):
+ _seed(ka, "d1", "Apple")
+ ka.dump(tmp_path)
+ data = json.loads((tmp_path / "data.json").read_text(encoding="utf-8"))
+ assert isinstance(data["items"], list)
+ assert [i["name"] for i in data["items"]] == ["Apple"]
diff --git a/tests/utils/test_client.py b/tests/utils/test_client.py
index 76a27a6..49b9df2 100644
--- a/tests/utils/test_client.py
+++ b/tests/utils/test_client.py
@@ -22,6 +22,7 @@ from hyperextract.utils.client import (
# _parse_client_spec
# =============================================================================
+
class TestParseClientSpec:
"""Tests for _parse_client_spec string parser."""
@@ -53,7 +54,9 @@ class TestParseClientSpec:
def test_embedder_defaults(self):
"""Embedder default kind uses embedder preset."""
- result = _parse_client_spec("bailian", api_key="sk-test", default_kind="embedder")
+ result = _parse_client_spec(
+ "bailian", api_key="sk-test", default_kind="embedder"
+ )
assert result["model"] == "text-embedding-v4" # default_embedder preset
def test_provider_orcarouter(self):
@@ -100,6 +103,7 @@ class TestParseClientSpec:
# create_llm / create_embedder
# =============================================================================
+
class TestCreateLLM:
"""Tests for create_llm factory."""
@@ -255,6 +259,7 @@ class TestCreateEmbedder:
# create_client (unified API)
# =============================================================================
+
class TestCreateClient:
"""Tests for create_client unified factory."""
@@ -302,6 +307,7 @@ class TestCreateClient:
# CompatibleEmbeddings
# =============================================================================
+
class TestCompatibleEmbeddings:
"""Tests for CompatibleEmbeddings wrapper."""
@@ -436,9 +442,12 @@ class TestCompatibleEmbeddings:
]
)
# Force the single input text to split into three chunks.
- with patch.object(
- emb, "_split_texts", return_value=[("c1", 0), ("c2", 0), ("c3", 0)]
- ), patch.object(emb, "_client", mock_openai_client):
+ with (
+ patch.object(
+ emb, "_split_texts", return_value=[("c1", 0), ("c2", 0), ("c3", 0)]
+ ),
+ patch.object(emb, "_client", mock_openai_client),
+ ):
result = emb.embed_documents(["a long text"])
assert result == [[6.0, 6.0, 6.0]]
@@ -514,6 +523,7 @@ class TestCompatibleEmbeddings:
# get_client (config file)
# =============================================================================
+
class TestGetClient:
"""Tests for get_client reading from config file."""
@@ -521,12 +531,12 @@ class TestGetClient:
"""Read client config from TOML file."""
config_file = tmp_path / "config.toml"
config_file.write_text(
- '[llm]\n'
+ "[llm]\n"
'provider = "bailian"\n'
'model = "qwen-plus"\n'
'api_key = "sk-from-file"\n'
'base_url = ""\n'
- '[embedder]\n'
+ "[embedder]\n"
'provider = "bailian"\n'
'model = "text-embedding-v4"\n'
'api_key = "sk-from-file"\n'
@@ -536,7 +546,9 @@ class TestGetClient:
assert llm.model_name == "qwen-plus"
assert isinstance(emb, CompatibleEmbeddings)
- def test_get_client_missing_file(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ def test_get_client_missing_file(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ):
"""Missing config file returns default configs."""
# Ensure consistent environment for default OpenAI fallback
monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
@@ -553,6 +565,7 @@ class TestGetClient:
# PROVIDER_PRESETS consistency
# =============================================================================
+
class TestProviderPresets:
"""Tests for PROVIDER_PRESETS data consistency."""