File size: 15,125 Bytes
2e658e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1f20e5
2e658e7
 
a1f20e5
 
 
 
2e658e7
 
 
 
 
 
 
 
a1f20e5
 
 
 
 
 
 
 
 
 
 
2e658e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1f20e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e658e7
 
 
 
 
 
 
 
 
a1f20e5
 
 
 
2e658e7
 
 
 
 
 
 
 
a1f20e5
 
 
 
 
2e658e7
 
 
 
 
 
 
 
 
 
 
 
 
 
a1f20e5
 
 
 
 
 
 
 
 
2e658e7
 
 
 
 
 
 
 
 
 
 
 
 
 
a1f20e5
 
 
 
 
 
 
 
 
2e658e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1f20e5
 
 
 
 
 
 
 
 
2e658e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1f20e5
 
 
 
 
 
 
 
 
2e658e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env python3
"""Atomic Hugging Face Dataset persistence for HermesFace state.

The public helpers retain the legacy single-file API, while the production
sync path commits one validated secure-backup archive plus metadata in a single
Dataset commit.
"""
from __future__ import annotations

import hashlib
import json
import logging
import os
import shutil
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from typing import Any, Callable, Dict, List, Optional, TypeVar

from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
from huggingface_hub.utils import HfHubHTTPError, RepositoryNotFoundError

T = TypeVar("T")
_RETRYABLE_STATUS = {408, 425, 429, 500, 502, 503, 504}

logging.basicConfig(
    level=logging.INFO,
    format='{"timestamp": "%(asctime)s", "level": "%(levelname)s", "module": "atomic-save", "message": "%(message)s"}',
)
logger = logging.getLogger(__name__)


def _is_retryable_hf_error(exc: Exception) -> bool:
    """True for transient Hugging Face Hub / network failures."""
    if isinstance(exc, HfHubHTTPError):
        response = getattr(exc, "response", None)
        status = getattr(response, "status_code", None)
        if status in _RETRYABLE_STATUS:
            return True
    message = str(exc).lower()
    return any(token in message for token in ("502", "503", "504", "bad gateway", "gateway timeout"))


def _safe_dataset_path(value: str) -> str:
    pure = PurePosixPath(str(value).replace("\\", "/"))
    if pure.is_absolute() or not pure.parts or any(part in {"", ".", ".."} for part in pure.parts):
        raise ValueError(f"unsafe dataset path: {value!r}")
    return pure.as_posix()


def validate_backup_source_paths(source_paths: List[str], state_dir: Optional[str] = None) -> List[Path]:
    """Resolve and validate explicitly allowlisted backup source files."""
    try:
        from backup_allowlist import BackupAllowlistError, is_path_allowed, scan_file_for_secrets
    except ImportError:
        from scripts.backup_allowlist import (  # type: ignore
            BackupAllowlistError,
            is_path_allowed,
            scan_file_for_secrets,
        )

    root = Path(state_dir or os.environ.get("HERMES_HOME", "/opt/data")).resolve()
    validated: List[Path] = []
    for raw in source_paths:
        unresolved = Path(raw)
        if unresolved.is_symlink():
            raise BackupAllowlistError(f"Refusing symlink backup source: {unresolved.name}")
        path = unresolved.resolve()
        try:
            relative = path.relative_to(root)
        except ValueError as exc:
            raise BackupAllowlistError(f"Refusing backup outside HERMES_HOME: {path.name}") from exc
        if not path.is_file():
            raise BackupAllowlistError(f"Refusing non-file backup source: {relative.as_posix()}")
        if not is_path_allowed(relative.as_posix()):
            raise BackupAllowlistError(f"Refusing non-allowlisted backup source: {relative.as_posix()}")
        reason = scan_file_for_secrets(path)
        if reason:
            raise BackupAllowlistError(
                f"Refusing backup: secret-like content in {relative.as_posix()} ({reason})"
            )
        validated.append(path)
    return validated


