accli 2.1.6__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {accli-2.1.6 → accli-2.2.0}/PKG-INFO +1 -1
  2. {accli-2.1.6 → accli-2.2.0}/accli/_version.py +1 -1
  3. {accli-2.1.6 → accli-2.2.0}/accli/cli.py +70 -2
  4. accli-2.2.0/accli/xet_cache.py +277 -0
  5. {accli-2.1.6 → accli-2.2.0}/accli.egg-info/PKG-INFO +1 -1
  6. {accli-2.1.6 → accli-2.2.0}/accli.egg-info/SOURCES.txt +3 -1
  7. accli-2.2.0/tests/test_xet_cache.py +107 -0
  8. {accli-2.1.6 → accli-2.2.0}/LICENSE +0 -0
  9. {accli-2.1.6 → accli-2.2.0}/README.md +0 -0
  10. {accli-2.1.6 → accli-2.2.0}/accli/AcceleratorJobProjectService.py +0 -0
  11. {accli-2.1.6 → accli-2.2.0}/accli/AcceleratorTaskDispatcher.py +0 -0
  12. {accli-2.1.6 → accli-2.2.0}/accli/AcceleratorTerminalCliProjectService.py +0 -0
  13. {accli-2.1.6 → accli-2.2.0}/accli/CsvRegionalTimeseriesValidator.py +0 -0
  14. {accli-2.1.6 → accli-2.2.0}/accli/__init__.py +0 -0
  15. {accli-2.1.6 → accli-2.2.0}/accli/__main__.py +0 -0
  16. {accli-2.1.6 → accli-2.2.0}/accli/acc_logo.ico +0 -0
  17. {accli-2.1.6 → accli-2.2.0}/accli/acc_logo.png +0 -0
  18. {accli-2.1.6 → accli-2.2.0}/accli/cleanup-nfs.ps1 +0 -0
  19. {accli-2.1.6 → accli-2.2.0}/accli/common.py +0 -0
  20. {accli-2.1.6 → accli-2.2.0}/accli/gui.py +0 -0
  21. {accli-2.1.6 → accli-2.2.0}/accli/job_views.py +0 -0
  22. {accli-2.1.6 → accli-2.2.0}/accli/log_timeline.py +0 -0
  23. {accli-2.1.6 → accli-2.2.0}/accli/mount_downloader.py +0 -0
  24. {accli-2.1.6 → accli-2.2.0}/accli/nfs_watcher.py +0 -0
  25. {accli-2.1.6 → accli-2.2.0}/accli/refresh_explorer.ps1 +0 -0
  26. {accli-2.1.6 → accli-2.2.0}/accli/setup-nfs.ps1 +0 -0
  27. {accli-2.1.6 → accli-2.2.0}/accli/token.py +0 -0
  28. {accli-2.1.6 → accli-2.2.0}/accli/version_checker.py +0 -0
  29. {accli-2.1.6 → accli-2.2.0}/accli.egg-info/dependency_links.txt +0 -0
  30. {accli-2.1.6 → accli-2.2.0}/accli.egg-info/entry_points.txt +0 -0
  31. {accli-2.1.6 → accli-2.2.0}/accli.egg-info/requires.txt +0 -0
  32. {accli-2.1.6 → accli-2.2.0}/accli.egg-info/top_level.txt +0 -0
  33. {accli-2.1.6 → accli-2.2.0}/pyproject.toml +0 -0
  34. {accli-2.1.6 → accli-2.2.0}/setup.cfg +0 -0
  35. {accli-2.1.6 → accli-2.2.0}/tests/test_jobs_commands.py +0 -0
  36. {accli-2.1.6 → accli-2.2.0}/tests/test_log_timeline.py +0 -0
  37. {accli-2.1.6 → accli-2.2.0}/tests/test_logs_command.py +0 -0
  38. {accli-2.1.6 → accli-2.2.0}/tests/test_mount_lifecycle.py +0 -0
  39. {accli-2.1.6 → accli-2.2.0}/tests/test_update_check.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: accli
3
- Version: 2.1.6
3
+ Version: 2.2.0
4
4
  Summary: IIASA Accelerator Client
5
5
  Author-email: Wrufesh S <wrufesh@gmail.com>
