accli 2.1.5__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.5 → accli-2.2.0}/PKG-INFO +1 -1
  2. {accli-2.1.5 → accli-2.2.0}/accli/_version.py +1 -1
  3. {accli-2.1.5 → accli-2.2.0}/accli/cli.py +126 -5
  4. {accli-2.1.5 → accli-2.2.0}/accli/mount_downloader.py +1 -1
  5. {accli-2.1.5 → accli-2.2.0}/accli/nfs_watcher.py +21 -2
  6. accli-2.2.0/accli/xet_cache.py +277 -0
  7. {accli-2.1.5 → accli-2.2.0}/accli.egg-info/PKG-INFO +1 -1
  8. {accli-2.1.5 → accli-2.2.0}/accli.egg-info/SOURCES.txt +3 -1
  9. accli-2.2.0/tests/test_xet_cache.py +107 -0
  10. {accli-2.1.5 → accli-2.2.0}/LICENSE +0 -0
  11. {accli-2.1.5 → accli-2.2.0}/README.md +0 -0
  12. {accli-2.1.5 → accli-2.2.0}/accli/AcceleratorJobProjectService.py +0 -0
  13. {accli-2.1.5 → accli-2.2.0}/accli/AcceleratorTaskDispatcher.py +0 -0
  14. {accli-2.1.5 → accli-2.2.0}/accli/AcceleratorTerminalCliProjectService.py +0 -0
  15. {accli-2.1.5 → accli-2.2.0}/accli/CsvRegionalTimeseriesValidator.py +0 -0
  16. {accli-2.1.5 → accli-2.2.0}/accli/__init__.py +0 -0
  17. {accli-2.1.5 → accli-2.2.0}/accli/__main__.py +0 -0
  18. {accli-2.1.5 → accli-2.2.0}/accli/acc_logo.ico +0 -0
  19. {accli-2.1.5 → accli-2.2.0}/accli/acc_logo.png +0 -0
  20. {accli-2.1.5 → accli-2.2.0}/accli/cleanup-nfs.ps1 +0 -0
  21. {accli-2.1.5 → accli-2.2.0}/accli/common.py +0 -0
  22. {accli-2.1.5 → accli-2.2.0}/accli/gui.py +0 -0
  23. {accli-2.1.5 → accli-2.2.0}/accli/job_views.py +0 -0
  24. {accli-2.1.5 → accli-2.2.0}/accli/log_timeline.py +0 -0
  25. {accli-2.1.5 → accli-2.2.0}/accli/refresh_explorer.ps1 +0 -0
  26. {accli-2.1.5 → accli-2.2.0}/accli/setup-nfs.ps1 +0 -0
  27. {accli-2.1.5 → accli-2.2.0}/accli/token.py +0 -0
  28. {accli-2.1.5 → accli-2.2.0}/accli/version_checker.py +0 -0
  29. {accli-2.1.5 → accli-2.2.0}/accli.egg-info/dependency_links.txt +0 -0
  30. {accli-2.1.5 → accli-2.2.0}/accli.egg-info/entry_points.txt +0 -0
  31. {accli-2.1.5 → accli-2.2.0}/accli.egg-info/requires.txt +0 -0
  32. {accli-2.1.5 → accli-2.2.0}/accli.egg-info/top_level.txt +0 -0
  33. {accli-2.1.5 → accli-2.2.0}/pyproject.toml +0 -0
  34. {accli-2.1.5 → accli-2.2.0}/setup.cfg +0 -0
  35. {accli-2.1.5 → accli-2.2.0}/tests/test_jobs_commands.py +0 -0
  36. {accli-2.1.5 → accli-2.2.0}/tests/test_log_timeline.py +0 -0
  37. {accli-2.1.5 → accli-2.2.0}/tests/test_logs_command.py +0 -0
  38. {accli-2.1.5 → accli-2.2.0}/tests/test_mount_lifecycle.py +0 -0
  39. {accli-2.1.5 → 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.5
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.5"
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.",
@@ -1107,7 +1170,56 @@ def ensure_nfs_daemon_stable(timeout: float) -> bool:
1107
1170
  return wait_for_nfs_portmapper("127.0.0.1", 111, timeout)
1108
1171
 
1109
1172
 
1110
- def map_windows_network_drive(mount_point_abs, max_attempts: int) -> tuple[bool, str]:
1173
+ def configure_windows_nfs_drive_cache(drive_str: str):
1174
+ """
1175
+ Configure per-drive Windows Client for NFS registry settings in HKCU before mounting.
1176
+ Disables NfsRdr per-drive lookup/readdir/attribute caching so renamed or recreated
1177
+ directories do not serve stale NFS filehandles from the Windows kernel redirector cache.
1178
+ """
1179
+ letter = drive_str.strip().rstrip(":\\/").upper()
1180
+ if len(letter) != 1 or not letter.isalpha():
1181
+ return
1182
+ try:
1183
+ import winreg
1184
+ base_key_path = f"Software\\Microsoft\\ClientForNFS\\CurrentVersion\\Persistent\\{letter}"
1185
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, base_key_path, 0, winreg.KEY_SET_VALUE) as k:
1186
+ winreg.SetValueEx(k, "NFSLookup", 0, winreg.REG_DWORD, 0)
1187
+ winreg.SetValueEx(k, "NFSReaddir", 0, winreg.REG_DWORD, 0)
1188
+ cache_key_path = f"{base_key_path}\\Cache"
1189
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, cache_key_path, 0, winreg.KEY_SET_VALUE) as ck:
1190
+ winreg.SetValueEx(ck, "FileAttributeCache", 0, winreg.REG_DWORD, 0)
1191
+ winreg.SetValueEx(ck, "AttributeTimeDelta", 0, winreg.REG_DWORD, 1)
1192
+ winreg.SetValueEx(ck, "RemoteWriteCache", 0, winreg.REG_DWORD, 0)
1193
+ except Exception:
1194
+ pass
1195
+
1196
+
1197
+ def configure_windows_explorer_drive_label(drive_root: str, label: str = ""):
1198
+ r"""
1199
+ Set the Windows Explorer MountPoints2 label for \\127.0.0.1\! and broadcast shell notifications
1200
+ so Explorer displays the project/share name instead of a generic 'Network Drive (W:)'.
1201
+ """
1202
+ display_label = f"Accelerator ({label})" if label else "Accelerator"
1203
+ try:
1204
+ import winreg
1205
+ for subkey in ("##127.0.0.1#!", "##127.0.0.1#!#"):
1206
+ key_path = f"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MountPoints2\\{subkey}"
1207
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE) as k:
1208
+ winreg.SetValueEx(k, "_LabelFromReg", 0, winreg.REG_SZ, display_label)
1209
+ except Exception:
1210
+ pass
1211
+ try:
1212
+ import ctypes
1213
+ # SHCNE_DRIVEADD (0x00000100), SHCNE_RENAMEFOLDER (0x00020000), SHCNE_UPDATEITEM (0x00002000)
1214
+ # SHCNF_PATHW | SHCNF_FLUSH (0x1005)
1215
+ ctypes.windll.shell32.SHChangeNotify(0x00000100, 0x1005, drive_root, None)
1216
+ ctypes.windll.shell32.SHChangeNotify(0x00020000, 0x1005, drive_root, None)
1217
+ ctypes.windll.shell32.SHChangeNotify(0x00002000, 0x1005, drive_root, None)
1218
+ except Exception:
1219
+ pass
1220
+
1221
+
1222
+ def map_windows_network_drive(mount_point_abs, max_attempts: int, label: str = "") -> tuple[bool, str]:
1111
1223
  """
1112
1224
  Attempt to map the NFS share to the requested drive letter using mount.exe.
1113
1225
  Retries with cleanup if Windows NFS client returns a transient error.
@@ -1117,6 +1229,7 @@ def map_windows_network_drive(mount_point_abs, max_attempts: int) -> tuple[bool,
1117
1229
  target_str = str(mount_point_abs).rstrip("\\/")
1118
1230
  if re.match(r"^[a-zA-Z]$", target_str):
1119
1231
  target_str += ":"
1232
+ configure_windows_nfs_drive_cache(target_str)
1120
1233
 
1121
1234
  mount_cmd = [
1122
1235
  "C:\\Windows\\System32\\mount.exe",
@@ -1133,6 +1246,7 @@ def map_windows_network_drive(mount_point_abs, max_attempts: int) -> tuple[bool,
1133
1246
 
1134
1247
  last_err = ""
1135
1248
  drive_root = str(mount_point_abs).rstrip("\\/") + "\\"
1249
+ configure_windows_explorer_drive_label(drive_root, label)
1136
1250
  for attempt in range(1, max_attempts + 1):
1137
1251
  cleanup_stuck_windows_mount_processes()
1138
1252
 
@@ -1160,6 +1274,7 @@ def map_windows_network_drive(mount_point_abs, max_attempts: int) -> tuple[bool,
1160
1274
  entries = os.listdir(drive_root)
1161
1275
  if len(entries) > 0:
1162
1276
  drive_ready = True
1277
+ configure_windows_explorer_drive_label(drive_root, label)
1163
1278
  return True, (res.stdout or "").strip()
1164
1279
  except OSError:
1165
1280
  pass
@@ -1454,6 +1569,11 @@ def mount_start(
1454
1569
  print(f"[cyan]Validating project '{project_slug}'...[/cyan]")
1455
1570
  validate_project_slug(server_url, project_slug)
1456
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
+
1457
1577
  # Ensure binaries are downloaded and cached
1458
1578
  try:
1459
1579
  mount_downloader.ensure_binaries(version=binary_version, use_fuse=fuse)
@@ -1520,9 +1640,9 @@ def mount_start(
1520
1640
  env["ACC_CAS_ENDPOINT"] = f"{server_url.rstrip('/')}/api/xet-cas"
1521
1641
  env["ACC_TOKEN"] = token
1522
1642
  cache_base = Path("C:/ProgramData/accli/cache") if sys_name == "Windows" else Path.home() / ".accli" / "cache"
1523
- (cache_base / "xet").mkdir(parents=True, exist_ok=True)
1643
+ xet_cache.xet_cache_dir(server_url).mkdir(parents=True, exist_ok=True)
1524
1644
  (cache_base / "hf-mount").mkdir(parents=True, exist_ok=True)
1525
- env["HF_XET_CACHE"] = str(cache_base / "xet")
1645
+ env["HF_XET_CACHE"] = str(xet_cache.xet_cache_dir(server_url))
1526
1646
  env["HF_HOME"] = str(cache_base)
1527
1647
  env["XDG_CACHE_HOME"] = str(cache_base)
1528
1648
 
@@ -1640,7 +1760,7 @@ def mount_start(
1640
1760
  raise typer.Exit(1)
1641
1761
 
1642
1762
  # Map the network drive in the CURRENT user session (so it is visible in Explorer)
1643
- success, err_msg = map_windows_network_drive(mount_point_abs, 5)
1763
+ success, err_msg = map_windows_network_drive(mount_point_abs, 5, label=project_slug)
1644
1764
  if success:
1645
1765
  start_nfs_watcher(str(mount_point_abs), interval=30)
1646
1766
  print(f"[bold green][OK] NFS mount successfully mapped at [white]{mount_point_abs}[/white]![/bold green]")
@@ -1694,6 +1814,7 @@ def mount_start(
1694
1814
  print(f"[yellow]Please check the log file at {log_file_path} for more details.[/yellow]")
1695
1815
  raise typer.Exit(1)
1696
1816
 
1817
+ configure_windows_explorer_drive_label(str(mount_point_abs).rstrip("\\/") + "\\", label=project_slug)
1697
1818
  start_nfs_watcher(str(mount_point_abs), interval=30)
1698
1819
  print(f"[bold green][OK] NFS mount process spawned successfully (PID: {process.pid}).[/bold green]")
1699
1820
  print(f"[cyan]Use 'umount' or 'accli mount stop' to unmount the drive.[/cyan]")
@@ -1735,7 +1856,7 @@ def mount_start(
1735
1856
  raise typer.Exit(1)
1736
1857
 
1737
1858
  # Map the network drive in the CURRENT user session (so it is visible in Explorer)
1738
- success, err_msg = map_windows_network_drive(mount_point_abs, 5)
1859
+ success, err_msg = map_windows_network_drive(mount_point_abs, 5, label=project_slug)
1739
1860
  if success:
1740
1861
  start_nfs_watcher(str(mount_point_abs), interval=30)
1741
1862
  print(f"[bold green][OK] NFS mount successfully mapped at [white]{mount_point_abs}[/white]![/bold green]")
@@ -9,7 +9,7 @@ import typer
9
9
  from rich import print
10
10
  from rich.progress import Progress, TextColumn, BarColumn, TaskProgressColumn, TimeElapsedColumn
11
11
 
12
- DEFAULT_VERSION = "v0.6.5-acc-pr140-p6"
12
+ DEFAULT_VERSION = "v0.6.5-acc-pr140-p16"
13
13
  BINARY_DIR = Path.home() / ".accli" / "bin"
14
14
 
15
15
  # Regex to safely validate version strings to prevent URL manipulation or directory traversal
@@ -7,6 +7,8 @@ from pathlib import Path
7
7
  from datetime import datetime
8
8
 
9
9
  # Windows Shell Notification constants
10
+ SHCNE_MKDIR = 0x00000008
11
+ SHCNE_RMDIR = 0x00000010
10
12
  SHCNE_UPDATEDIR = 0x00001000
11
13
  SHCNF_PATHW = 0x0005
12
14
 
@@ -62,10 +64,18 @@ def get_open_explorer_paths(script_path: Path, mount_point: str) -> list[str]:
62
64
  return []
63
65
 
64
66
 
65
- def notify_explorer(script_path: Path, mount_point: str, path_str: str):
67
+ def notify_explorer(script_path: Path, mount_point: str, path_str: str, removed_dirs: list[str] | None = None, added_dirs: list[str] | None = None):
66
68
  """Notifies Windows Shell and refreshes Explorer windows for path_str."""
67
69
  log(f"Broadcasting SHChangeNotify on '{path_str}'...")
68
70
  try:
71
+ if removed_dirs:
72
+ for dname in removed_dirs:
73
+ child_dir = str(Path(path_str) / dname)
74
+ ctypes.windll.shell32.SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, child_dir, None)
75
+ if added_dirs:
76
+ for dname in added_dirs:
77
+ child_dir = str(Path(path_str) / dname)
78
+ ctypes.windll.shell32.SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, child_dir, None)
69
79
  ctypes.windll.shell32.SHChangeNotify(
70
80
  SHCNE_UPDATEDIR,
71
81
  SHCNF_PATHW,
@@ -191,14 +201,23 @@ def run_watcher(mount_point: str, interval: float):
191
201
  dpath = Path(dir_str)
192
202
  current_state = scan_directory_state(dpath)
193
203
  if current_state is None:
204
+ if dir_str in cached_states:
205
+ del cached_states[dir_str]
206
+ parent_str = str(dpath.parent)
207
+ log(f"Directory '{dir_str}' disappeared -> notifying shell and refreshing '{parent_str}'")
208
+ notify_explorer(script_path, mount_point, parent_str, removed_dirs=[dpath.name])
194
209
  continue
195
210
 
196
211
  last_state = cached_states.get(dir_str)
197
212
  if last_state is not None:
198
213
  if current_state != last_state:
214
+ old_keys = set(last_state.keys())
215
+ new_keys = set(current_state.keys())
216
+ removed_dirs = [k for k in (old_keys - new_keys) if last_state[k][0]]
217
+ added_dirs = [k for k in (new_keys - old_keys) if current_state[k][0]]
199
218
  diff_summary = describe_changes(last_state, current_state)
200
219
  log(f"Change detected in '{dir_str}' -> {diff_summary}")
201
- notify_explorer(script_path, mount_point, dir_str)
220
+ notify_explorer(script_path, mount_point, dir_str, removed_dirs=removed_dirs, added_dirs=added_dirs)
202
221
  cached_states[dir_str] = current_state
203
222
  else:
204
223
  cached_states[dir_str] = current_state
@@ -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.5
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