class AtomicDatasetSaver:
    def __init__(
        self,
        repo_id: str,
        dataset_path: str = "state",
        *,
        api: Optional[HfApi] = None,
        token: Optional[str] = None,
    ):
        self.repo_id = repo_id
        self.dataset_path = _safe_dataset_path(dataset_path)
        self.token = token
        self.api = api or HfApi(token=token)
        self.max_retries = 3
        self.base_delay = 1.0
        self.max_backups = 3
        logger.info(f"init repo_id={repo_id} dataset_path={self.dataset_path}")

    def _call_with_retry(self, label: str, fn: Callable[[], T]) -> T:
        """Retry transient Hub API failures with bounded exponential backoff."""
        attempt = 0
        while True:
            try:
                return fn()
            except Exception as exc:
                attempt += 1
                if attempt > self.max_retries or not _is_retryable_hf_error(exc):
                    raise
                delay = min(30.0, self.base_delay * (2 ** (attempt - 1)))
                logger.warning(
                    f"{label}_retry attempt={attempt}/{self.max_retries} "
                    f"delay_s={delay:.1f} error={type(exc).__name__}"
                )
                time.sleep(delay)

    def calculate_checksum(self, file_path: Path) -> str:
        digest = hashlib.sha256()
        with file_path.open("rb") as handle:
            for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()

    def _repo_info(self):
        try:
            return self._call_with_retry(
                "repo_info",
                lambda: self.api.repo_info(repo_id=self.repo_id, repo_type="dataset"),
            )
        except RepositoryNotFoundError:
            return None

    def create_backup(self, current_commit: Optional[str]) -> Optional[str]:
        """Copy the current authoritative state files to a timestamped remote backup."""
        if not current_commit:
            return None
        try:
            files = self._call_with_retry(
                "list_repo_files",
                lambda: self.api.list_repo_files(
                    repo_id=self.repo_id, repo_type="dataset", revision=current_commit
                ),
            )
            prefix = f"{self.dataset_path}/"
            state_files = [path for path in files if path.startswith(prefix)]
            if not state_files:
                return None

            timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
            backup_path = f"backups/state_{timestamp}"
            logger.info(f"creating_backup path={backup_path} files={len(state_files)}")

            with tempfile.TemporaryDirectory(prefix="hermes-hf-backup-") as tmpdir:
                root = Path(tmpdir)
                operations = []
                for remote_path in state_files:
                    local = self._call_with_retry(
                        "hf_hub_download",
                        lambda remote_path=remote_path: hf_hub_download(
                            repo_id=self.repo_id,
                            repo_type="dataset",
                            filename=remote_path,
                            revision=current_commit,
                            token=self.token,
                        ),
                    )
                    relative = PurePosixPath(remote_path).relative_to(PurePosixPath(self.dataset_path))
                    destination = root.joinpath(*relative.parts)
                    destination.parent.mkdir(parents=True, exist_ok=True)
                    shutil.copy2(local, destination)
                    operations.append(
                        CommitOperationAdd(
                            path_in_repo=f"{backup_path}/{relative.as_posix()}",
                            path_or_fileobj=str(destination),
                        )
                    )

                if not operations:
                    return None
                info = self._call_with_retry(
                    "create_backup_commit",
                    lambda: self.api.create_commit(
                        repo_id=self.repo_id,
                        repo_type="dataset",
                        operations=operations,
                        commit_message=f"Backup state before update - {timestamp}",
                        parent_commit=current_commit,
                    ),
                )
                logger.info(f"backup_created commit={info.oid}")
                return info.oid
        except Exception as exc:
            # A failed remote backup must prevent replacing the current remote state.
            logger.error(f"backup_failed error={exc}")
            raise

    def save_secure_archive_atomic(
        self,
        archive_path: Path,
        state_data: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Validate and atomically commit one secure backup archive and metadata."""
        try:
            from secure_backup import extract_validated
        except ImportError:
            from scripts.secure_backup import extract_validated  # type: ignore

        archive = Path(archive_path)
        if archive.is_symlink() or not archive.is_file():
            raise ValueError("secure backup archive must be a regular file")

        # Validate member paths, member types, manifest, hashes, and SQLite before
        # any Hugging Face API call is permitted.
        with tempfile.TemporaryDirectory(prefix="hermes-archive-validate-") as tmpdir:
            manifest = extract_validated(archive, Path(tmpdir) / "validated")

        archive_sha256 = self.calculate_checksum(archive)
        operation_id = f"save_{int(time.time())}"
        repo_info = self._repo_info()
        current_commit = getattr(repo_info, "sha", None) if repo_info else None
        backup_commit = self.create_backup(current_commit)
        parent_commit = backup_commit or current_commit

        metadata = {
            "format": "hermes-secure-backup",
            "format_version": 1,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "operation_id": operation_id,
            "archive": "secure_state.tar.gz",
            "archive_sha256": archive_sha256,
            "manifest_sha256": hashlib.sha256(
                json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8")
            ).hexdigest(),
            "manifest": manifest,
            "backup_commit": backup_commit,
            "state_data": state_data or {},
        }

        with tempfile.TemporaryDirectory(prefix="hermes-hf-save-") as tmpdir:
            metadata_path = Path(tmpdir) / "metadata.json"
            metadata_path.write_text(
                json.dumps(metadata, sort_keys=True, separators=(",", ":")),
                encoding="utf-8",
            )
            operations = [
                CommitOperationAdd(
                    path_in_repo=f"{self.dataset_path}/secure_state.tar.gz",
                    path_or_fileobj=str(archive),
                ),
                CommitOperationAdd(
                    path_in_repo=f"{self.dataset_path}/metadata.json",
                    path_or_fileobj=str(metadata_path),
                ),
            ]
            info = self._call_with_retry(
                "create_commit",
                lambda: self.api.create_commit(
                    repo_id=self.repo_id,
                    repo_type="dataset",
                    operations=operations,
                    commit_message=f"Atomic secure state update - {operation_id}",
                    parent_commit=parent_commit,
                ),
            )

        result = {
            "success": True,
            "operation_id": operation_id,
            "commit_id": info.oid,
            "backup_commit": backup_commit,
            "timestamp": metadata["timestamp"],
            "archive_sha256": archive_sha256,
            "files_count": len(manifest.get("files", [])),
        }
        logger.info(f"atomic_secure_save_completed {result}")
        return result

    def save_state_atomic(
        self, state_data: Dict[str, Any], source_paths: List[str]
    ) -> Dict[str, Any]:
        """Legacy allowlisted individual-file commit retained for compatibility."""
        operation_id = f"save_{int(time.time())}"
        logger.info(f"starting_atomic_save op={operation_id} sources={source_paths}")
        validated_sources = validate_backup_source_paths(source_paths)

        repo_info = self._repo_info()
        current_commit = getattr(repo_info, "sha", None) if repo_info else None
        backup_commit = self.create_backup(current_commit)
        parent_commit = backup_commit or current_commit

        with tempfile.TemporaryDirectory(prefix="hermes-state-save-") as tmpdir:
            state_dir = Path(tmpdir) / "state"
            state_dir.mkdir(parents=True, exist_ok=True)
            metadata = {
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "operation_id": operation_id,
                "checksum": hashlib.sha256(
                    json.dumps(state_data, sort_keys=True).encode("utf-8")
                ).hexdigest(),
                "backup_commit": backup_commit,
                "state_data": state_data,
            }
            metadata_path = state_dir / "metadata.json"
            metadata_path.write_text(json.dumps(metadata, indent=2), encoding="utf-8")
            operations = [
                CommitOperationAdd(
                    path_in_repo=f"{self.dataset_path}/metadata.json",
                    path_or_fileobj=str(metadata_path),
                )
            ]
            for source in validated_sources:
                destination = state_dir / source.name
                shutil.copy2(source, destination)
                operations.append(
                    CommitOperationAdd(
                        path_in_repo=f"{self.dataset_path}/{source.name}",
                        path_or_fileobj=str(destination),
                    )
                )
            info = self._call_with_retry(
                "create_commit",
                lambda: self.api.create_commit(
                    repo_id=self.repo_id,
                    repo_type="dataset",
                    operations=operations,
                    commit_message=f"Atomic state update - {operation_id}",
                    parent_commit=parent_commit,
                ),
            )

        return {
            "success": True,
            "operation_id": operation_id,
            "commit_id": info.oid,
            "backup_commit": backup_commit,
            "timestamp": metadata["timestamp"],
            "files_count": len(validated_sources),
        }


def main() -> None:
    if len(sys.argv) < 3:
        print(json.dumps({
            "error": "Usage: python save_to_dataset_atomic.py <repo_id> <source_path1> [source_path2...]",
            "status": "error",
        }, indent=2))
        sys.exit(1)

    repo_id = sys.argv[1]
    source_paths = sys.argv[2:]
    for path in source_paths:
        if not os.path.exists(path):
            print(json.dumps({"error": f"Source path does not exist: {path}", "status": "error"}, indent=2))
            sys.exit(1)

    state_data = {
        "environment": "production",
        "version": "1.0.0",
        "platform": "huggingface-spaces",
        "app": "hermesface",
        "timestamp": datetime.now(timezone.utc).isoformat(),
    }
    try:
        result = AtomicDatasetSaver(repo_id).save_state_atomic(state_data, source_paths)
        print(json.dumps(result, indent=2))
    except Exception as exc:
        print(json.dumps({"error": str(exc), "status": "error"}, indent=2))
        sys.exit(1)


if __name__ == "__main__":
    main()