Debian Codegraph @

tests/lib/tools/memory_sync/test_memory_sync.py

raw
1 """The memory-store sync contract.
2
3 An agent keeps a folder of notes on disk. The same folder lives on the
4 server. Each sync makes the two agree: each side gets
5 the other's changes, and when both changed the same file the server wins.
6
7 Each test tells one story with two actors — `local` is the agent's
8 folder on disk, `server` is the remote copy. Paths are the same string
9 on both sides. `server.received` holds only what the sync sent;
10 arranging remote state never touches it.
11 """
12
13 from __future__ import annotations
14
15 import os
16 from typing import Any
17 from pathlib import Path
18
19 import pytest
20
21 from anthropic._compat import PYDANTIC_V1
22 from anthropic.lib.tools import _memories as memories_mod
23 from anthropic.lib.tools._memories import SessionMemoryError, SessionMemoryStores
24
25 from .conftest import Clock, run_sync
26 from ._fake_anthropic import MemoryServer, created, deleted, updated, _status_error, fake_anthropic
27
28 LOGGER = "anthropic.lib.tools.agent_toolset"
29
30
31 async def _downloaded(
32 tmp_path: Path, initial: dict[str, str], *, access: str | None = None
33 ) -> tuple[Path, MemoryServer, SessionMemoryStores]:
34 """A `SessionMemoryStores` with one store already downloaded to disk."""
35 client, server = fake_anthropic(initial, access=access)
36 stores = SessionMemoryStores(client, workdir=tmp_path)
37 await stores.download(await client.beta.sessions.retrieve("s1"))
38 return tmp_path / "memory" / "notes", server, stores
39
40
41 @pytest.mark.asyncio()
42 async def test_edits_flow_both_ways_and_the_server_wins_conflicts(
43 tmp_path: Path, caplog: pytest.LogCaptureFixture
44 ) -> None:
45 caplog.set_level("WARNING", logger=LOGGER)
46 local, server, stores = await _downloaded(
47 tmp_path, {"push.md": "v1", "pull.md": "v1", "both.md": "v1", "gone.md": "v1"}
48 )
49
50 (local / "push.md").write_text("v2 from agent")
51 (local / "new.md").write_text("new from agent")
52 server.write("pull.md", "v2 from server")
53 (local / "both.md").write_text("v2 from agent")
54 server.write("both.md", "v2 from server")
55 server.delete("gone.md")
56
57 await run_sync(stores)
58
59 # Each side has the other's change; the server won the conflict; the
60 # server's deletion took the local copy with it.
61 assert server.files["push.md"] == "v2 from agent"
62 assert server.files["new.md"] == "new from agent"
63 assert (local / "pull.md").read_text() == "v2 from server"
64 assert (local / "both.md").read_text() == "v2 from server"
65 assert not (local / "gone.md").exists()
66 assert "gone.md" not in server.files
67 assert "changed both locally and remotely" in caplog.text
68
69 # The push was guarded: overwrite only if the server still had v1.
70 sent = [created("new.md", "new from agent"), updated("push.md", "v2 from agent", was="v1")]
71 assert server.received == sent
72
73 # Settled: a second sync sends nothing more.
74 await run_sync(stores)
75 assert server.received == sent
76
77
78 @pytest.mark.asyncio()
79 async def test_local_deletions_reach_the_server_unless_it_changed(tmp_path: Path, clock: Clock) -> None:
80 # One memory's download write fails, so it is never on disk to begin with —
81 # that absence is not a deletion.
82 from anthropic.lib.tools import _file_store
83
84 real_put = _file_store.LocalFileStore.put
85
86 async def flaky_put(self: _file_store.LocalFileStore, rel: str, content: str) -> None:
87 if rel == "never.md":
88 raise OSError(5, "I/O error")
89 await real_put(self, rel, content)
90
91 # keep.md survives on disk so the pass is not an all-files-gone wipe.
92 client, server = fake_anthropic({"drop.md": "v1", "raced.md": "v1", "never.md": "v1", "keep.md": "v1"})
93 stores = SessionMemoryStores(client, workdir=tmp_path)
94 with pytest.MonkeyPatch.context() as mp:
95 mp.setattr(_file_store.LocalFileStore, "put", flaky_put)
96 await stores.download(await client.beta.sessions.retrieve("s1"))
97 local = tmp_path / "memory" / "notes"
98
99 (local / "drop.md").unlink()
100 (local / "raced.md").unlink()
101 server.write("raced.md", "v2 from server")
102
103 await run_sync(stores)
104 # The first pass only records the deletion; a corroborating pass after
105 # the window sends it.
106 assert "drop.md" in server.files
107 clock.now = memories_mod.DELETE_CORROBORATION_SECONDS + 1
108 await run_sync(stores)
109
110 # Only the un-raced deletion went out, guarded by the last-synced content.
111 sent = [deleted("drop.md", was="v1")]
112 assert server.received == sent
113 assert "drop.md" not in server.files
114 # The raced deletion lost — the server's edit came back to disk instead.
115 assert (local / "raced.md").read_text() == "v2 from server"
116 # The never-downloaded file was pulled, not deleted.
117 assert (local / "never.md").read_text() == "v1"
118 assert server.files["never.md"] == "v1"
119
120 await run_sync(stores)
121 assert server.received == sent
122
123
124 @pytest.mark.asyncio()
125 async def test_read_only_stores_are_never_written(tmp_path: Path) -> None:
126 local, server, stores = await _downloaded(
127 tmp_path, {"edit.md": "v1", "drop.md": "v1", "pull.md": "v1"}, access="read_only"
128 )
129
130 (local / "edit.md").write_text("v2 from agent")
131 (local / "drop.md").unlink()
132 (local / "new.md").write_text("new from agent")
133 server.write("pull.md", "v2 from server")
134
135 await run_sync(stores)
136
137 assert server.received == []
138 assert server.files == {"edit.md": "v1", "drop.md": "v1", "pull.md": "v2 from server"}
139 # Pulls still happen.
140 assert (local / "pull.md").read_text() == "v2 from server"
141
142 # A remote deletion is a pull too, so it removes the local copy even here.
143 server.delete("pull.md")
144 await run_sync(stores)
145 assert server.received == []
146 assert not (local / "pull.md").exists()
147
148
149 @pytest.mark.asyncio()
150 async def test_paths_that_escape_the_store_are_refused(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
151 caplog.set_level("WARNING", logger=LOGGER)
152 local, server, stores = await _downloaded(tmp_path, {"../evil.md": "boom", "ok.md": "fine"})
153
154 await run_sync(stores)
155
156 assert (local / "ok.md").read_text() == "fine"
157 assert list(tmp_path.rglob("evil.md")) == []
158 assert server.received == []
159 assert "escapes" in caplog.text
160
161
162 @pytest.mark.asyncio()
163 async def test_worker_lifecycle_cadence_and_dispose(tmp_path: Path, clock: Clock) -> None:
164 """The worker's call sequence: download → sync_if_due per call → finish → dispose."""
165 # The worker polls sync_if_due after each tool call and
166 # runs one final sync on a clean end. A fake clock makes the cadence
167 # observable.
168 client, server = fake_anthropic({"note.md": "v1"})
169 stores = SessionMemoryStores(client, workdir=tmp_path, sync_interval=300.0)
170 await stores.download(await client.beta.sessions.retrieve("s1"))
171 local = tmp_path / "memory" / "notes"
172
173 (local / "note.md").write_text("edit 1")
174 await stores.sync_if_due()
175 assert server.received == []
176
177 # One long gap fires exactly once, and not again until another interval.
178 clock.now = 2000.0
179 await stores.sync_if_due()
180 await stores.sync_if_due()
181 assert server.received == [updated("note.md", "edit 1", was="v1")]
182 clock.now = 2299.0
183 await stores.sync_if_due()
184 assert len(server.received) == 1
185
186 # The last sync is finish(): unconditional, once.
187 (local / "note.md").write_text("edit 2")
188 await stores.finish()
189 assert server.received[-1] == updated("note.md", "edit 2", was="edit 1")
190
191 # Dispose removes the store dir the download created.
192 assert local.exists()
193 await stores.dispose()
194 assert not local.exists()
195
196
197 @pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2")
198 @pytest.mark.asyncio()
199 async def test_write_and_edit_tools_refuse_read_only_roots(tmp_path: Path) -> None:
200 from anthropic.lib.tools.agent_toolset import AgentToolContext, beta_edit_tool, beta_write_tool
201 from anthropic.lib.tools._beta_functions import ToolError
202
203 ro = tmp_path / "memory" / "notes"
204 ro.mkdir(parents=True)
205 (ro / "facts.md").write_text("immutable")
206
207 ctx = AgentToolContext(workdir=str(tmp_path), read_only_roots=[ro.resolve()])
208 write = beta_write_tool(ctx)
209 edit = beta_edit_tool(ctx)
210
211 with pytest.raises(ToolError, match="read-only"):
212 await write.call({"file_path": str(ro / "facts.md"), "content": "overwritten"})
213 with pytest.raises(ToolError, match="read-only"):
214 await write.call({"file_path": str(ro / "new.md"), "content": "new"})
215 with pytest.raises(ToolError, match="read-only"):
216 await edit.call({"file_path": str(ro / "facts.md"), "old_string": "immutable", "new_string": "x"})
217 assert (ro / "facts.md").read_text() == "immutable"
218 assert not (ro / "new.md").exists()
219
220 # Paths outside the read-only root are unaffected.
221 await write.call({"file_path": "scratch.txt", "content": "ok"})
222 assert (tmp_path / "scratch.txt").read_text() == "ok"
223
224
225 @pytest.mark.asyncio()
226 async def test_a_binary_local_file_never_blocks_the_other_files(
227 tmp_path: Path, caplog: pytest.LogCaptureFixture
228 ) -> None:
229 """The store is utf-8-restricted, so a binary file the agent drops in the
230 folder is refused at read — warned once and skipped until it changes —
231 while every other file keeps syncing."""
232 caplog.set_level("WARNING", logger=LOGGER)
233 local, server, stores = await _downloaded(tmp_path, {"note.md": "v1"})
234
235 (local / "blob.bin").write_bytes(b"\xff\xfe\x00 not utf-8")
236 (local / "note.md").write_text("v2")
237
238 await run_sync(stores)
239 await run_sync(stores)
240
241 assert server.received == [updated("note.md", "v2", was="v1")]
242 assert "blob.bin" not in server.files
243 assert caplog.text.count("stays un-synced until its content changes path=blob.bin") == 1
244
245
246 @pytest.mark.asyncio()
247 async def test_an_oversized_file_is_skipped_until_it_shrinks(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
248 """A file the server refuses as too large is warned once and skipped —
249 not retried while unchanged, never blocking the other files — and syncs
250 as soon as an edit brings it under the cap."""
251 caplog.set_level("WARNING", logger=LOGGER)
252 local, server, stores = await _downloaded(tmp_path, {"note.md": "v1"})
253 server.max_content_bytes = 64
254
255 (local / "big.md").write_text("x" * 100)
256 (local / "note.md").write_text("v2")
257
258 await run_sync(stores)
259 await run_sync(stores)
260
261 # The small edit landed; the big file was attempted exactly once.
262 assert updated("note.md", "v2", was="v1") in server.received
263 assert sum(1 for r in server.received if r[0] == "create") == 1
264 assert "big.md" not in server.files
265 assert caplog.text.count("stays un-synced until its content changes path=big.md") == 1
266
267 (local / "big.md").write_text("small now")
268 await run_sync(stores)
269 assert server.files["big.md"] == "small now"
270
271
272 @pytest.mark.asyncio()
273 @pytest.mark.parametrize("status", [401, 403, 404])
274 async def test_a_refusal_that_says_nothing_about_the_content_is_retried_next_sync(
275 tmp_path: Path, caplog: pytest.LogCaptureFixture, status: int
276 ) -> None:
277 """Anything but a content refusal is retried by the next sync."""
278 caplog.set_level("WARNING", logger=LOGGER)
279 local, server, stores = await _downloaded(tmp_path, {"note.md": "v1"})
280 (local / "note.md").write_text("v2")
281 (local / "new.md").write_text("fresh")
282
283 async def refuse(_path: str) -> None:
284 raise _status_error(status)
285
286 server.upload_hook = refuse
287 await run_sync(stores)
288 server.upload_hook = None
289 await run_sync(stores)
290
291 assert server.files == {"note.md": "v2", "new.md": "fresh"}
292 assert "stays un-synced" not in caplog.text
293
294
295 @pytest.mark.asyncio()
296 async def test_an_upload_that_loses_the_race_pulls_the_winner_next_sync(
297 tmp_path: Path, caplog: pytest.LogCaptureFixture
298 ) -> None:
299 """The server changes between this sync's list and its update: the
300 content_sha256 precondition rejects the push (409), and the next sync
301 applies the conflict rule — the winning remote edit is pulled, the
302 local edit is never re-pushed."""
303 caplog.set_level("WARNING", logger=LOGGER)
304 local, server, stores = await _downloaded(tmp_path, {"note.md": "v1"})
305
306 (local / "note.md").write_text("local edit")
307 memories = stores._client.beta.memory_stores.memories # pyright: ignore[reportPrivateUsage]
308 real_update = memories.update
309
310 async def racing_update(memory_id: str, **kw: Any) -> Any:
311 # Race: the remote changes after this sync's list, before its update.
312 server.write("note.md", "raced remote edit")
313 return await real_update(memory_id, **kw)
314
315 memories.update = racing_update
316 await run_sync(stores)
317 memories.update = real_update
318
319 # The precondition rejected the push (one guarded attempt, no retry) and
320 # the server kept its raced edit.
321 assert server.received == [updated("note.md", "local edit", was="v1")]
322 assert server.files["note.md"] == "raced remote edit"
323 # The log says what actually happened: the push was refused and the local
324 # copy is now stale — nothing was "kept".
325 assert "the upload was refused and the local edit loses" in caplog.text
326 assert (local / "note.md").read_text() == "local edit"
327
328 # The next sync pulls the winner instead of re-pushing.
329 await run_sync(stores)
330 assert (local / "note.md").read_text() == "raced remote edit"
331 assert len(server.received) == 1
332
333
334 @pytest.mark.asyncio()
335 async def test_a_broken_store_fails_the_whole_download(tmp_path: Path) -> None:
336 """A store that cannot be materialised fails the download outright. A
337 session served without a folder its system prompt names would run with
338 amnesia; the worker turns this into a failed work item."""
339 client, _ = fake_anthropic({"note.md": "v1"}, broken_store=True)
340 stores = SessionMemoryStores(client, workdir=tmp_path)
341
342 with pytest.raises(SessionMemoryError, match="memstore_broken"):
343 await stores.download(await client.beta.sessions.retrieve("s1"))
344
345 # The half-downloaded folder self-destructed; nothing is tracked.
346 assert not (tmp_path / "memory" / "broken").exists()
347 assert stores.read_only_roots == []
348
349
350 @pytest.mark.asyncio()
351 async def test_a_legal_mount_path_is_honored_and_an_unclean_one_is_refused(tmp_path: Path) -> None:
352 """mount_path is the location the agent's system prompt names. A clean
353 absolute one is honored verbatim, and dispose removes it when the download
354 created it. One we cannot use verbatim fails the session rather than
355 quietly relocating the store somewhere the agent will never look."""
356 mount = tmp_path / "mnt" / "notes"
357 client, _ = fake_anthropic({"note.md": "v1"}, mount_path=str(mount))
358 stores = SessionMemoryStores(client, workdir=tmp_path / "wd")
359 await stores.download(await client.beta.sessions.retrieve("s1"))
360 assert (mount / "note.md").read_text() == "v1"
361 # The worker feeds these roots to the file tools' allowed roots, so the
362 # out-of-workdir mount stays reachable.
363 assert stores.roots == [mount.resolve()]
364 await stores.dispose()
365 assert not mount.exists()
366
367
368 @pytest.mark.asyncio()
369 async def test_an_unwritable_mount_path_fails_the_download(tmp_path: Path) -> None:
370 """A mount the host cannot provide is an environment failure: the download
371 raises loudly (failing the work item) instead of degrading to a session
372 with silently-empty memory."""
373 if os.geteuid() == 0:
374 pytest.skip("directory modes do not bind root")
375 parent = tmp_path / "mnt"
376 parent.mkdir()
377 parent.chmod(0o500) # the worker may not create the store's folder here
378 try:
379 client, server = fake_anthropic({"note.md": "v1"}, mount_path=str(parent / "notes"))
380 stores = SessionMemoryStores(client, workdir=tmp_path / "wd")
381
382 with pytest.raises(SessionMemoryError, match="writable"):
383 await stores.download(await client.beta.sessions.retrieve("s1"))
384 assert server.received == []
385 finally:
386 parent.chmod(0o700)
387
388
389 @pytest.mark.parametrize("bad", ["/mnt/../../etc/cron.d", "relative/notes", "", "notes"])
390 @pytest.mark.asyncio()
391 async def test_an_unclean_mount_path_fails_the_download(tmp_path: Path, bad: str) -> None:
392 # "" means the resource carries no mount_path at all — that one is allowed,
393 # and falls back to the workdir, because nothing pointed the agent anywhere.
394 client, server = fake_anthropic({"note.md": "v1"}, mount_path=bad or None)
395 stores = SessionMemoryStores(client, workdir=tmp_path / "wd")
396
397 if not bad:
398 await stores.download(await client.beta.sessions.retrieve("s1"))
399 assert (tmp_path / "wd" / "memory" / "notes" / "note.md").read_text() == "v1"
400 return
401
402 with pytest.raises(SessionMemoryError, match="not a clean absolute path"):
403 await stores.download(await client.beta.sessions.retrieve("s1"))
404
405 # Nothing was written anywhere, and no store is tracked.
406 assert not (tmp_path / "wd").exists()
407 assert server.received == []
408 assert stores.read_only_roots == []
409
410
411 @pytest.mark.asyncio()
412 async def test_prefix_items_and_foreign_resources_leave_no_trace(tmp_path: Path) -> None:
413 """Only `memory_store` resources are downloaded and only `memory`
414 items carry content — a `file` resource and `memory_prefix` rollups
415 pass through without touching the disk or the server."""
416 client, server = fake_anthropic({"ok.md": "fine"}, noise=True)
417 stores = SessionMemoryStores(client, workdir=tmp_path)
418 await stores.download(await client.beta.sessions.retrieve("s1"))
419 local = tmp_path / "memory" / "notes"
420
421 assert (local / "ok.md").read_text() == "fine"
422 assert list((tmp_path / "memory").iterdir()) == [local]
423 assert not (local / "projects").exists()
424 await run_sync(stores)
425 assert server.received == []
426
427
428 @pytest.mark.asyncio()
429 async def test_a_store_directory_that_already_exists_is_refused(tmp_path: Path) -> None:
430 """Nothing but a dead run leaves a folder at the store's path. Syncing into
431 it would fold that run's debris into the customer's store, so refuse — and
432 leave the folder exactly as it was found."""
433 stale = tmp_path / "memory" / "notes"
434 stale.mkdir(parents=True)
435 (stale / "debris.md").write_text("left by another session")
436
437 client, server = fake_anthropic({"note.md": "v1"})
438 stores = SessionMemoryStores(client, workdir=tmp_path)
439
440 with pytest.raises(SessionMemoryError, match="already exists"):
441 await stores.download(await client.beta.sessions.retrieve("s1"))
442
443 # Refused, not adopted and not deleted.
444 assert (stale / "debris.md").read_text() == "left by another session"
445 assert not (stale / "note.md").exists()
446 assert server.received == []
447 assert stores.read_only_roots == []
448
449 # A sibling folder in the same parent is none of our business.
450 other = tmp_path / "memory2" / "notes"
451 other.parent.mkdir(parents=True)
452 (tmp_path / "memory2" / "unrelated").mkdir()
453 client2, _ = fake_anthropic({"note.md": "v1"})
454 ok = SessionMemoryStores(client2, workdir=tmp_path / "memory2")
455 await ok.download(await client2.beta.sessions.retrieve("s1"))
456 assert (tmp_path / "memory2" / "memory" / "notes" / "note.md").read_text() == "v1"
457
458
459 # ---- the sync matrix -------------------------------------------------------
460 #
461 # Every combination of (remote moved?, local moved?) for a path the store has
462 # already downloaded, plus the paths only one side knows about. `local` and
463 # `remote` say what happened since the last sync; `disk` and `store` are the
464 # state both sides must agree on afterwards. A `fails` column injects a broken
465 # upload/download so the row also pins where a failed operation leaves us.
466
467 _MISSING = object()
468
469
470 @pytest.mark.parametrize(
471 ("name", "local", "remote", "disk", "store", "sent"),
472 [
473 # baseline "v1" on both sides unless the row says otherwise
474 ("untouched", None, None, "v1", "v1", []),
475 ("local edit", "v2", None, "v2", "v2", [("update", "v2", "v1")]),
476 ("remote edit", None, "v2", "v2", "v2", []),
477 ("both edit, server wins", "v2 local", "v2 remote", "v2 remote", "v2 remote", []),
478 ("local delete", _MISSING, None, _MISSING, _MISSING, [("delete", None, "v1")]),
479 ("remote delete", None, _MISSING, _MISSING, _MISSING, []),
480 ("both delete", _MISSING, _MISSING, _MISSING, _MISSING, []),
481 ("local delete, remote edit", _MISSING, "v2", "v2", "v2", []),
482 ("local edit, remote delete", "v2", _MISSING, "v2", "v2", [("create", "v2", None)]),
483 ],
484 )
485 @pytest.mark.asyncio()
486 async def test_sync_matrix(
487 tmp_path: Path,
488 clock: Clock,
489 name: str,
490 local: Any,
491 remote: Any,
492 disk: Any,
493 store: Any,
494 sent: list[tuple[Any, ...]],
495 ) -> None:
496 path, server, stores = await _downloaded(tmp_path, {"f.md": "v1"})
497
498 if local is _MISSING:
499 (path / "f.md").unlink()
500 elif local is not None:
501 (path / "f.md").write_text(local)
502
503 if remote is _MISSING:
504 server.delete("f.md")
505 elif remote is not None:
506 server.write("f.md", remote)
507
508 # Two passes: a local deletion is only sent after its corroboration window.
509 await run_sync(stores)
510 clock.now = memories_mod.DELETE_CORROBORATION_SECONDS + 1
511 await run_sync(stores)
512
513 if disk is _MISSING:
514 assert not (path / "f.md").exists(), name
515 else:
516 assert (path / "f.md").read_text() == disk, name
517
518 if store is _MISSING:
519 assert "f.md" not in server.files, name
520 else:
521 assert server.files["f.md"] == store, name
522
523 expected = [
524 created("f.md", v)
525 if kind == "create"
526 else updated("f.md", v, was=was)
527 if kind == "update"
528 else deleted("f.md", was=was)
529 for kind, v, was in sent
530 ]
531 assert server.received == expected, name
532
533 # Settled: a second pass sends nothing more and changes nothing.
534 await run_sync(stores)
535 assert server.received == expected, name
536
537
538 # ---- the failure column ----------------------------------------------------
539 #
540 # Same matrix, one operation broken. A failed operation must leave disk and
541 # server in a state the next sync can still reconcile — never one where the
542 # retry does the opposite of what was asked.
543
544
545 @pytest.mark.asyncio()
546 async def test_a_failed_upload_keeps_the_local_edit_and_retries(tmp_path: Path) -> None:
547 local, server, stores = await _downloaded(tmp_path, {"f.md": "v1"})
548 (local / "f.md").write_text("v2 from agent")
549
550 async def boom(*_a: Any, **_k: Any) -> Any:
551 raise RuntimeError("upload exploded")
552
553 original = stores._client.beta.memory_stores.memories.update # pyright: ignore[reportPrivateUsage]
554 stores._client.beta.memory_stores.memories.update = boom # pyright: ignore[reportPrivateUsage]
555 await run_sync(stores)
556
557 # The agent's edit survives; the server is untouched.
558 assert (local / "f.md").read_text() == "v2 from agent"
559 assert server.files["f.md"] == "v1"
560
561 # The baseline still says v1, so the next (working) sync retries the push.
562 stores._client.beta.memory_stores.memories.update = original # pyright: ignore[reportPrivateUsage]
563 await run_sync(stores)
564 assert server.files["f.md"] == "v2 from agent"
565
566
567 @pytest.mark.asyncio()
568 async def test_a_failed_pull_leaves_the_old_file_and_retries(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
569 from anthropic.lib.tools import _file_store
570
571 local, server, stores = await _downloaded(tmp_path, {"f.md": "v1"})
572 server.write("f.md", "v2 from server")
573
574 async def flaky_put(_self: _file_store.LocalFileStore, _rel: str, _content: str) -> None:
575 raise OSError(5, "I/O error")
576
577 monkeypatch.setattr(_file_store.LocalFileStore, "put", flaky_put)
578 await run_sync(stores)
579 monkeypatch.undo()
580
581 # The stale file is still there and the baseline never advanced...
582 assert (local / "f.md").read_text() == "v1"
583 assert server.received == []
584
585 # ...so the next sync pulls it, rather than mistaking v1 for a local edit
586 # and pushing it back over the server's v2.
587 await run_sync(stores)
588 assert (local / "f.md").read_text() == "v2 from server"
589 assert server.received == []
590
591
592 @pytest.mark.asyncio()
593 async def test_a_failed_local_removal_never_re_uploads_the_deleted_memory(
594 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
595 ) -> None:
596 """The server deleted the memory; removing our copy fails. The baseline must
597 stay put — dropping it would read the leftover file as a new local file and
598 create the memory the server just deleted."""
599 caplog.set_level("WARNING", logger=LOGGER)
600 from anthropic.lib.tools import _file_store
601
602 local, server, stores = await _downloaded(tmp_path, {"f.md": "v1"})
603 server.delete("f.md")
604
605 async def flaky_remove(_self: _file_store.LocalFileStore, _rel: str) -> None:
606 raise OSError(5, "I/O error")
607
608 monkeypatch.setattr(_file_store.LocalFileStore, "remove", flaky_remove)
609 await run_sync(stores)
610 monkeypatch.undo()
611
612 assert (local / "f.md").read_text() == "v1"
613 assert server.received == []
614 assert "f.md" not in server.files
615 assert "failed to remove memory deleted remotely" in caplog.text
616
617 # The retry deletes it locally; it is never pushed back.
618 await run_sync(stores)
619 assert not (local / "f.md").exists()
620 assert server.received == []
621 assert "f.md" not in server.files
622
623
624 @pytest.mark.asyncio()
625 async def test_a_store_that_landed_is_disposed_when_a_later_one_fails(tmp_path: Path) -> None:
626 """download() raises on the first store it cannot materialise, but the ones
627 that already landed are tracked — so the caller's dispose still reaps their
628 directories rather than leaking them."""
629 client, _ = fake_anthropic({"note.md": "v1"}, broken_store_last=True)
630 stores = SessionMemoryStores(client, workdir=tmp_path)
631
632 with pytest.raises(SessionMemoryError, match="memstore_broken"):
633 await stores.download(await client.beta.sessions.retrieve("s1"))
634
635 notes = tmp_path / "memory" / "notes"
636 assert notes.exists(), "the healthy store landed before the broken one failed"
637
638 await stores.dispose()
639 assert not notes.exists()
640 # The broken store's own half-download self-destructed at the failure.
641 assert not (tmp_path / "memory" / "broken").exists()
642
643
644 @pytest.mark.asyncio()
645 async def test_stores_sync_in_parallel_and_one_failure_spares_the_rest(
646 tmp_path: Path, caplog: pytest.LogCaptureFixture
647 ) -> None:
648 """Stores sync concurrently, and one store's failure never blocks another.
649
650 The slow store's listing waits for the fast store's listing to start —
651 only a parallel sync satisfies that — then explodes. A serial sync would
652 time the wait out instead (a different error message), and the fast
653 store's edit must land either way.
654 """
655 caplog.set_level("WARNING", logger=LOGGER)
656 import anyio
657
658 from ._fake_anthropic import _Resource
659
660 slow = MemoryServer({"a.md": "v1"})
661 fast = MemoryServer({"b.md": "v1"})
662 resources = {"memstore_slow": _Resource(slow), "memstore_fast": _Resource(fast)}
663 fast_list_started = anyio.Event()
664 syncing = False
665
666 class _Router:
667 def list(self, memory_store_id: str, **kwargs: Any) -> Any:
668 async def _iter() -> Any:
669 if syncing:
670 if memory_store_id == "memstore_fast":
671 fast_list_started.set()
672 else:
673 # Hangs forever under a serial sync (fast hasn't run yet).
674 with anyio.fail_after(10):
675 await fast_list_started.wait()
676 raise RuntimeError("slow store exploded")
677 async for item in resources[memory_store_id].list(memory_store_id, **kwargs):
678 yield item
679
680 return _iter()
681
682 async def retrieve(self, memory_id: str, *, memory_store_id: str, **kwargs: Any) -> Any:
683 return await resources[memory_store_id].retrieve(memory_id, memory_store_id=memory_store_id, **kwargs)
684
685 async def create(self, memory_store_id: str, **kwargs: Any) -> Any:
686 return await resources[memory_store_id].create(memory_store_id, **kwargs)
687
688 async def update(self, memory_id: str, *, memory_store_id: str, **kwargs: Any) -> Any:
689 return await resources[memory_store_id].update(memory_id, memory_store_id=memory_store_id, **kwargs)
690
691 async def delete(self, memory_id: str, *, memory_store_id: str, **kwargs: Any) -> Any:
692 return await resources[memory_store_id].delete(memory_id, memory_store_id=memory_store_id, **kwargs)
693
694 from types import SimpleNamespace
695
696 session = SimpleNamespace(
697 resources=[
698 SimpleNamespace(type="memory_store", memory_store_id=ms, mount_path=None, name=name, access=None)
699 for ms, name in [("memstore_slow", "slow"), ("memstore_fast", "fast")]
700 ]
701 )
702 client = SimpleNamespace(beta=SimpleNamespace(memory_stores=SimpleNamespace(memories=_Router())))
703 stores = SessionMemoryStores(client, workdir=tmp_path) # type: ignore[arg-type]
704 await stores.download(session) # type: ignore[arg-type]
705
706 syncing = True
707 (tmp_path / "memory" / "fast" / "b.md").write_text("v2 from agent")
708 await run_sync(stores)
709
710 # The slow store failed *after* seeing the fast store's listing start —
711 # proof the two ran concurrently — and the fast store still pushed.
712 assert "slow store exploded" in caplog.text
713 assert fast.received == [updated("b.md", "v2 from agent", was="v1")]
714 # The failed store's baseline was kept, so nothing is re-uploaded once it heals.
715 assert (tmp_path / "memory" / "slow" / "a.md").read_text() == "v1"
716
717
718 def test_sync_intervals_below_the_floor_are_rejected(tmp_path: Path) -> None:
719 client, _server = fake_anthropic({})
720 # NaN fails every comparison, so a validator phrased as `< floor` would
721 # accept it — and a NaN interval makes every cadence check due.
722 for interval in (4.9, 1.0, 0, -1.0, float("nan")):
723 with pytest.raises(ValueError, match="at least"):
724 SessionMemoryStores(client, workdir=tmp_path, sync_interval=interval)
725 # The floor itself and "never due" are fine.
726 SessionMemoryStores(client, workdir=tmp_path, sync_interval=5.0)
727 SessionMemoryStores(client, workdir=tmp_path, sync_interval=float("inf"))