6
6
  License: The MIT License (MIT)
@@ -1,3 +1,3 @@
1
1
  # Please strictly put double quote to use this info for git tag
2
2
  # Read a developer guide for git tag command with regex
3
- VERSION = "v2.1.6"
3
+ VERSION = "v2.2.0"
@@ -27,6 +27,7 @@ from typing_extensions import Annotated
27
27
 
28
28
  from ._version import VERSION
29
29
  from . import mount_downloader
30
+ from . import xet_cache
30
31
  from .version_checker import check_for_updates, get_upgrade_instruction
31
32
 
32
33
  warnings.filterwarnings('ignore')
@@ -461,6 +462,17 @@ def copy(
461
462
  server_url = get_server_url()
462
463
  cas_token, access_token, expires_at = exchange_refresh_token(project_slug)
463
464
 
465
+ # Use accli's own per-server Xet cache (the one `mount start` uses), so `accli cache clear`
466
+ # never touches other Hugging Face tools. hf-xet reads this when a session is created.
467
+ xet_dir = xet_cache.xet_cache_dir(server_url)
468
+ xet_dir.mkdir(parents=True, exist_ok=True)
469
+ os.environ["HF_XET_CACHE"] = str(xet_dir)
470
+
471
+ # A stale cache only matters for uploads: stop if the server's storage was cleaned up
472
+ # since this machine last cleared its cache.
473
+ if is_dest_remote:
474
+ xet_cache.check_gc_id(server_url, access_token)
475
+
464
476
  term_cli_project_service = AcceleratorTerminalCliProjectService(
465
477
  user_token=access_token,
466
478
  server_url=server_url,
@@ -735,6 +747,7 @@ def copy(
735
747
  completed_in_previous_batches = 0
736
748
 
737
749
  session = hf_xet.XetSession()
750
+ upload_marker = xet_cache.CacheInUse().__enter__()
738
751
  for batch_index, (b_paths, b_remotes) in enumerate(batches, 1):
739
752
  progress.print(f"[cyan]Processing batch {batch_index}/{len(batches)}...[/cyan]")
740
753
 
@@ -773,6 +786,8 @@ def copy(
773
786
  upload_results = [(p, sha, h.result()) for p, sha, h in handles]
774
787
  except Exception as e:
775
788
  progress.print(f"[bold red]ERROR: Upload failed for batch {batch_index}: {e}[/bold red]")
789
+ if xet_cache.is_shard_rejection(e):
790
+ progress.print(xet_cache.SHARD_REJECTED_HINT)
776
791
  raise typer.Exit(1)
777
792
 
778
793
  progress.print("[cyan]Computing SHA-256 hashes and registering metadata for batch...[/cyan]")
@@ -820,10 +835,58 @@ def copy(
820
835
  except Exception as e:
821
836
  progress.print(f"[bold red]ERROR: Bulk metadata registration failed for batch {batch_index}: {e}[/bold red]")
822
837
  raise typer.Exit(1)
838
+ upload_marker.__exit__(None, None, None)
823
839
 
824
840
  print("[bold green][OK] Upload completed successfully![/bold green]")
825
841
 
826
842
 
843
+ # --- Cache commands group ---
844
+ cache_app = typer.Typer(
845
+ help="Inspect or clear accli's local Xet cache.",
846
+ no_args_is_help=True
847
+ )
848
+ app.add_typer(cache_app, name="cache")
849
+
850
+
851
+ def _cache_server_url() -> str:
852
+ server_url = get_server_url()
853
+ if not server_url:
854
+ print("[bold red]ERROR: No server found. Please run 'accli login' first.[/bold red]")
855
+ raise typer.Exit(1)
856
+ return server_url
857
+
858
+
859
+ @cache_app.command("info")
860
+ def cache_info():
861
+ """
862
+ Show the Xet cache folder, its size, and the local vs server GC ID.
863
+ """
864
+ server_url = _cache_server_url()
865
+ try:
866
+ _, access_token, _ = exchange_refresh_token("")
867
+ except typer.Exit:
868
+ access_token = None
869
+ xet_cache.cache_info(server_url, access_token)
870
+
871
+
872
+ @cache_app.command("clear")
873
+ def cache_clear(
874
+ all_servers: Annotated[bool, typer.Option("--all", help="Delete the whole accli Xet cache, for every server.")] = False,
875
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip the confirmation prompt.")] = False,
876
+ force: Annotated[bool, typer.Option("--force", help="Clear even if a mount or another accli upload looks active.")] = False,
877
+ ):
878
+ """
879
+ Delete the Xet cache for the current server, then save the server's GC ID.
880
+ """
881
+ server_url = _cache_server_url()
882
+
883
+ def fetch_access_token() -> str:
884
+ _, access_token, _ = exchange_refresh_token("")
885
+ return access_token
886
+
887
+ xet_cache.clear_cache(server_url, fetch_access_token, all_servers=all_servers, yes=yes, force=force)
888
+
889
+
827
890
  # --- Mount commands group ---
828
891
  mount_app = typer.Typer(
829
892
  help="Manage mounting Accelerator project spaces locally using hf-mount.",
@@ -1506,6 +1569,11 @@ def mount_start(
1506
1569
  print(f"[cyan]Validating project '{project_slug}'...[/cyan]")
1507
1570
  validate_project_slug(server_url, project_slug)
1508
1571
 
1572
+ # hf-mount writes through the same Xet cache: stop if it may reference cleaned-up data.
1573
+ # The access token from validation is cached in memory, so this makes no extra request.
1574
+ _, mount_access_token, _ = exchange_refresh_token(project_slug)
1575
+ xet_cache.check_gc_id(server_url, mount_access_token)
1576
+
1509
1577
  # Ensure binaries are downloaded and cached
1510
1578
  try:
1511
1579
  mount_downloader.ensure_binaries(version=binary_version, use_fuse=fuse)
@@ -1572,9 +1640,9 @@ def mount_start(
1572
1640
  env["ACC_CAS_ENDPOINT"] = f"{server_url.rstrip('/')}/api/xet-cas"
1573
1641
  env["ACC_TOKEN"] = token
1574
1642
  cache_base = Path("C:/ProgramData/accli/cache") if sys_name == "Windows" else Path.home() / ".accli" / "cache"
1575
- (cache_base / "xet").mkdir(parents=True, exist_ok=True)
1643
+ xet_cache.xet_cache_dir(server_url).mkdir(parents=True, exist_ok=True)
1576
1644
  (cache_base / "hf-mount").mkdir(parents=True, exist_ok=True)
1577
- env["HF_XET_CACHE"] = str(cache_base / "xet")
1645
+ env["HF_XET_CACHE"] = str(xet_cache.xet_cache_dir(server_url))
1578
1646
  env["HF_HOME"] = str(cache_base)
1579
1647
  env["XDG_CACHE_HOME"] = str(cache_base)
1580
1648
 
@@ -0,0 +1,277 @@
1
+ """
2
+ Local Xet cache handling and GC ID sync.
3
+
4
+ The server puts a GC ID in every access token (claim ``xet_gc_id``) and changes it after each
5
+ storage cleanup. accli saves the ID it last synced with, per server, in ``~/.accli/state.json``.
6
+ When the two differ, the local Xet cache may point at data the server removed, so uploads stop
7
+ and ask the user to run ``accli cache clear``.
8
+
9
+ Each server gets its own cache folder, used as HF_XET_CACHE by ``copy`` and ``mount start``,
10
+ so clearing it never touches other Hugging Face tools or other servers.
11
+ """
12
+ import base64
13
+ import json
14
+ import os
15
+ import platform
16
+ import shutil
17
+ import subprocess
18
+ from pathlib import Path
19
+ from typing import Optional
20
+ from urllib.parse import urlparse
21
+
22
+ import typer
23
+ from rich import print
24
+
25
+ from accli.token import get_db_path
26
+
27
+ GC_ID_CLAIM = "xet_gc_id"
28
+
29
+ MISMATCH_MESSAGE = (
30
+ "[bold red]Server storage was cleaned up since this machine last cleared its Xet cache.[/bold red]\n"
31
+ "Run: [bold]accli cache clear[/bold]\n"
32
+ "then run this command again."
33
+ )
34
+
35
+ SHARD_REJECTED_HINT = (
36
+ "[yellow]The server rejected the upload's metadata (HTTP 400 on /shards). This usually means the "
37
+ "local Xet cache references data that was cleaned up on the server.[/yellow]\n"
38
+ "Run: [bold]accli cache clear[/bold]\n"
39
+ "then run the upload again."
40
+ )
41
+
42
+
43
+ # ---- Paths ----
44
+
45
+ def cache_base_dir() -> Path:
46
+ """Base folder of accli's caches (same as `mount start` uses)."""
47
+ if platform.system() == "Windows":
48
+ return Path("C:/ProgramData/accli/cache")
49
+ return Path.home() / ".accli" / "cache"
50
+
51
+
52
+ def xet_root_dir() -> Path:
53
+ return cache_base_dir() / "xet"
54
+
55
+
56
+ def _server_key(server_url: str) -> str:
57
+ parsed = urlparse(server_url or "")
58
+ host = parsed.netloc or parsed.path or "default"
59
+ return "".join(c if c.isalnum() or c in "-._" else "_" for c in host.lower()) or "default"
60
+
61
+
62
+ def xet_cache_dir(server_url: str) -> Path:
63
+ """HF_XET_CACHE folder for one server."""
64
+ return xet_root_dir() / _server_key(server_url)
65
+
66
+
67
+ def _active_dir() -> Path:
68
+ return cache_base_dir() / "xet-active"
69
+
70
+
71
+ def _state_path() -> Path:
72
+ return Path(get_db_path()).parent / "state.json"
73
+
74
+
75
+ # ---- State (saved GC IDs) ----
76
+
77
+ def _load_state() -> dict:
78
+ try:
79
+ return json.loads(_state_path().read_text(encoding="utf-8"))
80
+ except Exception:
81
+ return {}
82
+
83
+
84
+ def get_saved_gc_id(server_url: str) -> Optional[str]:
85
+ return _load_state().get("servers", {}).get(server_url, {}).get(GC_ID_CLAIM)
86
+
87
+
88
+ def save_gc_id(server_url: str, gc_id: Optional[str]) -> None:
89
+ state = _load_state()
90
+ servers = state.setdefault("servers", {})
91
+ entry = servers.setdefault(server_url, {})
92
+ if gc_id is None:
93
+ entry.pop(GC_ID_CLAIM, None)
94
+ else:
95
+ entry[GC_ID_CLAIM] = gc_id
96
+ path = _state_path()
97
+ tmp = path.with_suffix(".json.tmp")
98
+ tmp.write_text(json.dumps(state, indent=2), encoding="utf-8")
99
+ os.replace(tmp, path)
100
+
101
+
102
+ # ---- Token ----
103
+
104
+ def decode_gc_id(access_token: str) -> Optional[str]:
105
+ """Reads the GC ID claim from the access token's payload. No signature check is needed:
106
+ the value is only compared for equality. Returns None if the token has no claim."""
107
+ try:
108
+ payload_b64 = access_token.split(".")[1]
109
+ payload_b64 += "=" * (-len(payload_b64) % 4)
110
+ payload = json.loads(base64.urlsafe_b64decode(payload_b64))
111
+ value = payload.get(GC_ID_CLAIM)
112
+ return str(value) if value else None
113
+ except Exception:
114
+ return None
115
+
116
+
117
+ def check_gc_id(server_url: str, access_token: str) -> None:
118
+ """Stops with the 'clear your cache' message if the server's GC ID differs from the saved one.
119
+
120
+ No claim in the token (ID not set on the server, or an older server): no check.
121
+ No saved ID counts as a mismatch.
122
+ """
123
+ server_id = decode_gc_id(access_token)
124
+ if server_id is None:
125
+ return
126
+ if get_saved_gc_id(server_url) != server_id:
127
+ print(MISMATCH_MESSAGE)
128
+ raise typer.Exit(1)
129
+
130
+
131
+ def is_shard_rejection(error: Exception) -> bool:
132
+ text = str(error)
133
+ return "400" in text and "/shards" in text
134
+
135
+
136
+ # ---- Activity (refuse to clear while the cache is in use) ----
137
+
138
+ def _pid_alive(pid: int) -> bool:
139
+ if pid <= 0:
140
+ return False
141
+ if platform.system() == "Windows":
142
+ try:
143
+ res = subprocess.run(["tasklist", "/FI", f"PID eq {pid}"], capture_output=True, text=True, errors="replace")
144
+ return str(pid) in (res.stdout or "")
145
+ except Exception:
146
+ return False
147
+ try:
148
+ os.kill(pid, 0)
149
+ return True
150
+ except ProcessLookupError:
151
+ return False
152
+ except PermissionError:
153
+ return True
154
+ except Exception:
155
+ return False
156
+
157
+
158
+ class CacheInUse:
159
+ """Marks this process as using the Xet cache (for `copy`), so `cache clear` refuses meanwhile."""
160
+
161
+ def __enter__(self):
162
+ try:
163
+ _active_dir().mkdir(parents=True, exist_ok=True)
164
+ self._marker = _active_dir() / str(os.getpid())
165
+ self._marker.write_text("copy", encoding="utf-8")
166
+ except Exception:
167
+ self._marker = None
168
+ return self
169
+
170
+ def __exit__(self, *exc):
171
+ try:
172
+ if self._marker:
173
+ self._marker.unlink(missing_ok=True)
174
+ except Exception:
175
+ pass
176
+ return False
177
+
178
+
179
+ def _active_uploads() -> list[int]:
180
+ pids = []
181
+ try:
182
+ for marker in _active_dir().iterdir():
183
+ try:
184
+ pid = int(marker.name)
185
+ except ValueError:
186
+ continue
187
+ if pid != os.getpid() and _pid_alive(pid):
188
+ pids.append(pid)
189
+ elif pid != os.getpid():
190
+ marker.unlink(missing_ok=True)
191
+ except FileNotFoundError:
192
+ pass
193
+ return pids
194
+
195
+
196
+ def _mount_running() -> bool:
197
+ if platform.system() == "Windows":
198
+ try:
199
+ res = subprocess.run(["tasklist", "/FI", "IMAGENAME eq hf-mount-nfs.exe"], capture_output=True, text=True, errors="replace")
200
+ return "hf-mount-nfs.exe" in (res.stdout or "")
201
+ except Exception:
202
+ return False
203
+ try:
204
+ res = subprocess.run(["pgrep", "-f", "hf-mount"], capture_output=True, text=True)
205
+ return res.returncode == 0
206
+ except Exception:
207
+ return False
208
+
209
+
210
+ # ---- Commands ----
211
+
212
+ def _folder_size(path: Path) -> int:
213
+ total = 0
214
+ for root, _dirs, files in os.walk(path):
215
+ for f in files:
216
+ try:
217
+ total += (Path(root) / f).stat().st_size
218
+ except OSError:
219
+ pass
220
+ return total
221
+
222
+
223
+ def _human(n: int) -> str:
224
+ for unit in ("B", "KB", "MB", "GB", "TB"):
225
+ if n < 1024 or unit == "TB":
226
+ return f"{n:.1f} {unit}" if unit != "B" else f"{n} B"
227
+ n /= 1024
228
+ return f"{n} B"
229
+
230
+
231
+ def cache_info(server_url: str, access_token: Optional[str]) -> None:
232
+ folder = xet_cache_dir(server_url)
233
+ size = _folder_size(folder) if folder.exists() else 0
234
+ saved = get_saved_gc_id(server_url)
235
+ server_id = decode_gc_id(access_token) if access_token else None
236
+ print(f"[cyan]Server:[/cyan] {server_url}")
237
+ print(f"[cyan]Xet cache folder:[/cyan] {folder}")
238
+ print(f"[cyan]Size:[/cyan] {_human(size)}")
239
+ print(f"[cyan]Local GC ID:[/cyan] {saved or '(none)'}")
240
+ print(f"[cyan]Server GC ID:[/cyan] {server_id or '(not set)'}")
241
+ if server_id is not None and saved != server_id:
242
+ print("[yellow]The IDs differ: run 'accli cache clear' before your next upload.[/yellow]")
243
+
244
+
245
+ def clear_cache(server_url: str, fetch_access_token, all_servers: bool, yes: bool, force: bool) -> None:
246
+ """Deletes the Xet cache, then (only if that worked) saves the server's current GC ID."""
247
+ target = xet_root_dir() if all_servers else xet_cache_dir(server_url)
248
+
249
+ if not force:
250
+ uploads = _active_uploads()
251
+ if uploads:
252
+ print(f"[bold red]ERROR: Another accli upload is running (pid {', '.join(map(str, uploads))}). "
253
+ "Wait for it to finish, or use --force.[/bold red]")
254
+ raise typer.Exit(1)
255
+ if _mount_running():
256
+ print("[bold red]ERROR: A mount is running and uses this cache. Run 'accli mount stop' first, "
257
+ "or use --force.[/bold red]")
258
+ raise typer.Exit(1)
259
+
260
+ if not yes:
261
+ if not typer.confirm(f"Delete the Xet cache at {target}?"):
262
+ raise typer.Exit(0)
263
+
264
+ if target.exists():
265
+ try:
266
+ shutil.rmtree(target)
267
+ except Exception as e:
268
+ # The old ID stays saved, so the next upload asks again.
269
+ print(f"[bold red]ERROR: Could not delete {target}: {e}[/bold red]")
270
+ raise typer.Exit(1)
271
+ print(f"[green]Deleted the Xet cache at {target}.[/green]")
272
+
273
+ # An empty cache is valid for any GC ID, so fetching it after the delete is safe.
274
+ server_id = decode_gc_id(fetch_access_token())
275
+ save_gc_id(server_url, server_id)
276
+ if server_id:
277
+ print(f"[green]Synced with the server's GC ID ({server_id}). You can upload again.[/green]")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: accli
3
- Version: 2.1.6
3
+ Version: 2.2.0
4
4
  Summary: IIASA Accelerator Client
5
5
  Author-email: Wrufesh S <wrufesh@gmail.com>
6
6
  License: The MIT License (MIT)
@@ -22,6 +22,7 @@ accli/refresh_explorer.ps1
22
22
  accli/setup-nfs.ps1
23
23
  accli/token.py
24
24
  accli/version_checker.py
25
+ accli/xet_cache.py
25
26
  accli.egg-info/PKG-INFO
26
27
  accli.egg-info/SOURCES.txt
27
28
  accli.egg-info/dependency_links.txt
@@ -32,4 +33,5 @@ tests/test_jobs_commands.py
32
33
  tests/test_log_timeline.py
33
34
  tests/test_logs_command.py
34
35
  tests/test_mount_lifecycle.py
35
- tests/test_update_check.py
36
+ tests/test_update_check.py
37
+ tests/test_xet_cache.py
@@ -0,0 +1,107 @@
1
+ import base64
2
+ import json
3
+ import sys
4
+ import types
5
+
6
+ import pytest
7
+ import typer
8
+
9
+ # accli/__init__ imports the CLI, which imports hf_xet; these tests don't need it.
10
+ sys.modules.setdefault("hf_xet", types.ModuleType("hf_xet"))
11
+
12
+ from accli import xet_cache # noqa: E402
13
+
14
+
15
+ def make_token(payload: dict) -> str:
16
+ def b64(obj):
17
+ return base64.urlsafe_b64encode(json.dumps(obj).encode()).decode().rstrip("=")
18
+ return f"{b64({'alg': 'ES256'})}.{b64(payload)}.signature"
19
+
20
+
21
+ SERVER = "https://accelerator.example.org"
22
+
23
+
24
+ @pytest.fixture(autouse=True)
25
+ def home(tmp_path, monkeypatch):
26
+ monkeypatch.setenv("HOME", str(tmp_path))
27
+ monkeypatch.delenv("SUDO_USER", raising=False)
28
+ monkeypatch.delenv("PKEXEC_UID", raising=False)
29
+ monkeypatch.setattr(xet_cache, "_mount_running", lambda: False)
30
+ return tmp_path
31
+
32
+
33
+ def test_decode_gc_id():
34
+ assert xet_cache.decode_gc_id(make_token({"type": "TERM_CLI", "xet_gc_id": "a3f9c1"})) == "a3f9c1"
35
+ assert xet_cache.decode_gc_id(make_token({"type": "TERM_CLI"})) is None
36
+ assert xet_cache.decode_gc_id("not-a-jwt") is None
37
+
38
+
39
+ def test_no_claim_skips_check():
40
+ xet_cache.check_gc_id(SERVER, make_token({"type": "TERM_CLI"}))
41
+
42
+
43
+ def test_missing_saved_id_is_a_mismatch():
44
+ with pytest.raises(typer.Exit):
45
+ xet_cache.check_gc_id(SERVER, make_token({"xet_gc_id": "a3f9c1"}))
46
+
47
+
48
+ def test_matching_id_passes_and_other_id_stops():
49
+ xet_cache.save_gc_id(SERVER, "a3f9c1")
50
+ xet_cache.check_gc_id(SERVER, make_token({"xet_gc_id": "a3f9c1"}))
51
+ with pytest.raises(typer.Exit):
52
+ xet_cache.check_gc_id(SERVER, make_token({"xet_gc_id": "b7e2d0"}))
53
+
54
+
55
+ def test_ids_are_saved_per_server():
56
+ xet_cache.save_gc_id(SERVER, "a3f9c1")
57
+ xet_cache.save_gc_id("https://other.example.org", "zzz")
58
+ assert xet_cache.get_saved_gc_id(SERVER) == "a3f9c1"
59
+ assert xet_cache.get_saved_gc_id("https://other.example.org") == "zzz"
60
+
61
+
62
+ def test_clear_deletes_cache_then_saves_server_id():
63
+ folder = xet_cache.xet_cache_dir(SERVER)
64
+ (folder / "shard-cache").mkdir(parents=True)
65
+ (folder / "shard-cache" / "x.mdb").write_bytes(b"data")
66
+
67
+ xet_cache.clear_cache(SERVER, lambda: make_token({"xet_gc_id": "a3f9c1"}), all_servers=False, yes=True, force=False)
68
+
69
+ assert not folder.exists()
70
+ assert xet_cache.get_saved_gc_id(SERVER) == "a3f9c1"
71
+ xet_cache.check_gc_id(SERVER, make_token({"xet_gc_id": "a3f9c1"}))
72
+
73
+
74
+ def test_failed_delete_keeps_old_id(monkeypatch):
75
+ xet_cache.save_gc_id(SERVER, "old")
76
+ xet_cache.xet_cache_dir(SERVER).mkdir(parents=True)
77
+
78
+ def boom(_path):
79
+ raise OSError("busy")
80
+ monkeypatch.setattr(xet_cache.shutil, "rmtree", boom)
81
+
82
+ with pytest.raises(typer.Exit):
83
+ xet_cache.clear_cache(SERVER, lambda: make_token({"xet_gc_id": "new"}), all_servers=False, yes=True, force=False)
84
+ assert xet_cache.get_saved_gc_id(SERVER) == "old"
85
+
86
+
87
+ def test_clear_refuses_while_mount_runs(monkeypatch):
88
+ monkeypatch.setattr(xet_cache, "_mount_running", lambda: True)
89
+ with pytest.raises(typer.Exit):
90
+ xet_cache.clear_cache(SERVER, lambda: make_token({}), all_servers=False, yes=True, force=False)
91
+ # --force overrides
92
+ xet_cache.clear_cache(SERVER, lambda: make_token({}), all_servers=False, yes=True, force=True)
93
+
94
+
95
+ def test_clear_refuses_while_another_upload_runs(monkeypatch):
96
+ marker_dir = xet_cache._active_dir()
97
+ marker_dir.mkdir(parents=True)
98
+ (marker_dir / "424242").write_text("copy")
99
+ monkeypatch.setattr(xet_cache, "_pid_alive", lambda pid: pid == 424242)
100
+ with pytest.raises(typer.Exit):
101
+ xet_cache.clear_cache(SERVER, lambda: make_token({}), all_servers=False, yes=True, force=False)
102
+
103
+
104
+ def test_shard_rejection_detection():
105
+ err = Exception("Request error: HTTP status client error (400 Bad Request) for url (https://x/api/xet-cas/v1/shards)")
106
+ assert xet_cache.is_shard_rejection(err)
107
+ assert not xet_cache.is_shard_rejection(Exception("HTTP status server error (503) for url (https://x/v1/shards)"))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes