Debian Codegraph @

tests/lib/tools/memory_sync/test_delete_discipline.py

raw
1 """Server-delete discipline: a locally deleted file is deleted on the server
2 only after a second sync confirms it, at a bounded rate per sync, and only
3 when server deletes are enabled at all.
4
5 The first sync that sees the file missing records it; a later sync — after
6 `DELETE_CORROBORATION_SECONDS` (skipped on the session's final
7 `finish()`, the session's last sync) and a re-check that the file is still gone and the
8 marker still intact — sends the DELETE. Each sync sends a bounded number
9 of deletes; `sync_deletions="log_only"` only logs them, and
10 `"disabled"` sends none, ever.
11 """
12
13 from __future__ import annotations
14
15 import os
16 import shutil
17 from pathlib import Path
18
19 import pytest
20
21 import anthropic.lib.tools._memories as memories_mod
22 from anthropic.lib.tools._memories import MemoryDeleteMode, SessionMemoryStores
23
24 from .conftest import Clock, run_sync, listing_interrupted_by
25 from ._fake_anthropic import MemoryServer, deleted, updated, fake_anthropic
26
27 LOGGER = "anthropic.lib.tools.agent_toolset"
28
29 ELAPSED = memories_mod.DELETE_CORROBORATION_SECONDS + 1
30
31
32 async def _downloaded(
33 tmp_path: Path, initial: dict[str, str], *, sync_deletions: MemoryDeleteMode = "enabled"
34 ) -> tuple[Path, MemoryServer, SessionMemoryStores]:
35 """A `SessionMemoryStores` with one store already downloaded to disk."""
36 client, server = fake_anthropic(initial)
37 stores = SessionMemoryStores(client, workdir=tmp_path, sync_deletions=sync_deletions)
38 await stores.download(await client.beta.sessions.retrieve("s1"))
39 return tmp_path / "memory" / "notes", server, stores
40
41
42 @pytest.mark.asyncio()
43 async def test_a_local_deletion_is_confirmed_before_it_reaches_the_server(tmp_path: Path, clock: Clock) -> None:
44 local, server, stores = await _downloaded(tmp_path, {"a.md": "v1", "keep.md": "v1"})
45 (local / "a.md").unlink()
46
47 # The first pass only records the absence.
48 await run_sync(stores)
49 assert server.received == []
50 assert server.files == {"a.md": "v1", "keep.md": "v1"}
51
52 # Still inside the window: nothing goes out.
53 clock.now = memories_mod.DELETE_CORROBORATION_SECONDS - 1
54 await run_sync(stores)
55 assert server.received == []
56
57 # Window elapsed and the file is still gone: the guarded delete is sent.
58 clock.now = ELAPSED
59 await run_sync(stores)
60 assert server.received == [deleted("a.md", was="v1")]
61 assert server.files == {"keep.md": "v1"}
62
63
64 @pytest.mark.asyncio()
65 async def test_a_file_that_reappears_is_not_deleted_and_leaves_pending(tmp_path: Path, clock: Clock) -> None:
66 local, server, stores = await _downloaded(tmp_path, {"a.md": "v1"})
67 (local / "a.md").unlink()
68 await run_sync(stores)
69
70 (local / "a.md").write_text("v1")
71 clock.now = ELAPSED
72 await run_sync(stores)
73 assert server.received == []
74 assert server.files == {"a.md": "v1"}
75
76 # The reappearance cleared the pending entry: deleting again starts a
77 # fresh window instead of firing on the stale observation.
78 (local / "a.md").unlink()
79 await run_sync(stores)
80 assert server.received == []
81 clock.now = 2 * ELAPSED
82 await run_sync(stores)
83 assert server.received == [deleted("a.md", was="v1")]
84
85
86 @pytest.mark.asyncio()
87 async def test_disabled_mode_never_deletes_but_still_syncs(
88 tmp_path: Path, clock: Clock, caplog: pytest.LogCaptureFixture
89 ) -> None:
90 caplog.set_level("DEBUG", logger=LOGGER)
91 local, server, stores = await _downloaded(
92 tmp_path, {"gone.md": "v1", "push.md": "v1", "pull.md": "v1"}, sync_deletions="disabled"
93 )
94 (local / "gone.md").unlink()
95 (local / "push.md").write_text("v2 from agent")
96 server.write("pull.md", "v2 from server")
97
98 await run_sync(stores)
99 clock.now = ELAPSED
100 await run_sync(stores)
101 clock.now = 2 * ELAPSED
102 await run_sync(stores)
103
104 # Uploads and pulls still flow; the deletion never does.
105 assert server.received == [updated("push.md", "v2 from agent", was="v1")]
106 assert server.files == {"gone.md": "v1", "push.md": "v2 from agent", "pull.md": "v2 from server"}
107 assert (local / "pull.md").read_text() == "v2 from server"
108 assert "server deletes are disabled" in caplog.text
109
110
111 @pytest.mark.asyncio()
112 async def test_the_per_pass_cap_spreads_deletes_over_passes(
113 tmp_path: Path, clock: Clock, caplog: pytest.LogCaptureFixture
114 ) -> None:
115 caplog.set_level("WARNING", logger=LOGGER)
116 files = {f"f{i:02d}.md": "v1" for i in range(14)}
117 local, server, stores = await _downloaded(tmp_path, files)
118 doomed = sorted(files)[:12]
119 for name in doomed:
120 (local / name).unlink()
121
122 await run_sync(stores)
123 assert server.received == []
124
125 # cap = max(8, min(50, 14 // 4)) = 8: the first confirming sync stops there.
126 clock.now = ELAPSED
127 await run_sync(stores)
128 assert server.received == [deleted(name, was="v1") for name in doomed[:8]]
129 assert "delete cap reached: sent 8 deletes, held 4 for later syncs" in caplog.text
130
131 # The held-back deletions confirm on the next pass.
132 await run_sync(stores)
133 assert server.received == [deleted(name, was="v1") for name in doomed]
134 assert server.files == {name: "v1" for name in sorted(files)[12:]}
135
136
137 @pytest.mark.asyncio()
138 async def test_the_final_sync_waives_the_window_but_still_re_checks(tmp_path: Path) -> None:
139 """A deletion made in a session shorter than the waiting window still
140 goes through: the final sync skips the wait, and the re-check just
141 before the delete stands in for the second observation."""
142 local, server, stores = await _downloaded(tmp_path, {"a.md": "v1", "keep.md": "v1"})
143 (local / "a.md").unlink()
144
145 await stores.finish()
146
147 assert server.received == [deleted("a.md", was="v1")]
148 assert server.files == {"keep.md": "v1"}
149
150
151 @pytest.mark.asyncio()
152 async def test_a_folder_destroyed_mid_sync_sends_no_deletes(tmp_path: Path, clock: Clock) -> None:
153 """The directory scan saw an intact folder, then the folder vanished
154 while the server listing was in flight: the re-check just before the
155 delete must notice the marker is gone and hold every delete."""
156 local, server, stores = await _downloaded(tmp_path, {"a.md": "v1", "keep.md": "v1"})
157 (local / "a.md").unlink()
158 await run_sync(stores)
159 clock.now = ELAPSED
160
161 with listing_interrupted_by(stores, lambda: shutil.rmtree(local)):
162 await run_sync(stores)
163
164 assert server.received == []
165 assert server.files == {"a.md": "v1", "keep.md": "v1"}
166
167
168 @pytest.mark.skipif(os.geteuid() == 0, reason="permission checks do not bind root")
169 @pytest.mark.asyncio()
170 async def test_an_unreadable_subdirectory_fails_the_pass_instead_of_reading_as_deletions(
171 tmp_path: Path, clock: Clock, caplog: pytest.LogCaptureFixture
172 ) -> None:
173 """Files under a directory the scan cannot enter are not treated as deleted."""
174 caplog.set_level("WARNING", logger=LOGGER)
175 local, server, stores = await _downloaded(tmp_path, {"sub/a.md": "v1", "sub/b.md": "v1", "top.md": "v1"})
176 (local / "top.md").write_text("v2")
177 (local / "sub").chmod(0o000)
178 try:
179 await run_sync(stores)
180 clock.now = ELAPSED
181 await run_sync(stores)
182 finally:
183 (local / "sub").chmod(0o700)
184
185 assert server.received == []
186 assert caplog.text.count("memory sync failed") == 2
187
188 # Readable again: the edit goes out and nothing is deleted.
189 clock.now = 2 * ELAPSED
190 await run_sync(stores)
191 assert server.received == [updated("top.md", "v2", was="v1")]
192 assert server.files == {"sub/a.md": "v1", "sub/b.md": "v1", "top.md": "v2"}
193
194
195 @pytest.mark.asyncio()
196 async def test_a_recovery_re_download_clears_pending_deletes(tmp_path: Path, clock: Clock) -> None:
197 """The re-download rebuilt the disk, so an absence observed before it says
198 nothing about the rebuilt folder."""
199 local, server, stores = await _downloaded(tmp_path, {"a.md": "v1"})
200 (local / "a.md").unlink()
201 await run_sync(stores)
202
203 clock.now = ELAPSED
204 shutil.rmtree(local)
205 await run_sync(stores)
206 assert (local / "a.md").read_text() == "v1"
207
208 # A fresh deletion starts a fresh window — the pre-recovery observation
209 # must not corroborate it.
210 (local / "a.md").unlink()
211 await run_sync(stores)
212 assert server.received == []
213 clock.now = 2 * ELAPSED
214 await run_sync(stores)
215 assert server.received == [deleted("a.md", was="v1")]
216
217
218 @pytest.mark.asyncio()
219 async def test_log_only_mode_logs_the_delete_but_never_sends_it(
220 tmp_path: Path, clock: Clock, caplog: pytest.LogCaptureFixture
221 ) -> None:
222 """The dry-run setting: the full pipeline runs — window, re-checks, cap —
223 but the confirmed delete is logged instead of sent, on every sync while
224 the file stays missing."""
225 caplog.set_level("INFO", logger=LOGGER)
226 local, server, stores = await _downloaded(tmp_path, {"a.md": "v1", "keep.md": "v1"}, sync_deletions="log_only")
227 (local / "a.md").unlink()
228
229 await run_sync(stores)
230 assert "log-only" not in caplog.text # still inside the waiting window
231
232 clock.now = ELAPSED
233 await run_sync(stores)
234 await run_sync(stores)
235
236 assert server.received == []
237 assert server.files == {"a.md": "v1", "keep.md": "v1"}
238 assert caplog.text.count("log-only: sync would delete this memory on the server path=a.md") == 2
239
240
241 @pytest.mark.asyncio()
242 async def test_finish_runs_once_and_a_second_call_raises(tmp_path: Path) -> None:
243 local, server, stores = await _downloaded(tmp_path, {"a.md": "v1"})
244 (local / "a.md").write_text("v2")
245
246 await stores.finish()
247 assert server.files == {"a.md": "v2"}
248
249 with pytest.raises(RuntimeError, match="finish"):
250 await stores.finish()