Debian Codegraph @

tests/lib/tools/memory_sync/test_e2e_memory.py

raw
1 """Memory-store sync driven end to end through the real `EnvironmentWorker`.
2
3 Real: the worker, `SessionMemoryStores`, `FileStore`,
4 and the filesystem. Faked: the network (an in-memory `MemoryServer` plus
5 stub heartbeat/stop), the session tool-call stream, and the clock. So the
6 chain worker → gate on the sessions token → download → `sync_if_due` per
7 tool call → `finish` → `dispose` runs for real against a fake
8 server; assertions read the server and the disk.
9 """
10
11 from __future__ import annotations
12
13 import json
14 import time
15 import base64
16 import asyncio
17 import contextlib
18 from types import SimpleNamespace
19 from typing import Any
20 from pathlib import Path
21 from collections.abc import Callable, AsyncIterator
22
23 import pytest
24
25 import anthropic.lib.tools._memories as memories_mod
26 import anthropic.lib.environments._worker as worker_mod
27 from anthropic.lib.tools._memories import MemoryDeleteMode
28 from anthropic.lib.environments._worker import EnvironmentWorker
29
30 from ._fake_anthropic import MemoryServer, created, updated, fake_anthropic
31
32
33 def _causes(exc: BaseException) -> list[BaseException]:
34 """Flatten an exception and any ExceptionGroup members it wraps."""
35 inner = getattr(exc, "exceptions", None)
36 if inner is None:
37 return [exc]
38 return [exc, *(c for e in inner for c in _causes(e))]
39
40
41 def fake_session(
42 monkeypatch: pytest.MonkeyPatch,
43 tmp_path: Path,
44 *,
45 token: str | None,
46 tool_calls: int,
47 interval: float | None = 300.0,
48 on_call: Callable[[int], None] | None = None,
49 then_raise: Exception | None = None,
50 clock: Callable[[], float] | None = None,
51 no_stores: bool = False,
52 sync_deletions: MemoryDeleteMode = "enabled",
53 tools: Callable[[Any], list[Any]] | None = None,
54 ) -> tuple[EnvironmentWorker, MemoryServer, Path]:
55 """An `EnvironmentWorker` pointed at a fake client; one work item queued."""
56
57 class _FakeWork:
58 """Stub of `client.beta.environments.work` — heartbeat and stop are no-ops."""
59
60 async def heartbeat(self, *_a: Any, **_kw: Any) -> Any:
61 return SimpleNamespace(last_heartbeat="hb", ttl_seconds=60, state="running", lease_extended=True)
62
63 async def stop(self, *_a: Any, **_kw: Any) -> None:
64 pass
65
66 # One fake client serves every role: sessions.retrieve (for skills +
67 # memory download), memory_stores.memories (the MemoryServer), and
68 # environments.work (heartbeat + stop). The worker's
69 # _copy_client_with_bearer_auth call returns it, and the memory stores
70 # ride that same sub-client.
71 memory_client, server = fake_anthropic({"note.md": "v1"}, no_stores=no_stores)
72 client: Any = SimpleNamespace(
73 beta=SimpleNamespace(
74 sessions=memory_client.beta.sessions,
75 memory_stores=memory_client.beta.memory_stores,
76 environments=SimpleNamespace(work=_FakeWork()),
77 )
78 )
79
80 def _scoped(_client: Any, *, auth_token: str, helper: str) -> Any: # noqa: ARG001
81 return client
82
83 monkeypatch.setattr(worker_mod, "_copy_client_with_bearer_auth", _scoped)
84
85 if clock is not None:
86 monkeypatch.setattr(memories_mod, "monotonic", clock)
87
88 # Encode the token the way the poll response carries it: base64url JSON.
89 secret = (
90 None if token is None else base64.urlsafe_b64encode(json.dumps({"sessions_token": token}).encode()).decode()
91 )
92 work_item = SimpleNamespace(
93 id="w1", environment_id="e1", secret=secret, data=SimpleNamespace(type="session", id="s1")
94 )
95
96 async def _aiter_work(*_a: Any, **_kw: Any) -> AsyncIterator[Any]:
97 yield work_item
98
99 monkeypatch.setattr(worker_mod, "aiter_work", _aiter_work)
100
101 @contextlib.asynccontextmanager
102 async def _run_session_tools(*_a: Any, **_kw: Any) -> AsyncIterator[AsyncIterator[int]]:
103 async def _calls() -> AsyncIterator[int]:
104 for i in range(tool_calls):
105 if on_call is not None:
106 on_call(i)
107 yield i
108 if then_raise is not None:
109 raise then_raise
110
111 yield _calls()
112
113 monkeypatch.setattr(worker_mod, "_run_session_tools", _run_session_tools)
114
115 worker = EnvironmentWorker(
116 client,
117 environment_id="e1",
118 environment_key="ek",
119 workdir=tmp_path,
120 memory_sync_interval=interval,
121 memory_sync_deletions=sync_deletions,
122 tools=tools if tools is not None else lambda _env: [],
123 )
124 return worker, server, tmp_path / "memory" / "notes"
125
126
127 async def _run_timed(worker: EnvironmentWorker) -> float:
128 """Run the worker to completion and return the wall-clock seconds it took."""
129 start = time.monotonic()
130 await asyncio.wait_for(worker.run(), timeout=10)
131 return time.monotonic() - start
132
133
134 @pytest.mark.asyncio()
135 async def test_worker_syncs_on_cadence_finishes_and_disposes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
136 now = 0.0
137
138 def on_call(i: int) -> None:
139 nonlocal now
140 # The agent edits its note, then a long gap passes before the
141 # worker's sync_if_due poll — so every poll is due.
142 (local / "note.md").write_text(f"edit {i}")
143 now += 400.0
144
145 worker, server, local = fake_session(
146 monkeypatch, tmp_path, token="tok", tool_calls=3, on_call=on_call, clock=lambda: now
147 )
148
149 await asyncio.wait_for(worker.run(), timeout=10)
150
151 # One session fetch, shared by the skills and memory downloads.
152 assert server.retrieves == ["s1"]
153 # Download happened (the file landed on disk before any edit); three
154 # cadence syncs pushed edits 0/1/2; the final sync had nothing new.
155 assert server.received == [
156 updated("note.md", "edit 0", was="v1"),
157 updated("note.md", "edit 1", was="edit 0"),
158 updated("note.md", "edit 2", was="edit 1"),
159 ]
160 # Dispose removed the store dir the download created.
161 assert not local.exists()
162
163
164 @pytest.mark.asyncio()
165 async def test_worker_fails_the_item_when_the_sessions_token_is_missing(
166 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
167 ) -> None:
168 """The session has memory stores attached but the work item carried no
169 sessions token, so its memories cannot be mounted. The ITEM fails before a
170 single tool call is served — running the session anyway would give it
171 amnesia, where hosted sandboxes fail the start. The worker keeps polling."""
172 caplog.set_level("ERROR", logger="anthropic.lib.environments._worker")
173 calls: list[int] = []
174 worker, server, local = fake_session(monkeypatch, tmp_path, token=None, tool_calls=2, on_call=calls.append)
175
176 # run() completes: the item failed, the poll loop did not.
177 await asyncio.wait_for(worker.run(), timeout=10)
178
179 assert "work item failed" in caplog.text
180 assert "carried no sessions token" in caplog.text
181 # The session never served a tool call, and memory was never touched.
182 assert calls == []
183 assert server.received == []
184 assert not local.exists()
185
186
187 @pytest.mark.asyncio()
188 async def test_worker_skips_memory_when_the_interval_is_none(
189 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
190 ) -> None:
191 caplog.set_level("ERROR", logger="anthropic.lib.environments._worker")
192 worker, server, local = fake_session(monkeypatch, tmp_path, token="tok", tool_calls=2, interval=None)
193
194 await asyncio.wait_for(worker.run(), timeout=10)
195
196 # Even with a sessions token, interval=None turns memory off entirely.
197 assert server.received == []
198 assert not local.exists()
199 # Turning memory off is a deliberate choice, so it says nothing loud.
200 assert caplog.text == ""
201
202
203 def test_worker_rejects_a_sub_floor_interval(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
204 for interval in (4.9, 0, float("nan")):
205 with pytest.raises(ValueError, match="at least"):
206 fake_session(monkeypatch, tmp_path, token="tok", tool_calls=0, interval=interval)
207
208
209 @pytest.mark.asyncio()
210 async def test_worker_fails_the_item_when_a_memory_store_cannot_be_downloaded(
211 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
212 ) -> None:
213 """A folder already at the store's path is debris from a run that died. The
214 download refuses it and the ITEM fails — rather than serving a session whose
215 system prompt names a memory folder holding someone else's files. The worker
216 itself keeps polling; a killed worker's leftovers must not crashloop it."""
217 caplog.set_level("ERROR", logger="anthropic.lib.environments._worker")
218 debris = tmp_path / "memory" / "notes"
219 debris.mkdir(parents=True)
220 (debris / "left-behind.md").write_text("from a dead run")
221
222 worker, server, _local = fake_session(monkeypatch, tmp_path, token="tok", tool_calls=2)
223
224 # run() completes: the item failed, the poll loop did not.
225 await asyncio.wait_for(worker.run(), timeout=10)
226
227 assert "work item failed" in caplog.text
228 assert "already exists" in caplog.text
229 # Nothing was pushed, and the debris is exactly as it was found.
230 assert server.received == []
231 assert (debris / "left-behind.md").read_text() == "from a dead run"
232 assert not (debris / "note.md").exists()
233
234
235 @pytest.mark.asyncio()
236 async def test_worker_flushes_writes_when_the_stream_raises(
237 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
238 ) -> None:
239 caplog.set_level("ERROR", logger="anthropic.lib.environments._worker")
240 now = 0.0
241
242 def on_call(i: int) -> None:
243 nonlocal now
244 (local / "note.md").write_text(f"edit {i}")
245 if i == 0:
246 # Only the first edit gets a cadence sync; the second is still
247 # on disk when the stream breaks.
248 now += 400.0
249
250 worker, server, local = fake_session(
251 monkeypatch,
252 tmp_path,
253 token="tok",
254 tool_calls=2,
255 on_call=on_call,
256 then_raise=RuntimeError("stream broke"),
257 clock=lambda: now,
258 )
259
260 # The item fails; the poll loop does not. anyio wraps the RuntimeError in
261 # an ExceptionGroup whose own message says nothing, so the worker flattens
262 # it — the log names the real cause.
263 await asyncio.wait_for(worker.run(), timeout=10)
264 assert "work item failed" in caplog.text
265 assert "stream broke" in caplog.text
266
267 # The raise skipped the final sync, but the shutdown flush pushed the
268 # pending edit before dispose removed the folder.
269 assert server.received == [
270 updated("note.md", "edit 0", was="v1"),
271 updated("note.md", "edit 1", was="edit 0"),
272 ]
273 # Dispose still ran (shielded teardown).
274 assert not local.exists()
275
276
277 @pytest.mark.asyncio()
278 async def test_worker_clean_end_syncs_once_and_the_flush_adds_nothing(
279 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
280 ) -> None:
281 caplog.set_level("WARNING", logger="anthropic.lib.tools.agent_toolset")
282 caplog.set_level("WARNING", logger="anthropic.lib.environments._worker")
283 now = 0.0
284
285 def on_call(i: int) -> None:
286 nonlocal now
287 (local / "note.md").write_text(f"edit {i}")
288 if i == 0:
289 now += 400.0
290
291 worker, server, local = fake_session(
292 monkeypatch, tmp_path, token="tok", tool_calls=2, on_call=on_call, clock=lambda: now
293 )
294
295 await asyncio.wait_for(worker.run(), timeout=10)
296
297 # The cadence sync pushed edit 0 and the clean-end final sync pushed
298 # edit 1 — exactly once each. The teardown flush runs after them but
299 # finds nothing dirty, so nothing more is sent.
300 assert server.received == [
301 updated("note.md", "edit 0", was="v1"),
302 updated("note.md", "edit 1", was="edit 0"),
303 ]
304 # Neither teardown pass hit its time bound, so nothing says "cut off".
305 assert "cut off" not in caplog.text
306 assert not local.exists()
307
308
309 @pytest.mark.asyncio()
310 async def test_worker_flushes_after_a_clean_final_sync_that_failed(
311 tmp_path: Path, monkeypatch: pytest.MonkeyPatch
312 ) -> None:
313 """sync() swallows its own failures, so a clean stream end whose final
314 sync broke would silently lose the last edits — the teardown flush is
315 their second chance."""
316
317 async def finish_that_breaks(_self: memories_mod.SessionMemoryStores) -> None:
318 return # a store-level failure inside the last sync: logged, nothing pushed
319
320 monkeypatch.setattr(memories_mod.SessionMemoryStores, "finish", finish_that_breaks)
321
322 def on_call(_i: int) -> None:
323 (local / "note.md").write_text("last edit")
324
325 worker, server, local = fake_session(monkeypatch, tmp_path, token="tok", tool_calls=1, on_call=on_call)
326
327 await asyncio.wait_for(worker.run(), timeout=10)
328
329 assert server.files["note.md"] == "last edit"
330 assert not local.exists()
331
332
333 @pytest.mark.asyncio()
334 async def test_worker_flush_is_bounded_and_teardown_still_runs(
335 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
336 ) -> None:
337 """A flush that hangs is cut off at MEMORY_FLUSH_TIMEOUT and says so; dispose still runs."""
338 caplog.set_level("WARNING", logger="anthropic.lib.environments._worker")
339 monkeypatch.setattr(worker_mod, "MEMORY_FLUSH_TIMEOUT", 0.05)
340 flush_started = asyncio.Event()
341
342 async def hanging_flush(_self: memories_mod.SessionMemoryStores) -> None:
343 flush_started.set()
344 await asyncio.sleep(5)
345
346 monkeypatch.setattr(memories_mod.SessionMemoryStores, "flush_writes", hanging_flush)
347
348 def on_call(i: int) -> None:
349 (local / "note.md").write_text(f"edit {i}")
350
351 worker, _server, local = fake_session(
352 monkeypatch,
353 tmp_path,
354 token="tok",
355 tool_calls=1,
356 on_call=on_call,
357 then_raise=RuntimeError("stream broke"),
358 )
359
360 elapsed = await _run_timed(worker)
361
362 assert flush_started.is_set()
363 # Without the timeout the hung flush would hold teardown the full 5s.
364 assert elapsed < 2.0
365 assert "memory flush cut off after" in caplog.text
366 assert not local.exists()
367
368
369 @pytest.mark.asyncio()
370 async def test_worker_final_sync_is_bounded_and_the_flush_still_runs(
371 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
372 ) -> None:
373 """A final sync that hangs is cut off at MEMORY_FLUSH_TIMEOUT and says so;
374 the flush after it still uploads the last edit."""
375 caplog.set_level("WARNING", logger="anthropic.lib.environments._worker")
376 # The same bound covers the real flush that follows, which must finish
377 # inside it even on a loaded CI machine.
378 monkeypatch.setattr(worker_mod, "MEMORY_FLUSH_TIMEOUT", 0.5)
379
380 async def hanging_finish(_self: memories_mod.SessionMemoryStores) -> None:
381 await asyncio.sleep(5)
382
383 monkeypatch.setattr(memories_mod.SessionMemoryStores, "finish", hanging_finish)
384
385 def on_call(_i: int) -> None:
386 (local / "note.md").write_text("last edit")
387
388 worker, server, local = fake_session(monkeypatch, tmp_path, token="tok", tool_calls=1, on_call=on_call)
389
390 elapsed = await _run_timed(worker)
391
392 assert elapsed < 2.0
393 assert "final memory sync cut off after" in caplog.text
394 # The flush finished in time, so only the final sync reports a cut-off.
395 assert "memory flush cut off after" not in caplog.text
396 assert server.files["note.md"] == "last edit"
397 assert not local.exists()
398
399
400 @pytest.mark.asyncio()
401 async def test_worker_logs_what_a_cut_off_flush_left_behind(
402 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
403 ) -> None:
404 """One upload never completes: the flush is cut off, the store logs that
405 one of its two changed files did not make it, and the other one did."""
406 caplog.set_level("WARNING", logger="anthropic.lib.tools.agent_toolset")
407 caplog.set_level("WARNING", logger="anthropic.lib.environments._worker")
408 monkeypatch.setattr(worker_mod, "MEMORY_FLUSH_TIMEOUT", 0.5)
409
410 def on_call(_i: int) -> None:
411 (local / "kept.md").write_text("saved")
412 (local / "stuck.md").write_text("only copy")
413
414 worker, server, local = fake_session(
415 monkeypatch,
416 tmp_path,
417 token="tok",
418 tool_calls=1,
419 on_call=on_call,
420 then_raise=RuntimeError("stream broke"),
421 )
422 never = asyncio.Event()
423
424 async def hook(path: str) -> None:
425 if path == "stuck.md":
426 await asyncio.wait_for(never.wait(), timeout=5)
427
428 server.upload_hook = hook
429
430 elapsed = await _run_timed(worker)
431
432 assert elapsed < 3.0
433 assert server.files["kept.md"] == "saved"
434 assert "stuck.md" not in server.files
435 assert "1 of 2 changed files had not finished uploading memory_store_id=memstore_notes" in caplog.text
436 assert "memory flush cut off after" in caplog.text
437 assert not local.exists()
438
439
440 @pytest.mark.asyncio()
441 async def test_worker_stays_quiet_when_no_memory_store_is_attached(
442 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
443 ) -> None:
444 """Most sessions have no memory at all. Missing a sessions token is only
445 worth shouting about when there is memory the session cannot reach."""
446 caplog.set_level("ERROR", logger="anthropic.lib.environments._worker")
447 worker, server, local = fake_session(monkeypatch, tmp_path, token=None, tool_calls=2, no_stores=True)
448
449 await asyncio.wait_for(worker.run(), timeout=10)
450
451 assert server.received == []
452 assert not local.exists()
453 assert caplog.text == ""
454
455
456 @pytest.mark.asyncio()
457 async def test_worker_can_turn_sync_deletions_off(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
458 """`memory_sync_deletions="disabled"` reaches the stores: a local deletion
459 never propagates however many syncs run, while uploads still do."""
460 now = 0.0
461
462 def on_call(i: int) -> None:
463 nonlocal now
464 if i == 0:
465 (local / "note.md").unlink()
466 (local / "new.md").write_text("survives")
467 # Every gap dwarfs both the sync interval and the corroboration window.
468 now += 400.0
469
470 worker, server, local = fake_session(
471 monkeypatch,
472 tmp_path,
473 token="tok",
474 tool_calls=3,
475 on_call=on_call,
476 clock=lambda: now,
477 sync_deletions="disabled",
478 )
479
480 await asyncio.wait_for(worker.run(), timeout=10)
481
482 assert server.files["note.md"] == "v1"
483 assert server.received == [created("new.md", "survives")]
484
485
486 @pytest.mark.asyncio()
487 async def test_worker_flushes_and_disposes_even_when_env_teardown_raises(
488 tmp_path: Path, monkeypatch: pytest.MonkeyPatch
489 ) -> None:
490 """A raising env.__aexit__ must not skip the flush or leave the folder
491 behind for the next work item to trip over."""
492 from anthropic.lib.tools import agent_toolset
493
494 real_aexit = agent_toolset.AgentToolContext.__aexit__
495
496 async def broken_aexit(self: agent_toolset.AgentToolContext, *exc: Any) -> None:
497 await real_aexit(self, *exc)
498 raise OSError("teardown burp")
499
500 monkeypatch.setattr(agent_toolset.AgentToolContext, "__aexit__", broken_aexit)
501
502 def on_call(_i: int) -> None:
503 (local / "note.md").write_text("edit before burp")
504
505 worker, server, local = fake_session(
506 monkeypatch, tmp_path, token="tok", tool_calls=1, on_call=on_call, then_raise=RuntimeError("stream died")
507 )
508
509 await asyncio.wait_for(worker.run(), timeout=10)
510
511 assert server.files["note.md"] == "edit before burp"
512 assert not local.exists()
513
514
515 @pytest.mark.asyncio()
516 async def test_the_last_sync_runs_after_the_bash_subprocesses_are_killed(
517 tmp_path: Path, monkeypatch: pytest.MonkeyPatch
518 ) -> None:
519 """finish() skips the delete waiting window, so it must only run once
520 nothing can still be rewriting files — after env teardown kills the
521 session's subprocesses."""
522 from anthropic.lib.tools import agent_toolset
523
524 order: list[str] = []
525 real_aexit = agent_toolset.AgentToolContext.__aexit__
526 real_finish = memories_mod.SessionMemoryStores.finish
527
528 async def recording_aexit(self: agent_toolset.AgentToolContext, *exc: Any) -> None:
529 order.append("env_teardown")
530 await real_aexit(self, *exc)
531
532 async def recording_finish(self: memories_mod.SessionMemoryStores) -> None:
533 order.append("finish")
534 await real_finish(self)
535
536 monkeypatch.setattr(agent_toolset.AgentToolContext, "__aexit__", recording_aexit)
537 monkeypatch.setattr(memories_mod.SessionMemoryStores, "finish", recording_finish)
538
539 def on_call(_i: int) -> None:
540 (local / "note.md").write_text("last edit")
541
542 worker, server, local = fake_session(monkeypatch, tmp_path, token="tok", tool_calls=1, on_call=on_call)
543
544 await asyncio.wait_for(worker.run(), timeout=10)
545
546 assert order == ["env_teardown", "finish"]
547 assert server.files["note.md"] == "last edit"
548 assert not local.exists()
549
550
551 @pytest.mark.asyncio()
552 async def test_the_lease_is_heartbeated_until_the_memory_teardown_is_done(
553 tmp_path: Path, monkeypatch: pytest.MonkeyPatch
554 ) -> None:
555 """The lease must not lapse while the final sync, flush and dispose still hold the folder."""
556 order: list[str] = []
557 real_heartbeat_loop = worker_mod._heartbeat_loop
558 real_dispose = memories_mod.SessionMemoryStores.dispose
559
560 async def recording_heartbeat_loop(*args: Any, **kwargs: Any) -> None:
561 try:
562 await real_heartbeat_loop(*args, **kwargs)
563 finally:
564 order.append("heartbeat stopped")
565
566 async def recording_dispose(self: memories_mod.SessionMemoryStores) -> None:
567 await real_dispose(self)
568 order.append("folder removed")
569
570 monkeypatch.setattr(worker_mod, "_heartbeat_loop", recording_heartbeat_loop)
571 monkeypatch.setattr(memories_mod.SessionMemoryStores, "dispose", recording_dispose)
572
573 worker, _server, _local = fake_session(monkeypatch, tmp_path, token="tok", tool_calls=1)
574
575 await asyncio.wait_for(worker.run(), timeout=10)
576
577 assert order == ["folder removed", "heartbeat stopped"]
578
579
580 @pytest.mark.asyncio()
581 async def test_worker_grants_file_tools_access_to_store_folders(
582 tmp_path: Path, monkeypatch: pytest.MonkeyPatch
583 ) -> None:
584 """The tool context handed to the tools factory carries the downloaded
585 store folders as allowed roots, so the file tools can reach a memory
586 mounted outside the working directory."""
587 contexts: list[Any] = []
588
589 def capture(env: Any) -> list[Any]:
590 contexts.append(env)
591 return []
592
593 worker, _server, local = fake_session(monkeypatch, tmp_path, token="tok", tool_calls=1, tools=capture)
594
595 await asyncio.wait_for(worker.run(), timeout=10)
596
597 (env,) = contexts
598 assert env.allowed_roots == [local.resolve()]
599 assert env.read_only_roots == []