Repository navigation
Expand file tree
/
Copy pathtest_maggraph.py
More file actions
320 lines (240 loc) · 11.4 KB
/
Copy pathtest_maggraph.py
File metadata and controls
320 lines (240 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""Pytest suite for MagGraph Python bindings."""
from __future__ import annotations
import asyncio
from importlib.metadata import version
from pathlib import Path
import maggraph
import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
BASIC_CONFIG = REPO_ROOT / "examples" / "basic" / "maggraph.toml"
BASIC_GRAPH = REPO_ROOT / "examples" / "basic" / "knowledge_graph"
def test_package_version_matches_distribution_metadata() -> None:
assert maggraph.__version__ == version("maggraph")
def test_load_config_resolves_root_path() -> None:
config = maggraph.load_config(str(BASIC_CONFIG))
assert config.storage_mode == "local"
assert Path(config.root_path) == BASIC_GRAPH.resolve()
def test_open_index_lists_nodes() -> None:
index = maggraph.open_index(str(BASIC_GRAPH))
nodes = index.list_nodes()
assert "welcome" in nodes
assert "getting_started" in nodes
assert len(index) >= 2
def test_read_node_returns_body() -> None:
index = maggraph.open_index(str(BASIC_GRAPH))
node = index.read_node("welcome")
assert node.id == "welcome"
assert node.node_type == "note"
assert "Welcome" in node.body
assert node.to_markdown().startswith("---")
def test_traverse_bfs_reaches_neighbors() -> None:
index = maggraph.open_index(str(BASIC_GRAPH))
result = index.traverse("welcome", depth=1, order="bfs")
visited = {n.id for n in result.nodes}
assert result.start == "welcome"
assert "getting_started" in visited
markdown = result.to_markdown(index)
assert "# MagGraph Traversal Report" in markdown
assert "### welcome" in markdown
def test_traverse_unknown_start_raises() -> None:
index = maggraph.open_index(str(BASIC_GRAPH))
with pytest.raises(maggraph.MagGraphError, match="not found"):
index.traverse("missing-node", depth=1)
@pytest.mark.asyncio
async def test_traverse_async_does_not_block_event_loop() -> None:
index = maggraph.open_index(str(BASIC_GRAPH))
tick = asyncio.Event()
async def waiter() -> None:
await tick.wait()
task = asyncio.create_task(waiter())
await asyncio.sleep(0)
assert not task.done()
result = await asyncio.wait_for(index.traverse_async("welcome", depth=2, order="bfs"), timeout=5)
tick.set()
await task
assert any(n.id == "getting_started" for n in result.nodes)
@pytest.mark.asyncio
async def test_read_node_async() -> None:
index = maggraph.open_index(str(BASIC_GRAPH))
node = await asyncio.wait_for(index.read_node_async("welcome"), timeout=5)
assert node.id == "welcome"
def test_config_open_index_helper() -> None:
config = maggraph.load_config(str(BASIC_CONFIG))
index = config.open_index()
assert len(index) >= 2
def test_crud_round_trip(tmp_path: Path) -> None:
import shutil
graph = tmp_path / "graph"
shutil.copytree(BASIC_GRAPH, graph)
index = maggraph.open_index(str(graph))
index.create_node("agent_test", node_type="note", body="# Test\n", links=[])
assert "agent_test" in index.list_nodes()
index.update_node("agent_test", "# Updated\n")
assert "Updated" in index.read_node("agent_test").body
index.delete_node("agent_test")
assert "agent_test" not in index.list_nodes()
def test_search_backlinks_recall_and_quality_primitives(tmp_path: Path) -> None:
import shutil
graph = tmp_path / "graph"
shutil.copytree(BASIC_GRAPH, graph)
index = maggraph.open_index(str(graph))
memory_node = index.create_memory_node("prefers_cli", "preference", "User prefers CLI workflows.")
assert memory_node.node_type == "preference"
results = index.search("Welcome")
assert any(item["id"] == "welcome" for item in results)
assert "getting_started" in index.backlinks("welcome")
bundle = index.recall_bundle("welcome", reason="pytest", body_chars=80)
assert bundle["id"] == "welcome"
assert "pytest" in bundle["markdown"]
assert "backlinks" in bundle
index.suppress_node("getting_started", reason="duplicate")
filtered = index.search("Getting")
assert not any(item["id"] == "getting_started" for item in filtered)
index.unsuppress_node("getting_started")
assert any(item["id"] == "getting_started" for item in index.search("Getting"))
index.merge_nodes("welcome", "getting_started")
assert "getting_started" not in index.list_nodes()
assert "Merged from" in index.read_node("welcome").body
def test_update_file_and_changed_since(tmp_path: Path) -> None:
import shutil
graph = tmp_path / "graph"
shutil.copytree(BASIC_GRAPH, graph)
index = maggraph.open_index(str(graph))
(graph / "fresh.md").write_text(
'---\nid: "fresh"\ntype: "project_fact"\ntags: ["agent"]\n---\n# Fresh\n',
encoding="utf-8",
)
assert index.update_file("fresh.md") == "fresh"
assert "fresh" in index.list_nodes()
changes = index.changed_since(0)
assert any(item["id"] == "fresh" for item in changes)
tagged = index.search("", tags=["agent"])
assert any(item["id"] == "fresh" for item in tagged)
# ─────────────────────────────────────────────────────────────────────────────
# T-M4: LakehouseReader Python API tests
# ─────────────────────────────────────────────────────────────────────────────
def _write_local_graph(tmp_path: Path, *, mode: str = "local", remote_sources: str = "") -> tuple[Path, Path]:
"""Write a minimal graph + config to tmp_path. Returns (config_path, graph_dir)."""
graph = tmp_path / "graph"
graph.mkdir()
(graph / "note.md").write_text(
'---\nid: "note"\ntype: "note"\n---\n# Hello\n', encoding="utf-8"
)
remote_block = f"\n[lakehouse]\nremote_sources = [{remote_sources}]\n" if remote_sources else ""
config = tmp_path / "maggraph.toml"
config.write_text(
f'[storage]\nmode = "{mode}"\nroot_path = "./graph"\n{remote_block}',
encoding="utf-8",
)
return config, graph
def _write_lakehouse_node(graph: Path, *, source: str) -> None:
"""Write a node with an external source URI into graph."""
(graph / "asset.md").write_text(
f'---\nid: "asset"\ntype: "external_asset"\nsource: "{source}"\n---\n# Asset\n',
encoding="utf-8",
)
def test_lakehouse_reader_local_mode_returns_markdown(tmp_path: Path) -> None:
"""In local mode, read_node_with_content returns kind='local' with the markdown body."""
config_path, _ = _write_local_graph(tmp_path)
config = maggraph.load_config(str(config_path))
index = config.open_index()
reader = config.open_lakehouse_reader()
result = reader.read_node(index, "note")
assert result.node.id == "note"
assert result.content.kind == "local"
assert result.content.body is not None
assert "Hello" in result.content.body
assert "Hello" in result.content.to_markdown()
assert repr(result).startswith("NodeWithContent")
def test_lakehouse_reader_via_index_method(tmp_path: Path) -> None:
"""GraphIndex.read_node_with_content delegates to the reader correctly."""
config_path, _ = _write_local_graph(tmp_path)
config = maggraph.load_config(str(config_path))
index = config.open_index()
reader = config.open_lakehouse_reader()
result = index.read_node_with_content(reader, "note")
assert result.node.id == "note"
assert result.content.kind == "local"
def test_lakehouse_reader_resolved_content_repr(tmp_path: Path) -> None:
"""ResolvedContent.__repr__ includes kind and body length for local content."""
config_path, _ = _write_local_graph(tmp_path)
config = maggraph.load_config(str(config_path))
index = config.open_index()
reader = config.open_lakehouse_reader()
content = reader.read_node(index, "note").content
r = repr(content)
assert "local" in r
assert "body_len" in r
def test_lakehouse_reader_resolves_s3_stub(tmp_path: Path) -> None:
"""In lakehouse mode with a mocked S3 remote, source nodes resolve as external_asset."""
remote_sources = '{ uri = "s3://corp-data/lake", format = "parquet" }'
config_path, graph = _write_local_graph(
tmp_path, mode="lakehouse", remote_sources=remote_sources
)
_write_lakehouse_node(graph, source="s3://corp-data/lake/churn.parquet")
config = maggraph.load_config(str(config_path))
index = config.open_index()
reader = config.open_lakehouse_reader()
result = reader.read_node(index, "asset")
assert result.node.id == "asset"
assert result.content.kind == "external_asset"
assert result.content.uri is not None
assert "s3://" in result.content.uri
assert result.content.format == "parquet"
assert result.content.body is None # external assets have no inline body
md = result.content.to_markdown()
assert "External asset" in md or "s3://" in md
def test_lakehouse_reader_caches_result(tmp_path: Path) -> None:
"""Reading the same node twice should populate the cache; cache_len() == 1."""
remote_sources = '{ uri = "s3://corp-data/lake", format = "parquet" }'
config_path, graph = _write_local_graph(
tmp_path, mode="lakehouse", remote_sources=remote_sources
)
_write_lakehouse_node(graph, source="s3://corp-data/lake/churn.parquet")
config = maggraph.load_config(str(config_path))
index = config.open_index()
reader = config.open_lakehouse_reader()
# First read populates cache
reader.read_node(index, "asset")
assert reader.cache_len() == 1
assert reader.cache_bytes() > 0
# Second read hits cache — len stays at 1
reader.read_node(index, "asset")
assert reader.cache_len() == 1
def test_lakehouse_reader_file_uri(tmp_path: Path) -> None:
"""file:// sources resolve to ExternalAsset with Parquet metadata when magic header present."""
data_dir = tmp_path / "data"
data_dir.mkdir()
parquet_file = data_dir / "metrics.parquet"
parquet_file.write_bytes(b"PAR1" + b"\x00" * 20 + b"PAR1") # minimal PAR1 magic
graph = tmp_path / "graph"
graph.mkdir()
file_uri = parquet_file.as_uri() # file:///…
(graph / "metrics.md").write_text(
f'---\nid: "metrics"\ntype: "external_asset"\nsource: "{file_uri}"\n---\nPointer\n',
encoding="utf-8",
)
remote_uri = data_dir.as_uri()
config = tmp_path / "maggraph.toml"
config.write_text(
f'[storage]\nmode = "lakehouse"\nroot_path = "./graph"\n\n'
f'[lakehouse]\nremote_sources = [{{ uri = "{remote_uri}", format = "parquet" }}]\n',
encoding="utf-8",
)
cfg = maggraph.load_config(str(config))
index = cfg.open_index()
reader = cfg.open_lakehouse_reader()
result = reader.read_node(index, "metrics")
assert result.content.kind == "external_asset"
assert result.content.format == "parquet"
assert result.content.parquet_magic_valid is True
@pytest.mark.asyncio
async def test_lakehouse_reader_async(tmp_path: Path) -> None:
"""read_node_async on LakehouseReader returns the same result as the sync version."""
config_path, _ = _write_local_graph(tmp_path)
config = maggraph.load_config(str(config_path))
index = config.open_index()
reader = config.open_lakehouse_reader()
result = await asyncio.wait_for(reader.read_node_async(index, "note"), timeout=5)
assert result.node.id == "note"
assert result.content.kind == "local"