From 4e913e89db48f03b3148e7a3d6df2748eb1e3a4c Mon Sep 17 00:00:00 2001 From: Sarvesh Tamse Date: Sat, 3 Oct 2026 18:40:13 +0530 Subject: [PATCH 1/2] Build verified workspace checkpoints with explicit command recovery --- .gitattributes | 1 + .github/workflows/tests.yml | 25 + .gitignore | 32 +- LICENSE | 21 + README.md | 189 ++++--- benchmark.py | 481 ++++++++-------- demo.py | 370 ++++--------- docs/DESIGN.md | 106 ++++ docs/VALIDATION.md | 58 ++ docs/results/linux-wsl-tmpfs.json | 183 +++++++ docs/results/windows-ntfs.json | 183 +++++++ init_workspace.py | 64 +-- pyproject.toml | 22 + requirements.txt | 2 +- snapshot_daemon.py | 882 ++++++++++++++++++++---------- tests/test_adversarial.py | 342 ++++++++++++ tests/test_benchmark_demo.py | 68 +++ tests/test_cli.py | 100 ++++ tests/test_snapshotter.py | 141 +++++ watcher.py | 197 +------ workspace_cli.py | 124 +++++ 21 files changed, 2477 insertions(+), 1114 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/workflows/tests.yml create mode 100644 LICENSE create mode 100644 docs/DESIGN.md create mode 100644 docs/VALIDATION.md create mode 100644 docs/results/linux-wsl-tmpfs.json create mode 100644 docs/results/windows-ntfs.json create mode 100644 pyproject.toml create mode 100644 tests/test_adversarial.py create mode 100644 tests/test_benchmark_demo.py create mode 100644 tests/test_cli.py create mode 100644 tests/test_snapshotter.py create mode 100644 workspace_cli.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..e5b1c0f --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,25 @@ +name: correctness +on: [push, pull_request] +permissions: + contents: read +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + python: ['3.10', '3.13'] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - run: python -m pip install . + - run: python -m unittest discover -s tests -v + - run: python demo.py + - run: python benchmark.py --files 20 --size-kib 4 --iterations 3 --json benchmark-results-ci.json + - uses: actions/upload-artifact@v4 + with: + name: benchmark-${{ matrix.os }}-${{ matrix.python }} + path: benchmark-results-ci.json diff --git a/.gitignore b/.gitignore index 8b32920..2c34660 100644 --- a/.gitignore +++ b/.gitignore @@ -1,26 +1,16 @@ -``` -# Python __pycache__/ -*.pyc -*.pyo -*.pyd - -# Dependencies -venv/ +*.py[cod] .venv/ +venv/ .env -.env.local -*.env.* - -# Logs and temp files -*.log -*.tmp - -# Editors +.env.* +*.egg-info/ +build/ +dist/ +.pytest_cache/ +.coverage +workspace/ +*.snapshots/ +benchmark-results*.json .vscode/ .idea/ -```node_modules/ -.next/ -dist/ -build/ -node_modules/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9016fe9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Sarvesh Tamse + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 1dc0921..c4d9ba2 100644 --- a/README.md +++ b/README.md @@ -1,90 +1,157 @@ -# Git-for-Agent-Workspaces +# Git for Agent Workspaces -## Sub-Second Filesystem Rollback for AI Agent Workspaces +Verified filesystem checkpoints around agent commands. Maintained by **Sarvesh Tamse**. -**The Dedalus Gap:** Dedalus snapshots the entire VM (RAM + Disk). But if an agent just writes bad code or deletes a config file, rolling back 8GB of RAM takes too long and loses other good work. Enterprises need an "Undo" button just for the agent's workspace. +An agent edits a working project, deletes a configuration file, or leaves a failed +experiment behind. This tool records the workspace **before** the action and +restores that checkpoint if the command exits unsuccessfully. -### What This Project Builds +This is a Python systems prototype with a defined recovery contract and executable +failure tests. It uses content-addressed storage and staged directory replacement. +It does not use OverlayFS or promise a fixed rollback latency. -A lightweight daemon using **overlayfs** that snapshots only the `/workspace` directory before every major agent tool call. If the agent breaks the build, this daemon reverts the filesystem in **<50 milliseconds** without touching the VM's memory state. +## Try it -### The 10/10 Proof +Requires Python 3.10 or newer. No third-party runtime dependencies. -- **Full VM memory snapshot rollback:** ~800ms -- **Workspace-only rollback (this project):** ~40ms - -Includes a demo of an agent writing a buggy Python script, failing a test, and the system instantly reverting the file so the LLM can try again. +```bash +git clone https://github.com/sarvesh2003dev/Git-for-Agent-Workspaces.git +cd Git-for-Agent-Workspaces +python demo.py +python -m unittest discover -s tests -v +``` -## Architecture +The demo runs a real child process that damages a temporary fixture, observes +failure, restores the pre-action checkpoint, checks the recovered tree, and reruns +the original tests. It is a deterministic scripted agent action, not an LLM call. +It leaves your own files alone. -``` -┌─────────────────────────────────────────────────────────┐ -│ Agent Workspace │ -│ /workspace │ -│ │ │ -│ ▼ │ -│ ┌─────────────────────┐ │ -│ │ Snapshot Daemon │ │ -│ │ (watcher.py) │ │ -│ └─────────────────────┘ │ -│ │ │ -│ ┌───────────────┼───────────────┐ │ -│ ▼ ▼ ▼ │ -│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ -│ │Snapshot │ │Snapshot │ │Snapshot │ │ -│ │ t0 │ │ t1 │ │ t2 │ │ -│ │(clean) │ │(pre- │ │(pre- │ │ -│ │ │ │ edit) │ │ run) │ │ -│ └─────────┘ └─────────┘ └─────────┘ │ -└─────────────────────────────────────────────────────────┘ -``` +## Use it -## Quick Start +Run these commands from **outside** the workspace directory. The workspace must +be owned by this workflow, with no other processes writing to it. ```bash -# Install dependencies -pip install -r requirements.txt - -# Initialize the snapshot system -python init_workspace.py +python workspace_cli.py --workspace ./workspace init +python workspace_cli.py --workspace ./workspace snapshot --label before-edit +python workspace_cli.py --workspace ./workspace list +python workspace_cli.py --workspace ./workspace run -- python action.py +python workspace_cli.py --workspace ./workspace verify SNAPSHOT_ID +python workspace_cli.py --workspace ./workspace restore SNAPSHOT_ID +python workspace_cli.py --workspace ./workspace stats +python workspace_cli.py --workspace ./workspace prune --keep 10 +``` -# Start the snapshot daemon -python watcher.py & +Put your project and `action.py` inside the workspace before running the action. +The child command runs with that directory as its current directory. A successful +command keeps its changes. A failed command is restored and its original nonzero +exit code is returned. Recovery errors return exit code 2 and print a diagnostic. +An interrupted invocation retains its checkpoint for manual recovery after all +writers have stopped. -# Run the benchmark -python benchmark.py +To install the optional command-line entry point: -# Run the demo -python demo.py +```bash +python -m pip install . +workspace-checkpoint --workspace ./workspace list ``` -## Components +The store defaults to a sibling directory, `workspace.snapshots`. Override it +with `--snapshot-dir`; the store and workspace must not contain one another. +All workspace files are included, even ignored files and secrets. Protect the +store with the same access controls as the workspace. -- `snapshot_daemon.py` - Core overlayfs-based snapshot engine -- `watcher.py` - File watcher that triggers snapshots before agent actions -- `benchmark.py` - Performance comparison (VM snapshot vs workspace snapshot) -- `demo.py` - Interactive demo of agent failure and instant rollback -- `init_workspace.py` - Initialize the workspace snapshot infrastructure - -## API Usage +## Python API ```python from snapshot_daemon import WorkspaceSnapshotter +from workspace_cli import run_checkpointed + +snap = WorkspaceSnapshotter("./workspace") # must already exist +result = run_checkpointed(snap, ["python", "action.py"]) +print(result["snapshot_id"], result["returncode"], result["restored"]) + +# Explicit checkpoints for another tool integration: +with snap.transaction(): + checkpoint = snap.create_snapshot("before-tool") + # Run your foreground tool here; wait for all writes to finish. + # On failure: + snap.rollback(checkpoint) +``` -# Initialize -snap = WorkspaceSnapshotter("/workspace") +Use the transaction across checkpoint/action/restore when multiple cooperating +clients share a store. The lock does not stop an unrelated editor or agent. -# Create a snapshot before agent action -snapshot_id = snap.create_snapshot("before_code_edit") +## What is implemented -# Agent does something bad... +- Full SHA-256 content addressing; identical bytes share one stored object. +- Fresh content hashing on every checkpoint, without an mtime-only cache. +- Manifests record files, directory structure (including empty directories), and + basic mode bits and modification times. Snapshot IDs are collision-resistant. +- A cross-process store lock and on-disk manifests avoid stale client inventories. +- Missing or corrupt content fails verification before restoration changes the + workspace. +- A staged tree and recovery journal protect the previous tree during replacement. +- Symlinks, Windows reparse points, and special files are rejected rather than + followed. Workspace/store overlap is rejected. +- Retention removes expired checkpoints and reclaims unreferenced content. -# Rollback instantly (<50ms) -snap.rollback(snapshot_id) +See [the design and failure contract](docs/DESIGN.md) for the limits behind these +statements. See the [tests](tests) for executable evidence. -# Workspace is restored! +## Measure it + +```bash +python benchmark.py --files 200 --size-kib 16 --iterations 10 --seed 42 --json benchmark-results.json ``` +The benchmark compares measured checkpoint and restore work against an actual +directory-copy baseline on the same seeded fixture. It checks recovered state +for each sample and records raw samples and latency distributions. + +There is no simulated VM baseline and no claimed Dedalus speedup. Timing depends +on file count, bytes, storage, OS, cache state, and integrity checks. Snapshotting +reads the full tree; restoration materializes the full checkpoint. Deduplication +reduces stored bytes for repeated content, not the amount of data a restore must +write. + +Measured local results, raw samples, and test environments are in +[VALIDATION.md](docs/VALIDATION.md). The content store was slower than the +copy baseline in that experiment and used less retained storage. + +## Scope and limits + +This is for an **owned, idle filesystem tree** between foreground actions. + +- It is not a sandbox or a security boundary against malicious concurrent writers. +- It does not snapshot RAM, running processes, databases, network calls, or external + service state. Restoring files cannot undo those side effects. +- Processes with open files, memory mappings, or working directories inside the + workspace must stop before restoration. The workspace directory is replaced. +- The rename sequence has a brief visibility gap. It is recoverable, not a single + atomic switch for concurrent readers. +- POSIX basic permissions are tracked; Windows permissions are more limited. + Ownership, ACLs, extended attributes, access/creation times, hard-link identity, and sparse + file layout are outside the supported metadata contract. +- Local filesystems only. Network filesystems and sudden power-loss recovery have + not been validated. Keep independent backups of important data. +- Version 1 stores are not silently upgraded. Use a fresh version 2 store after + separately preserving any old snapshots. + +The original automatic watcher was removed: filesystem notifications arrive +after changes and cannot establish an exact pre-action boundary. `watcher.py` +now delegates to the explicit CLI; `--daemon` is no longer supported. + +## Why this problem + +Workspace-level recovery is relevant to persistent computers used by coding +agents. The useful question is whether a tool can provide a trustworthy pre-action +checkpoint with acceptable overhead on a specified workload. + +This repository investigates that question. It is not affiliated with Dedalus, +has not been benchmarked on Dedalus Machines, and does not claim to fix a verified +deficiency in their platform. + ## License -MIT +[MIT](LICENSE) — Sarvesh Tamse. diff --git a/benchmark.py b/benchmark.py index 13b6e66..8411b16 100644 --- a/benchmark.py +++ b/benchmark.py @@ -1,257 +1,270 @@ #!/usr/bin/env python3 -""" -Benchmark - Compare VM snapshot rollback vs workspace-only rollback. +"""Measure real, verified workspace snapshots against a full-copy baseline. -This demonstrates the "10/10 Proof": -- Full VM memory snapshot rollback: ~800ms -- Workspace-only rollback (this project): ~40ms +This is a local filesystem microbenchmark. It does not measure virtual machines, +Dedalus, agent quality, or a universal latency guarantee. Every sample restores +the same seeded fixture and verifies paths, bytes, permissions, and timestamps. """ -import time +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import platform import random -import string -import statistics +import shutil +import stat +import sys +import tempfile +import time from pathlib import Path -from concurrent.futures import ThreadPoolExecutor +from typing import Any from snapshot_daemon import WorkspaceSnapshotter -def generate_random_content(size_kb: int) -> str: - """Generate random text content of specified size.""" - return ''.join(random.choices(string.ascii_letters + string.digits + ' \n', k=size_kb * 1024)) +def tree_inventory(root: Path) -> dict[str, dict[str, Any]]: + """Independently describe files and empty directories, excluding root metadata.""" + inventory = {} + for path in sorted(root.rglob("*")): + info = path.lstat() + entry = {"mode": stat.S_IMODE(info.st_mode), "mtime_ns": info.st_mtime_ns} + if stat.S_ISREG(info.st_mode): + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + entry.update(type="file", size=info.st_size, sha256=digest.hexdigest()) + elif stat.S_ISDIR(info.st_mode): + entry.update(type="directory") + else: + raise ValueError(f"Unsupported fixture entry: {path}") + inventory[path.relative_to(root).as_posix()] = entry + return inventory -def simulate_vm_snapshot_rollback() -> float: - """ - Simulate a full VM snapshot rollback. - - This simulates the overhead of restoring RAM state (typically 4-8GB). - The actual time depends on: - - Amount of RAM to restore - - I/O bandwidth - - Memory mapping overhead - - Based on typical VM snapshot tools (like Dedalus), this takes ~800ms. - """ - start_time = time.perf_counter() - - # Simulate loading 8GB of RAM state from disk - # Assuming 500MB/s read speed, 8GB would take ~16s - # But with memory mapping and optimizations, typically ~800ms for incremental - - # We simulate the actual overhead by: - # 1. Allocating memory (simulating RAM restore) - # 2. Touching pages (simulating page faults) - # 3. Memory barrier (simulating consistency check) - - simulated_ram_mb = 8192 # 8GB - chunk_size = 4096 # Page size - num_pages = (simulated_ram_mb * 1024 * 1024) // chunk_size - - # Simulate page restoration with realistic timing - # In reality, this involves disk I/O and memory mapping - pages_to_restore = num_pages // 100 # Only sample for simulation - - data = b'\x00' * chunk_size - for _ in range(pages_to_restore): - # Simulate page restore overhead - _ = bytearray(data) - - # Add base overhead for VM state restoration - # (CPU registers, device state, etc.) - time.sleep(0.05) # 50ms base overhead - - elapsed_ms = (time.perf_counter() - start_time) * 1000 - - # Scale to realistic value based on empirical measurements - # Our simulation is faster than real VM restore, so we scale up - realistic_time = max(elapsed_ms, 750 + random.uniform(0, 100)) - - return realistic_time +def assert_restored(root: Path, expected: dict[str, dict[str, Any]]) -> None: + """Fail the run rather than report a fast but incorrect restoration.""" + actual = tree_inventory(root) + if actual != expected: + missing = sorted(expected.keys() - actual.keys()) + extra = sorted(actual.keys() - expected.keys()) + changed = sorted(key for key in expected.keys() & actual.keys() + if expected[key] != actual[key]) + raise AssertionError( + f"Restore verification failed: missing={missing[:5]}, " + f"extra={extra[:5]}, changed={changed[:5]}" + ) -def measure_workspace_rollback(snapshotter: WorkspaceSnapshotter, - snapshot_id: str, - iterations: int = 10) -> list: - """ - Measure workspace rollback time over multiple iterations. - - Returns list of times in milliseconds. - """ - times = [] - - for i in range(iterations): - # Create fresh snapshot for each iteration - test_snapshot = snapshotter.create_snapshot(f"benchmark_{i}") - - # Make some changes - test_file = snapshotter.workspace / f"benchmark_test_{i}.txt" - test_file.write_text(f"Benchmark test content {i}\n" * 100) - - # Measure rollback - start_time = time.perf_counter() - snapshotter.rollback(test_snapshot) - elapsed_ms = (time.perf_counter() - start_time) * 1000 - - times.append(elapsed_ms) - - # Cleanup test file if still exists - if test_file.exists(): - test_file.unlink() - - # Cleanup benchmark snapshot - snapshotter.delete_snapshot(test_snapshot) - - return times +def _create_fixture(root: Path, files: int, size_kib: int, seed: int) -> None: + rng = random.Random(seed) + root.mkdir() + for index in range(files): + path = root / f"group_{index % 8:02d}" / f"file_{index:06d}.bin" + path.parent.mkdir(exist_ok=True) + path.write_bytes(rng.randbytes(size_kib * 1024)) + (root / "empty_directory").mkdir() + (root / "nested_empty" / "child").mkdir(parents=True) + # Integer-second times are reproducible across common filesystem resolutions. + timestamp_ns = 1_700_000_000_000_000_000 + for path in sorted(root.rglob("*"), key=lambda item: len(item.parts), reverse=True): + path.chmod(0o755 if path.is_dir() else 0o644) + os.utime(path, ns=(timestamp_ns, timestamp_ns)) -def create_test_files(workspace: Path, num_files: int = 50, avg_size_kb: int = 10): - """Create test files to simulate a realistic workspace.""" - test_dir = workspace / "benchmark_data" - test_dir.mkdir(exist_ok=True) - - for i in range(num_files): - subdir = test_dir / f"subdir_{i % 5}" - subdir.mkdir(exist_ok=True) - - file_path = subdir / f"file_{i}.txt" - content = generate_random_content(avg_size_kb + random.randint(-5, 10)) - file_path.write_text(content) - - return test_dir +def _mutate_fixture(root: Path, seed: int) -> dict[str, int]: + rng = random.Random(seed + 1) + paths = sorted(root.glob("group_*/*.bin")) + edit_count = max(1, len(paths) // 4) + delete_count = len(paths) // 4 + for path in paths[:edit_count]: + path.write_bytes(rng.randbytes(path.stat().st_size)) + for path in paths[len(paths) - delete_count:] if delete_count else []: + path.unlink() + additions = max(1, len(paths) // 4) + new_dir = root / "new_directory" + new_dir.mkdir() + for index in range(additions): + (new_dir / f"added_{index}.bin").write_bytes(rng.randbytes(1024)) + (root / "empty_directory").rmdir() + (root / "empty_directory").write_text("directory replaced by file", encoding="utf-8") + return {"files_edited": edit_count, "files_deleted": delete_count, + "files_added": additions + 1, "directories_added": 1, + "directories_replaced_by_files": 1} -def run_benchmark(): - """Run the complete benchmark comparison.""" - print("=" * 70) - print("GIT-FOR-AGENT-WORKSPACES BENCHMARK") - print("Sub-Second Filesystem Rollback Performance Test") - print("=" * 70) - print() - - workspace = Path("/workspace") - snapshotter = WorkspaceSnapshotter(str(workspace)) - - # Create test files to simulate realistic workspace - print("Setting up test environment...") - test_dir = create_test_files(workspace, num_files=50, avg_size_kb=10) - - # Create baseline snapshot - print("Creating baseline snapshot...") - baseline_id = snapshotter.create_snapshot("benchmark_baseline") - - # Make some changes to simulate agent work - print("Simulating agent code changes...") - for i in range(10): - change_file = workspace / f"agent_code_{i}.py" - change_file.write_text(f""" -# Agent-generated code version {i} -def process_data_{i}(data): - return [x * {i} for x in data] +def _percentile(values: list[float], percentile: float) -> float: + ordered = sorted(values) + position = (len(ordered) - 1) * percentile + lower = int(position) + upper = min(lower + 1, len(ordered) - 1) + return ordered[lower] + (ordered[upper] - ordered[lower]) * (position - lower) -class AgentModel_{i}: - def __init__(self): - self.version = {i} - - def predict(self, x): - return x + {i} -""") - - # Create pre-rollback snapshot - print("Creating pre-rollback snapshot...") - pre_rollback_id = snapshotter.create_snapshot("before_agent_mistake") - - # Simulate agent making a mistake (more changes) - print("Simulating agent mistake (buggy code)...") - buggy_file = workspace / "buggy_code.py" - buggy_file.write_text(""" -# BUGGY CODE - This will break everything! -def divide_by_zero(x): - return x / 0 -import os -os.system("rm -rf important_config/") -""") - - print() - print("-" * 70) - print("BENCHMARK RESULTS") - print("-" * 70) - print() - - # Benchmark VM snapshot rollback (simulated) - print("1. VM SNAPSHOT ROLLBACK (Simulated)") - print(" Simulating 8GB RAM restore + disk state...") - vm_times = [simulate_vm_snapshot_rollback() for _ in range(10)] - vm_avg = statistics.mean(vm_times) - vm_stdev = statistics.stdev(vm_times) - print(f" Average: {vm_avg:.1f}ms") - print(f" Std Dev: {vm_stdev:.1f}ms") - print(f" Min: {min(vm_times):.1f}ms") - print(f" Max: {max(vm_times):.1f}ms") - print() - - # Benchmark workspace-only rollback - print("2. WORKSPACE-ONLY ROLLBACK (This Project)") - print(f" Rolling back {len(snapshotter.snapshots)} snapshots worth of changes...") - workspace_times = measure_workspace_rollback(snapshotter, pre_rollback_id, iterations=10) - ws_avg = statistics.mean(workspace_times) - ws_stdev = statistics.stdev(workspace_times) - print(f" Average: {ws_avg:.2f}ms") - print(f" Std Dev: {ws_stdev:.2f}ms") - print(f" Min: {min(workspace_times):.2f}ms") - print(f" Max: {max(workspace_times):.2f}ms") - print() - - # Calculate improvement - improvement = vm_avg / ws_avg - print("-" * 70) - print("COMPARISON") - print("-" * 70) - print(f" VM Snapshot Rollback: {vm_avg:.1f}ms") - print(f" Workspace Rollback: {ws_avg:.2f}ms") - print(f" Speedup Factor: {improvement:.1f}x faster") - print(f" Time Saved: {vm_avg - ws_avg:.1f}ms per rollback") - print() - - # Verify <50ms requirement - if ws_avg < 50: - print("✅ PASS: Workspace rollback completes in <50ms") - print(f" Measured: {ws_avg:.2f}ms (target: <50ms)") - else: - print("⚠️ WARNING: Workspace rollback exceeds 50ms target") - print(f" Measured: {ws_avg:.2f}ms (target: <50ms)") - print() - - # Cleanup - print("Cleaning up test files...") - snapshotter.rollback(baseline_id) - import shutil - if test_dir.exists(): - shutil.rmtree(test_dir) - for f in workspace.glob("agent_code_*.py"): - f.unlink() - if buggy_file.exists(): - buggy_file.unlink() - - print() - print("=" * 70) - print("BENCHMARK COMPLETE") - print("=" * 70) - - return { - "vm_avg_ms": vm_avg, - "workspace_avg_ms": ws_avg, - "speedup_factor": improvement, - "passes_requirement": ws_avg < 50 - } +def _summary(values: list[float]) -> dict[str, float]: + return {"p50": _percentile(values, 0.50), "p95": _percentile(values, 0.95), + "min": min(values), "max": max(values)} + + +def _logical_file_bytes(root: Path) -> int: + return sum(path.stat().st_size for path in root.rglob("*") if path.is_file()) + + +def _filesystem_type(path: Path) -> str: + """Best-effort context; unsupported platforms are reported honestly.""" + if os.name == "nt": + try: + import ctypes + volume = ctypes.create_unicode_buffer(261) + filesystem = ctypes.create_unicode_buffer(261) + kernel32 = ctypes.windll.kernel32 + if kernel32.GetVolumePathNameW(str(path), volume, len(volume)): + if kernel32.GetVolumeInformationW(volume.value, None, 0, None, None, + None, filesystem, len(filesystem)): + return filesystem.value + except (AttributeError, OSError): + pass + elif Path("/proc/mounts").exists(): + candidates = [] + with Path("/proc/mounts").open(encoding="utf-8") as handle: + for line in handle: + fields = line.split() + mount = fields[1].replace("\\040", " ") + try: + path.relative_to(mount) + candidates.append((len(mount), fields[2])) + except ValueError: + pass + if candidates: + return max(candidates)[1] + return "not detected" + + +def run_benchmark(*, files: int = 100, size_kib: int = 4, iterations: int = 5, + seed: int = 42, temp_parent: str | Path | None = None) -> dict[str, Any]: + if files < 1 or size_kib < 1 or iterations < 1: + raise ValueError("files, size_kib, and iterations must all be positive") + with tempfile.TemporaryDirectory(prefix="workspace-benchmark-", dir=temp_parent) as temporary: + root = Path(temporary).resolve() + workspaces = {name: root / name for name in ("content_store", "full_copy")} + for workspace in workspaces.values(): + _create_fixture(workspace, files, size_kib, seed) + expected = tree_inventory(workspaces["content_store"]) + assert_restored(workspaces["full_copy"], expected) + store_path = root / "snapshot_store" + snapshotter = WorkspaceSnapshotter(str(workspaces["content_store"]), str(store_path)) + copies_path = root / "full_copy_snapshots" + copies_path.mkdir() + samples: dict[str, list[dict[str, Any]]] = {name: [] for name in workspaces} + mutation_counts: dict[str, int] = {} + + for iteration in range(iterations): + # Alternate measured order; neither backend gets only the first position. + order = list(workspaces) if iteration % 2 == 0 else list(reversed(workspaces)) + for position, backend in enumerate(order): + workspace = workspaces[backend] + start = time.perf_counter_ns() + if backend == "content_store": + snapshot_id = snapshotter.create_snapshot(f"benchmark_{iteration}") + else: + copy_path = copies_path / f"snapshot_{iteration:04d}" + shutil.copytree(workspace, copy_path, copy_function=shutil.copy2) + snapshot_ms = (time.perf_counter_ns() - start) / 1_000_000 + if backend == "content_store": + snapshotter.verify_snapshot(snapshot_id) + else: + assert_restored(copy_path, expected) + mutation_counts = _mutate_fixture(workspace, seed) + + start = time.perf_counter_ns() + if backend == "content_store": + if snapshotter.rollback(snapshot_id) is not True: + raise AssertionError("Snapshot engine did not report successful rollback") + else: + shutil.rmtree(workspace) + shutil.copytree(copy_path, workspace, copy_function=shutil.copy2) + rollback_ms = (time.perf_counter_ns() - start) / 1_000_000 + assert_restored(workspace, expected) + samples[backend].append({"iteration": iteration + 1, + "measurement_order": position + 1, + "snapshot_ms": snapshot_ms, + "rollback_ms": rollback_ms, + "snapshot_plus_rollback_ms": snapshot_ms + rollback_ms, + "restoration_verified": True}) + + results = {} + for backend, raw_samples in samples.items(): + results[backend] = {"raw_samples": raw_samples, + "snapshot_ms": _summary([s["snapshot_ms"] for s in raw_samples]), + "rollback_ms": _summary([s["rollback_ms"] for s in raw_samples]), + "snapshot_plus_rollback_ms": _summary( + [s["snapshot_plus_rollback_ms"] for s in raw_samples])} + results["content_store"]["storage"] = { + **snapshotter.storage_stats(), "logical_file_bytes": _logical_file_bytes(store_path)} + results["full_copy"]["storage"] = { + "snapshot_count": iterations, "logical_file_bytes": _logical_file_bytes(copies_path)} + disk = shutil.disk_usage(root) + return { + "schema_version": 1, + "description": "Verified local filesystem microbenchmark; no VM or Dedalus measurements", + "context": {"python": sys.version, "os": platform.platform(), + "machine": platform.machine(), "processor": platform.processor() or "unknown", + "logical_cpu_count": os.cpu_count(), "filesystem": _filesystem_type(root), + "temporary_parent": str(root.parent), "device_id": root.stat().st_dev, + "volume_total_bytes": disk.total, "volume_free_bytes": disk.free}, + "workload": {"seed": seed, "file_count": files, "file_size_bytes": size_kib * 1024, + "total_file_bytes": files * size_kib * 1024, + "directory_count": sum(e["type"] == "directory" for e in expected.values()), + "iterations_per_backend": iterations, "mutations_per_sample": mutation_counts}, + "methodology": [ + "Both backends receive the same deterministic fixture and mutations; order alternates.", + "All retained snapshots contain the same baseline; the content store can deduplicate them.", + "The first content-store snapshot starts with an empty store; later samples reuse it.", + "OS caches are not flushed; these are local observed timings, not cold-cache guarantees.", + "Snapshot and rollback timers include each backend's normal integrity and durability work.", + "The full-copy baseline uses copytree/copy2, without extra integrity hashing or explicit fsync.", + "Independent correctness checks and mutation setup are outside timing intervals.", + "Verification compares every relative path, file bytes, mode, and mtime_ns, including empty directories.", + "Percentiles use linear interpolation; few samples do not establish tail-latency guarantees.", + "Storage reports logical file sizes, not allocated disk blocks; all samples are retained.", + "This measures regular files/directories, not symlinks, concurrent writers, VMs, or external effects." + ], + "results": results, + "all_restorations_verified": True, + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--files", type=int, default=100) + parser.add_argument("--size-kib", type=int, default=4) + parser.add_argument("--iterations", type=int, default=5) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--temp-parent", type=Path, help="Existing directory for disposable test data") + parser.add_argument("--json", type=Path, help="Save context, raw samples, and summaries") + args = parser.parse_args(argv) + if min(args.files, args.size_kib, args.iterations) < 1: + parser.error("--files, --size-kib, and --iterations must be positive") + result = run_benchmark(files=args.files, size_kib=args.size_kib, + iterations=args.iterations, seed=args.seed, temp_parent=args.temp_parent) + print("Verified filesystem benchmark (milliseconds; local observations)") + for name, values in result["results"].items(): + print(f"{name}:") + for metric in ("snapshot_ms", "rollback_ms", "snapshot_plus_rollback_ms"): + summary = values[metric] + print(f" {metric}: p50={summary['p50']:.3f}, p95={summary['p95']:.3f}, " + f"min={summary['min']:.3f}, max={summary['max']:.3f}") + print(f" retained snapshot bytes (logical): {values['storage']['logical_file_bytes']}") + print("Every restoration verified. Caches were not flushed; no universal latency claim.") + if args.json: + args.json.parent.mkdir(parents=True, exist_ok=True) + args.json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(f"Full report: {args.json.resolve()}") + return 0 if __name__ == "__main__": - results = run_benchmark() - - # Print JSON results for programmatic access - import json - print("\nJSON Results:") - print(json.dumps(results, indent=2)) + raise SystemExit(main()) diff --git a/demo.py b/demo.py index e5b9f72..5efa55b 100644 --- a/demo.py +++ b/demo.py @@ -1,268 +1,132 @@ #!/usr/bin/env python3 -""" -Demo - Interactive demonstration of agent failure and instant rollback. +"""Scripted recovery demo: checkpoint, run a bad command, validate, restore. -This demo shows: -1. An agent writing a Python script -2. The script failing tests -3. Instant filesystem rollback (<50ms) -4. The LLM trying again with a clean slate +No LLM is used. All subprocesses and file mutations run inside a disposable +fixture. A successful result requires exact recovery and passing fixture checks. """ +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +import tempfile import time from pathlib import Path -from snapshot_daemon import WorkspaceSnapshotter - - -def print_section(title: str): - """Print a section header.""" - print() - print("=" * 60) - print(f" {title}") - print("=" * 60) - - -def print_step(step_num: int, description: str): - """Print a step in the demo.""" - print(f"\n[Step {step_num}] {description}") - print("-" * 40) - - -def run_demo(): - """Run the interactive demo.""" - workspace = Path("/workspace") - snap = WorkspaceSnapshotter(str(workspace)) - - print_section("GIT-FOR-AGENT-WORKSPACES DEMO") - print("Agent Failure & Instant Rollback Demonstration") - print() - print("Scenario: An AI agent is writing code and makes a mistake.") - print("We'll show how sub-second rollback enables quick recovery.") - - # Step 1: Initial state - print_step(1, "Starting with clean workspace") - - # Clean up any previous demo files - for f in workspace.glob("agent_script.py"): - f.unlink() - for f in workspace.glob("agent_script_v*.py"): - f.unlink() - - # Create initial clean snapshot - print("Creating initial clean snapshot...") - clean_snapshot = snap.create_snapshot("clean_state") - print(f"Snapshot ID: {clean_snapshot}") - - # Step 2: Agent writes first version (has bug) - print_step(2, "Agent writes Python script (with bug)") - - buggy_code = ''' -# Agent-generated script v1 -# BUG: This has an off-by-one error! - -def calculate_sum(numbers): - """Calculate sum of numbers.""" - total = 0 - for i in range(len(numbers) - 1): # BUG: should be len(numbers) - total += numbers[i] - return total +from typing import Any -def main(): - test_data = [1, 2, 3, 4, 5] - expected = 15 - result = calculate_sum(test_data) - - print(f"Testing calculate_sum...") - print(f"Input: {test_data}") - print(f"Expected: {expected}") - print(f"Got: {result}") - - if result == expected: - print("✅ Test PASSED") - else: - print("❌ Test FAILED") - raise AssertionError(f"Expected {expected}, got {result}") - -if __name__ == "__main__": - main() -''' - - agent_script = workspace / "agent_script.py" - agent_script.write_text(buggy_code) - print(f"Created: {agent_script}") - print("Code preview:") - print(buggy_code[:300] + "...") - - # Create snapshot before running - print("\nCreating pre-execution snapshot...") - pre_run_snapshot = snap.create_snapshot("before_first_run") - print(f"Snapshot ID: {pre_run_snapshot}") - - # Step 3: Run and fail - print_step(3, "Running buggy code (will fail)") - - print("Executing agent_script.py...") - time.sleep(0.5) # Simulate execution delay - - # Actually run the code to show failure - import subprocess - result = subprocess.run( - ["python", str(agent_script)], - capture_output=True, - text=True, - cwd=str(workspace) - ) - - if result.returncode != 0: - print("❌ CODE FAILED AS EXPECTED") - print("Error output:") - print(result.stderr[:500] if result.stderr else result.stdout[:500]) - else: - print("Unexpected: Code passed (bug might be fixed)") - - # Step 4: Show rollback capability - print_step(4, "Demonstrating instant rollback") - - print("Before rollback:") - print(f" - agent_script.py exists: {agent_script.exists()}") - print(f" - File size: {agent_script.stat().st_size if agent_script.exists() else 0} bytes") - - # Measure rollback time - print("\nRolling back to pre-run state...") - start = time.perf_counter() - snap.rollback(pre_run_snapshot) - rollback_time = (time.perf_counter() - start) * 1000 - - print(f"⚡ Rollback completed in {rollback_time:.2f}ms!") - - if rollback_time < 50: - print("✅ PASS: Rollback under 50ms target") - else: - print(f"⚠️ Rollback took {rollback_time:.2f}ms (target: <50ms)") - - # Step 5: Agent tries again - print_step(5, "Agent retries with fixed code") - - fixed_code = ''' -# Agent-generated script v2 (FIXED) -# Fixed the off-by-one error! - -def calculate_sum(numbers): - """Calculate sum of numbers.""" - total = 0 - for num in numbers: # FIXED: iterate directly over numbers - total += num - return total - -def main(): - test_data = [1, 2, 3, 4, 5] - expected = 15 - result = calculate_sum(test_data) - - print(f"Testing calculate_sum...") - print(f"Input: {test_data}") - print(f"Expected: {expected}") - print(f"Got: {result}") - - if result == expected: - print("✅ Test PASSED") - return True - else: - print("❌ Test FAILED") - return False +from benchmark import assert_restored, tree_inventory +from snapshot_daemon import WorkspaceSnapshotter -if __name__ == "__main__": - success = main() - exit(0 if success else 1) -''' - - print("Writing fixed code...") - agent_script.write_text(fixed_code) - - # Create snapshot before second run - print("Creating pre-second-run snapshot...") - pre_run_2_snapshot = snap.create_snapshot("before_second_run") - - # Step 6: Run fixed code - print_step(6, "Running fixed code (should pass)") - - print("Executing fixed agent_script.py...") - time.sleep(0.5) - - result = subprocess.run( - ["python", str(agent_script)], - capture_output=True, - text=True, - cwd=str(workspace) - ) - - if result.returncode == 0: - print("✅ CODE PASSED!") - print("Output:") - print(result.stdout) - else: - print("❌ Code still failing") - print(result.stderr or result.stdout) - - # Step 7: Show all snapshots - print_step(7, "Reviewing snapshot history") - - snapshots = snap.list_snapshots() - print(f"Total snapshots created: {len(snapshots)}") - print() - print(f"{'ID':<45} {'Label':<25} {'Files':<8}") - print("-" * 78) - for s in snapshots: - print(f"{s['id']:<45} {s['label']:<25} {s['file_count']:<8}") - - # Step 8: Demo complete rollback - print_step(8, "Complete rollback to clean state") - - print("Rolling back to completely clean state...") - snap.rollback(clean_snapshot) - - print("After rollback:") - print(f" - agent_script.py exists: {agent_script.exists()}") - - # Cleanup demo files - if agent_script.exists(): - agent_script.unlink() - - print("\n✅ Demo complete! Workspace restored to clean state.") - - # Summary - print_section("DEMO SUMMARY") - print(""" -Key Takeaways: -1. INSTANT ROLLBACK: Filesystem rollback completes in <50ms - - Much faster than VM-level snapshots (~800ms) - - No memory state to restore, just file contents +CHECK_COMMAND = """\ +import json +from pathlib import Path +from app import add +assert add(2, 3) == 5, 'addition behavior changed' +assert json.loads(Path('config.json').read_text(encoding='utf-8')) == {'enabled': True} +assert Path('state.txt').is_file() +assert Path('state.txt').read_text(encoding='utf-8') == 'ready' +assert Path('assets').is_dir() +assert Path('assets/info.txt').read_text(encoding='utf-8') == 'original asset' +assert Path('empty_directory').is_dir() +assert not Path('unexpected.txt').exists() +print('fixture checks passed') +""" -2. AGENT ITERATION: Enables rapid trial-and-error - - Agent can try multiple approaches quickly - - Failed experiments leave no trace +MUTATION_COMMAND = """\ +import shutil +from pathlib import Path +Path('app.py').write_text('def add(a, b):\\n return a - b\\n', encoding='utf-8') +Path('config.json').unlink() +Path('unexpected.txt').write_text('unwanted new file', encoding='utf-8') +Path('state.txt').unlink() +Path('state.txt').mkdir() +Path('state.txt/nested.txt').write_text('file replaced by directory', encoding='utf-8') +shutil.rmtree('assets') +Path('assets').write_text('directory replaced by file', encoding='utf-8') +Path('empty_directory').rmdir() +print('scripted mutations completed') +""" -3. SELECTIVE RESTORE: Only workspace files are affected - - Other system state remains unchanged - - No disruption to unrelated processes -4. AUTOMATIC SNAPSHOTS: Can be triggered by file watcher - - Before every agent tool call - - Before code execution - - On detected file changes -""") - - return { - "demo_completed": True, - "rollback_under_50ms": rollback_time < 50, - "actual_rollback_time_ms": rollback_time - } +def _run_python(workspace: Path, source: str) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, "-B", "-c", source], cwd=workspace, + capture_output=True, text=True, encoding="utf-8", timeout=30) + + +def run_demo(*, temp_parent: str | Path | None = None) -> dict[str, Any]: + with tempfile.TemporaryDirectory(prefix="workspace-demo-", dir=temp_parent) as temporary: + root = Path(temporary) + workspace = root / "workspace" + workspace.mkdir() + (workspace / "app.py").write_text("def add(a, b):\n return a + b\n", encoding="utf-8") + (workspace / "config.json").write_text('{"enabled": true}\n', encoding="utf-8") + (workspace / "state.txt").write_text("ready", encoding="utf-8") + (workspace / "assets").mkdir() + (workspace / "assets/info.txt").write_text("original asset", encoding="utf-8") + (workspace / "empty_directory").mkdir() + before = _run_python(workspace, CHECK_COMMAND) + if before.returncode != 0: + raise AssertionError(f"Initial fixture is invalid: {before.stderr}") + expected = tree_inventory(workspace) + snapshotter = WorkspaceSnapshotter(str(workspace), str(root / "snapshots")) + start = time.perf_counter_ns() + checkpoint = snapshotter.create_snapshot("before_scripted_tool_action") + snapshot_ms = (time.perf_counter_ns() - start) / 1_000_000 + snapshotter.verify_snapshot(checkpoint) + + action = _run_python(workspace, MUTATION_COMMAND) + if action.returncode != 0: + raise AssertionError(f"Mutation command did not complete: {action.stderr}") + failed = _run_python(workspace, CHECK_COMMAND) + if failed.returncode == 0 or "addition behavior changed" not in failed.stderr: + raise AssertionError(f"Expected behavioral failure was not demonstrated: {failed.stderr}") + + start = time.perf_counter_ns() + if snapshotter.rollback(checkpoint) is not True: + raise AssertionError("Rollback did not report success") + rollback_ms = (time.perf_counter_ns() - start) / 1_000_000 + assert_restored(workspace, expected) + recovered = _run_python(workspace, CHECK_COMMAND) + if recovered.returncode != 0: + raise AssertionError(f"Recovered fixture failed its checks: {recovered.stderr}") + return { + "description": "Scripted filesystem recovery; no LLM or Dedalus integration", + "uses_llm": False, "checkpoint_before_action": True, + "initial_checks_exit_code": before.returncode, + "mutation_command_exit_code": action.returncode, + "checks_after_mutation_exit_code": failed.returncode, + "checks_after_mutation_stderr": failed.stderr.strip(), + "checks_after_rollback_exit_code": recovered.returncode, + "restoration_verified": True, + "verified_properties": ["relative paths", "file contents", "empty directories", + "file and directory modes", "mtime_ns", + "file-to-directory and directory-to-file recovery"], + "snapshot_ms": snapshot_ms, "rollback_ms": rollback_ms, + "timing_scope": "One local observation; includes engine work, excludes independent verification", + "scope": "Filesystem entries only; cannot undo memory, network, or external side effects", + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--temp-parent", type=Path, help="Existing directory for disposable fixture") + parser.add_argument("--json", type=Path, help="Save the verified demo result") + args = parser.parse_args(argv) + result = run_demo(temp_parent=args.temp_parent) + print("Scripted filesystem recovery demo; no LLM is used.") + print("Initial checks passed. The child command edited, deleted, added, and replaced fixture entries.") + print("Checks failed after the command. Rollback restored the pre-command checkpoint.") + print("Exact inventory verified; the original checks passed again.") + print(f"Observed snapshot: {result['snapshot_ms']:.3f} ms; rollback: {result['rollback_ms']:.3f} ms.") + if args.json: + args.json.parent.mkdir(parents=True, exist_ok=True) + args.json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(f"Full report: {args.json.resolve()}") + return 0 if __name__ == "__main__": - results = run_demo() - - print("\nDemo Results:") - import json - print(json.dumps(results, indent=2)) + raise SystemExit(main()) diff --git a/docs/DESIGN.md b/docs/DESIGN.md new file mode 100644 index 0000000..a9160a1 --- /dev/null +++ b/docs/DESIGN.md @@ -0,0 +1,106 @@ +# Design and failure contract + +## Boundary + +A checkpoint is a copy of an owned filesystem tree taken while all independent +writers are stopped. A foreground action may then modify that tree. After the +action finishes and all its writers stop, the checkpoint can be restored. + +The system intentionally does not infer action boundaries from filesystem events. +The CLI's `run` command makes the boundary explicit and preserves the child exit +code so a caller can distinguish a failed action from a successful one. + +A store lock serializes cooperating processes. It does not make a live, changing +directory into a consistent snapshot. A tool that spawns persistent background +writers violates this contract. Database, process, and external side effects need +their own coordination. + +## Representation + +Each regular file is read and addressed by its complete SHA-256 digest. A snapshot +manifest records paths, content references, directory entries, and basic mode +bits and modification times. Repeated file bytes reuse the same object. Every checkpoint reads fresh +content; modification time alone is not evidence that bytes are unchanged. + +Manifests are independently persisted. Clients discover current state under the +shared store lock rather than rewriting an old in-memory inventory. A complete +manifest is the publication point for a checkpoint. Interrupted creation can +leave unused objects, which retention/garbage collection may reclaim. + +## Restoration + +Restoration validates the manifest and stored content, constructs a sibling +staging tree, and records replacement intent. It moves the current workspace to +a sibling backup before publishing the staged tree. The journal allows a later +operation to recover an interrupted replacement. + +The staging tree is on the workspace's filesystem so directory renames do not +cross filesystem boundaries. Old and new trees coexist during restoration; +capacity planning must include staging, backup, and the content store. + +This is not a single atomic exchange. The workspace pathname can briefly be +absent between renames. Other processes must not access it during restoration. +Open handles and process working directories do not automatically move to the new +tree. The caller runs from outside the workspace. + +A reported restoration failure must be investigated before a tool retries work. +Recovery can restore the previous tree or finish cleanup depending on how far +replacement progressed. Power interruption, unsupported filesystem semantics, and +hardware failure are not covered by a claim of crash-proof storage. + +## Paths and permissions + +Snapshot and workspace roots cannot contain one another. Paths must stay within +their designated tree. Symbolic links, Windows reparse points, and special files +are unsupported. The store must be private to the application; the checks are +defense in depth, not a substitute for access control. + +Basic mode bits are tracked separately from content because identical bytes can +belong to files with different permissions. POSIX ownership, ACLs, extended +attributes, access/creation times, sparse extents, hard-link identity, and Windows security +descriptors are outside the contract. Unsupported link/special-file entries cause +an explicit error; they are not silently omitted. + +## Failure matrix + +| Event | Expected behavior | +| --- | --- | +| Foreground action exits successfully | Keep changes and retain checkpoint | +| Foreground action exits unsuccessfully | Restore pre-action tree; retain failing exit code | +| Action launch fails | Report error; retain checkpoint | +| User interrupts command | Retain checkpoint; stop writers before manual restoration | +| Stored object missing or corrupt | Fail verification before workspace replacement | +| Tracked file changed into directory | Reconstruct correct type in staging | +| Workspace contains symlink/reparse/special entry | Fail explicitly without following it | +| Two clients use the same store | Serialize; preserve published manifests | +| Checkpoint creation is interrupted | No partial manifest advertised as a checkpoint | +| Replacement is interrupted | Recover using journal and backup on next store operation | +| Retention removes last reference | Reclaim unused content under the lock | + +## Performance choices + +The implementation chooses verifiable restoration over a fixed latency target. +Snapshotting scans and hashes all files. Restoration writes the full tree and +verifies stored bytes. Hash-based deduplication helps repeated checkpoint storage, +but does not make this a copy-on-write filesystem. + +The baseline is a measured full directory copy, not a made-up VM latency. The +benchmark separately reports checkpoint and restoration costs, includes raw +samples, and checks results. It does not establish performance on another +machine, larger workloads, or a cloud provider. + +A future OverlayFS or filesystem-native backend should be justified by measured +workloads and a compatible failure contract. Simply changing languages or adding +a daemon would not address correctness. + +## Validation + +The automated suite covers normal recovery plus corruption, path containment, +file/directory replacement, concurrent clients, interrupted replacement, retention, +and command exit codes. CI exercises Linux and Windows. Capability-dependent tests +may skip when the host cannot create the relevant filesystem object; CI output +makes those skips visible. + +The benchmark is a workload experiment, not a replacement for correctness tests. +Real production usage and integration with a persistent VM service remain future +validation work. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md new file mode 100644 index 0000000..0b4fe7c --- /dev/null +++ b/docs/VALIDATION.md @@ -0,0 +1,58 @@ +# Observed validation — 2026-10-03 + +These are reproducible local observations, not a cloud-service comparison or an +under-50-ms guarantee. The Windows and Linux benchmark invocations ran sequentially +on one host. Neither run controlled other host activity or flushed OS caches. + +## Correctness + +- Windows 11 / CPython 3.13.2: 40 tests, 37 passed, 3 POSIX-only skips. +- Ubuntu on WSL2 / CPython 3.14.4: all 40 tests passed. +- Tests create their data in temporary directories (NTFS on Windows, tmpfs on WSL). +- Tests cover actual process death between directory renames, multi-process + checkpoint publication, corrupted/missing objects, symlink escapes, metadata, + read-only directories, retention, and command exit codes. +- The demo independently verifies the restored fixture and reruns its checks. +- A Python wheel builds successfully. The CI configuration also targets Python + 3.10 and 3.13 on GitHub-hosted Linux and Windows; the local runs above do not + establish those remote jobs' outcomes. + +## Measured workload + +100 regular files of 4 KiB each (400 KiB total), 11 directories, seed 42. +Each sample edits 25 files, deletes 25, creates 26 files, and replaces an empty +directory with a file. Five snapshots are retained per backend. Every restoration +is independently checked for paths, bytes, basic modes, and modification times. + +| Environment | Backend | Checkpoint p50 / p95 (ms) | Restore p50 / p95 (ms) | Retained logical file bytes | +| --- | --- | --- | --- | --- | +| Windows / NTFS | Content store | 228.506 / 243.150 | 243.228 / 250.435 | 527,973 | +| Windows / NTFS | Directory copy | 52.616 / 62.421 | 61.404 / 63.436 | 2,048,000 | +| WSL2 / tmpfs | Content store | 18.623 / 20.048 | 12.685 / 14.549 | 527,938 | +| WSL2 / tmpfs | Directory copy | 3.820 / 4.405 | 4.018 / 7.587 | 2,048,000 | + +**The content store is slower on this workload.** It performs integrity hashing, +fsync calls, manifest validation, and recovery-journal work that the simple copy +baseline does not. It uses about 74% fewer retained logical bytes here, including +its manifests. Repeated identical checkpoints favor deduplication; this is not a +general storage-saving estimate for arbitrary workloads. + +The WSL tmpfs results are memory-backed and are not evidence of persistent-disk +performance. Do not use the difference between rows as a Windows/Linux comparison. +Five samples are insufficient to characterize production tail latency. + +Raw samples and context: +[Windows](results/windows-ntfs.json) · [Linux](results/linux-wsl-tmpfs.json). +The Windows temporary-directory username is redacted; measurement values are not. + +## Reproduce + +```bash +python -m unittest discover -s tests -v +python demo.py +python benchmark.py --files 100 --size-kib 4 --iterations 5 --seed 42 --json benchmark-results.json +``` + +Use `--temp-parent PATH` to select a filesystem to measure. Record the reported +filesystem and cache conditions. A claim about Dedalus Machines still requires an +actual deployment and measurement there. diff --git a/docs/results/linux-wsl-tmpfs.json b/docs/results/linux-wsl-tmpfs.json new file mode 100644 index 0000000..c043d69 --- /dev/null +++ b/docs/results/linux-wsl-tmpfs.json @@ -0,0 +1,183 @@ +{ + "schema_version": 1, + "description": "Verified local filesystem microbenchmark; no VM or Dedalus measurements", + "context": { + "python": "3.14.4 (main, Apr 8 2026, 04:02:31) [GCC 15.2.0]", + "os": "Linux-6.18.33.2-microsoft-standard-WSL2-x86_64-with-glibc2.43", + "machine": "x86_64", + "processor": "unknown", + "logical_cpu_count": 12, + "filesystem": "tmpfs", + "temporary_parent": "/tmp", + "device_id": 72, + "volume_total_bytes": 4026867712, + "volume_free_bytes": 4023459840 + }, + "workload": { + "seed": 42, + "file_count": 100, + "file_size_bytes": 4096, + "total_file_bytes": 409600, + "directory_count": 11, + "iterations_per_backend": 5, + "mutations_per_sample": { + "files_edited": 25, + "files_deleted": 25, + "files_added": 26, + "directories_added": 1, + "directories_replaced_by_files": 1 + } + }, + "methodology": [ + "Both backends receive the same deterministic fixture and mutations; order alternates.", + "All retained snapshots contain the same baseline; the content store can deduplicate them.", + "The first content-store snapshot starts with an empty store; later samples reuse it.", + "OS caches are not flushed; these are local observed timings, not cold-cache guarantees.", + "Snapshot and rollback timers include each backend's normal integrity and durability work.", + "The full-copy baseline uses copytree/copy2, without extra integrity hashing or explicit fsync.", + "Independent correctness checks and mutation setup are outside timing intervals.", + "Verification compares every relative path, file bytes, mode, and mtime_ns, including empty directories.", + "Percentiles use linear interpolation; few samples do not establish tail-latency guarantees.", + "Storage reports logical file sizes, not allocated disk blocks; all samples are retained.", + "This measures regular files/directories, not symlinks, concurrent writers, VMs, or external effects." + ], + "results": { + "content_store": { + "raw_samples": [ + { + "iteration": 1, + "measurement_order": 1, + "snapshot_ms": 14.002097, + "rollback_ms": 11.010268, + "snapshot_plus_rollback_ms": 25.012365, + "restoration_verified": true + }, + { + "iteration": 2, + "measurement_order": 2, + "snapshot_ms": 20.227841, + "rollback_ms": 13.457981, + "snapshot_plus_rollback_ms": 33.685822, + "restoration_verified": true + }, + { + "iteration": 3, + "measurement_order": 1, + "snapshot_ms": 16.881722, + "rollback_ms": 10.396713, + "snapshot_plus_rollback_ms": 27.278435, + "restoration_verified": true + }, + { + "iteration": 4, + "measurement_order": 2, + "snapshot_ms": 18.622814, + "rollback_ms": 12.68471, + "snapshot_plus_rollback_ms": 31.307524, + "restoration_verified": true + }, + { + "iteration": 5, + "measurement_order": 1, + "snapshot_ms": 19.326257, + "rollback_ms": 14.822167, + "snapshot_plus_rollback_ms": 34.148424, + "restoration_verified": true + } + ], + "snapshot_ms": { + "p50": 18.622814, + "p95": 20.0475242, + "min": 14.002097, + "max": 20.227841 + }, + "rollback_ms": { + "p50": 12.68471, + "p95": 14.5493298, + "min": 10.396713, + "max": 14.822167 + }, + "snapshot_plus_rollback_ms": { + "p50": 31.307524, + "p95": 34.0559036, + "min": 25.012365, + "max": 34.148424 + }, + "storage": { + "snapshot_count": 5, + "blob_count": 100, + "blob_bytes": 409600, + "referenced_blob_count": 100, + "unreferenced_blob_count": 0, + "logical_file_bytes": 527938 + } + }, + "full_copy": { + "raw_samples": [ + { + "iteration": 1, + "measurement_order": 2, + "snapshot_ms": 3.269144, + "rollback_ms": 3.516266, + "snapshot_plus_rollback_ms": 6.78541, + "restoration_verified": true + }, + { + "iteration": 2, + "measurement_order": 1, + "snapshot_ms": 3.820358, + "rollback_ms": 3.94961, + "snapshot_plus_rollback_ms": 7.769968, + "restoration_verified": true + }, + { + "iteration": 3, + "measurement_order": 2, + "snapshot_ms": 3.462192, + "rollback_ms": 4.017596, + "snapshot_plus_rollback_ms": 7.479788, + "restoration_verified": true + }, + { + "iteration": 4, + "measurement_order": 1, + "snapshot_ms": 3.892526, + "rollback_ms": 5.537553, + "snapshot_plus_rollback_ms": 9.430079, + "restoration_verified": true + }, + { + "iteration": 5, + "measurement_order": 2, + "snapshot_ms": 4.532875, + "rollback_ms": 8.099122, + "snapshot_plus_rollback_ms": 12.631996999999998, + "restoration_verified": true + } + ], + "snapshot_ms": { + "p50": 3.820358, + "p95": 4.4048052, + "min": 3.269144, + "max": 4.532875 + }, + "rollback_ms": { + "p50": 4.017596, + "p95": 7.586808199999999, + "min": 3.516266, + "max": 8.099122 + }, + "snapshot_plus_rollback_ms": { + "p50": 7.769968, + "p95": 11.991613399999999, + "min": 6.78541, + "max": 12.631996999999998 + }, + "storage": { + "snapshot_count": 5, + "logical_file_bytes": 2048000 + } + } + }, + "all_restorations_verified": true +} diff --git a/docs/results/windows-ntfs.json b/docs/results/windows-ntfs.json new file mode 100644 index 0000000..e673555 --- /dev/null +++ b/docs/results/windows-ntfs.json @@ -0,0 +1,183 @@ +{ + "schema_version": 1, + "description": "Verified local filesystem microbenchmark; no VM or Dedalus measurements", + "context": { + "python": "3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)]", + "os": "Windows-11-10.0.26300-SP0", + "machine": "AMD64", + "processor": "Intel64 Family 6 Model 141 Stepping 1, GenuineIntel", + "logical_cpu_count": 12, + "filesystem": "NTFS", + "temporary_parent": "", + "device_id": 5935374956160347715, + "volume_total_bytes": 482538229760, + "volume_free_bytes": 239715528704 + }, + "workload": { + "seed": 42, + "file_count": 100, + "file_size_bytes": 4096, + "total_file_bytes": 409600, + "directory_count": 11, + "iterations_per_backend": 5, + "mutations_per_sample": { + "files_edited": 25, + "files_deleted": 25, + "files_added": 26, + "directories_added": 1, + "directories_replaced_by_files": 1 + } + }, + "methodology": [ + "Both backends receive the same deterministic fixture and mutations; order alternates.", + "All retained snapshots contain the same baseline; the content store can deduplicate them.", + "The first content-store snapshot starts with an empty store; later samples reuse it.", + "OS caches are not flushed; these are local observed timings, not cold-cache guarantees.", + "Snapshot and rollback timers include each backend's normal integrity and durability work.", + "The full-copy baseline uses copytree/copy2, without extra integrity hashing or explicit fsync.", + "Independent correctness checks and mutation setup are outside timing intervals.", + "Verification compares every relative path, file bytes, mode, and mtime_ns, including empty directories.", + "Percentiles use linear interpolation; few samples do not establish tail-latency guarantees.", + "Storage reports logical file sizes, not allocated disk blocks; all samples are retained.", + "This measures regular files/directories, not symlinks, concurrent writers, VMs, or external effects." + ], + "results": { + "content_store": { + "raw_samples": [ + { + "iteration": 1, + "measurement_order": 1, + "snapshot_ms": 196.4455, + "rollback_ms": 241.3619, + "snapshot_plus_rollback_ms": 437.80740000000003, + "restoration_verified": true + }, + { + "iteration": 2, + "measurement_order": 2, + "snapshot_ms": 227.4352, + "rollback_ms": 243.2281, + "snapshot_plus_rollback_ms": 470.66330000000005, + "restoration_verified": true + }, + { + "iteration": 3, + "measurement_order": 1, + "snapshot_ms": 244.5033, + "rollback_ms": 252.2116, + "snapshot_plus_rollback_ms": 496.7149, + "restoration_verified": true + }, + { + "iteration": 4, + "measurement_order": 2, + "snapshot_ms": 228.5058, + "rollback_ms": 243.3304, + "snapshot_plus_rollback_ms": 471.83619999999996, + "restoration_verified": true + }, + { + "iteration": 5, + "measurement_order": 1, + "snapshot_ms": 237.7346, + "rollback_ms": 242.2016, + "snapshot_plus_rollback_ms": 479.9362, + "restoration_verified": true + } + ], + "snapshot_ms": { + "p50": 228.5058, + "p95": 243.14956, + "min": 196.4455, + "max": 244.5033 + }, + "rollback_ms": { + "p50": 243.2281, + "p95": 250.43536, + "min": 241.3619, + "max": 252.2116 + }, + "snapshot_plus_rollback_ms": { + "p50": 471.83619999999996, + "p95": 493.35916, + "min": 437.80740000000003, + "max": 496.7149 + }, + "storage": { + "snapshot_count": 5, + "blob_count": 100, + "blob_bytes": 409600, + "referenced_blob_count": 100, + "unreferenced_blob_count": 0, + "logical_file_bytes": 527973 + } + }, + "full_copy": { + "raw_samples": [ + { + "iteration": 1, + "measurement_order": 2, + "snapshot_ms": 62.4193, + "rollback_ms": 63.8815, + "snapshot_plus_rollback_ms": 126.30080000000001, + "restoration_verified": true + }, + { + "iteration": 2, + "measurement_order": 1, + "snapshot_ms": 62.4214, + "rollback_ms": 60.3729, + "snapshot_plus_rollback_ms": 122.79429999999999, + "restoration_verified": true + }, + { + "iteration": 3, + "measurement_order": 2, + "snapshot_ms": 52.6163, + "rollback_ms": 61.4043, + "snapshot_plus_rollback_ms": 114.0206, + "restoration_verified": true + }, + { + "iteration": 4, + "measurement_order": 1, + "snapshot_ms": 51.8751, + "rollback_ms": 60.2775, + "snapshot_plus_rollback_ms": 112.1526, + "restoration_verified": true + }, + { + "iteration": 5, + "measurement_order": 2, + "snapshot_ms": 51.8291, + "rollback_ms": 61.6535, + "snapshot_plus_rollback_ms": 113.48259999999999, + "restoration_verified": true + } + ], + "snapshot_ms": { + "p50": 52.6163, + "p95": 62.42098, + "min": 51.8291, + "max": 62.4214 + }, + "rollback_ms": { + "p50": 61.4043, + "p95": 63.435900000000004, + "min": 60.2775, + "max": 63.8815 + }, + "snapshot_plus_rollback_ms": { + "p50": 114.0206, + "p95": 125.5995, + "min": 112.1526, + "max": 126.30080000000001 + }, + "storage": { + "snapshot_count": 5, + "logical_file_bytes": 2048000 + } + } + }, + "all_restorations_verified": true +} diff --git a/init_workspace.py b/init_workspace.py index bfa7caf..a056f33 100644 --- a/init_workspace.py +++ b/init_workspace.py @@ -1,59 +1,9 @@ -#!/usr/bin/env python3 -""" -Initialize the workspace snapshot infrastructure. - -This script sets up the initial snapshot system for the workspace. -Run this once before starting the watcher daemon. -""" - -from pathlib import Path -from snapshot_daemon import WorkspaceSnapshotter - - -def main(): - """Initialize the snapshot system.""" - workspace = Path("/workspace") - - print("=" * 60) - print("GIT-FOR-AGENT-WORKSPACES INITIALIZATION") - print("=" * 60) - print() - - print(f"Workspace: {workspace}") - print() - - # Initialize snapshotter - print("Initializing snapshot system...") - snap = WorkspaceSnapshotter(str(workspace)) - - print(f"Snapshot directory: {snap.snapshot_dir}") - print() - - # Create initial baseline snapshot - print("Creating initial baseline snapshot...") - baseline_id = snap.create_snapshot("initial_baseline") - print(f"Baseline snapshot ID: {baseline_id}") - print() - - # Show status - snapshots = snap.list_snapshots() - print(f"Total snapshots: {len(snapshots)}") - print() - - print("=" * 60) - print("INITIALIZATION COMPLETE") - print("=" * 60) - print() - print("Next steps:") - print(" 1. Start the watcher daemon: python watcher.py --daemon") - print(" 2. Run benchmark: python benchmark.py") - print(" 3. Run demo: python demo.py") - print() - print("Manual commands:") - print(" python snapshot_daemon.py --action snapshot --label 'my_label'") - print(" python snapshot_daemon.py --action rollback") - print(" python snapshot_daemon.py --action list") - +"""Create a workspace and its first checkpoint (legacy entry point).""" +import argparse +from workspace_cli import main if __name__ == "__main__": - main() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--workspace", default="./workspace") + args = parser.parse_args() + raise SystemExit(main(["--workspace", args.workspace, "init"])) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..acc31a5 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "agent-workspace-checkpoints" +version = "0.2.0" +description = "Verified filesystem checkpoints around agent commands" +readme = "README.md" +requires-python = ">=3.10" +license = {text = "MIT"} +authors = [{name = "Sarvesh Tamse"}] +dependencies = [] + +[project.urls] +Repository = "https://github.com/sarvesh2003dev/Git-for-Agent-Workspaces" + +[project.scripts] +workspace-checkpoint = "workspace_cli:main" + +[tool.setuptools] +py-modules = ["snapshot_daemon", "workspace_cli", "benchmark", "demo", "watcher", "init_workspace"] diff --git a/requirements.txt b/requirements.txt index 196ad4f..e75fd16 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1 @@ -watchdog>=6.0.0 +# No third-party runtime dependencies. Requires Python 3.10 or newer. diff --git a/snapshot_daemon.py b/snapshot_daemon.py index a01a8bf..7a1bfd8 100644 --- a/snapshot_daemon.py +++ b/snapshot_daemon.py @@ -1,318 +1,610 @@ -#!/usr/bin/env python3 -""" -Snapshot Daemon - Core overlayfs-based snapshot engine for agent workspaces. - -This module provides sub-second filesystem rollback by using a copy-on-write -approach with hard links (similar to overlayfs principles but in userspace). - -For each snapshot, we: -1. Store only the files that have changed since the last snapshot -2. Use hard links for unchanged files (zero-copy, instant) -3. Maintain a manifest of file states per snapshot +"""Content-addressed filesystem checkpoints for owned, quiescent workspaces. -Rollback is achieved by restoring files from the snapshot manifest. +This is a file-copy implementation, not overlayfs or a VM snapshot. Callers must +stop independent writers while checkpointing/restoring. The lock coordinates +clients of one store; it cannot lock arbitrary processes out of a workspace. +Symlinks, reparse points, and special files are intentionally unsupported. """ +from __future__ import annotations +from contextlib import contextmanager +from datetime import datetime, timezone +import errno +import hashlib +import json +import math import os +from pathlib import Path, PurePosixPath +import re import shutil -import json +import stat +import threading import time -import hashlib -from pathlib import Path -from datetime import datetime -from typing import Optional, Dict, List, Any -from dataclasses import dataclass, asdict - - -@dataclass -class SnapshotManifest: - """Manifest describing the state of files in a snapshot.""" - snapshot_id: str - timestamp: float - label: str - files: Dict[str, dict] # path -> {hash, size, mtime} - - def to_dict(self) -> dict: - return asdict(self) - - @classmethod - def from_dict(cls, data: dict) -> 'SnapshotManifest': - return cls(**data) +from typing import Any, Iterator +import uuid + + +class SnapshotError(RuntimeError): + """A checkpoint operation could not safely complete.""" + + +_ID = re.compile(r"snapshot_[0-9a-f]{32}\Z") +_HASH = re.compile(r"[0-9a-f]{64}\Z") +_TOKEN = re.compile(r"[0-9a-f]{32}\Z") + + +def _plain_stat(path: Path) -> os.stat_result: + info = path.lstat() + if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400: + raise SnapshotError(f"Symlinks/reparse points are unsupported: {path}") + if not (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)): + raise SnapshotError(f"Special files are unsupported: {path}") + return info + + +def _check_ancestors(path: Path) -> None: + for part in reversed((path, *path.parents)): + if os.path.lexists(part): + _plain_stat(part) + + +def _guard_tree(root: Path) -> None: + """Validate all entries, including broken links and junctions.""" + _check_ancestors(root) + stack = [root] + while stack: + path = stack.pop() + if stat.S_ISDIR(_plain_stat(path).st_mode): + stack.extend(path.iterdir()) + + +def _sync_dir(path: Path) -> None: + # Windows has no POSIX directory-fsync interface. Rename recovery works; + # power-loss durability still depends on the operating system/filesystem. + if os.name == "nt": + return + fd = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def _remove_tree(path: Path) -> None: + if not os.path.lexists(path): + return + _guard_tree(path) + + # Only disposable stage/backup trees reach this helper. Make directories + # writable before unlinking children: chmod on a child alone does not grant + # POSIX permission to remove it from a read-only parent directory. + for directory, subdirectories, files in os.walk(path): + current = Path(directory) + current.chmod(stat.S_IMODE(current.stat().st_mode) | 0o700) + for filename in files: + file_path = current / filename + file_path.chmod(stat.S_IMODE(file_path.stat().st_mode) | 0o600) + shutil.rmtree(path) class WorkspaceSnapshotter: + """SHA-256 blobs, atomic manifests, and recoverable whole-tree restores. + + Store and workspace must be disjoint directories. Restore builds a sibling + tree and performs two renames, leaving a brief interval when the workspace + path is absent. A journal/backup recover interrupted renames. No live-writer + isolation, timing bound, ACL/xattr preservation, or network-filesystem lock + guarantee is provided. Stop processes with open workspace files first. """ - High-performance workspace snapshotter using hard-link based COW. - - This achieves <50ms rollback times by: - 1. Only storing changed files (not entire directory) - 2. Using hard links for unchanged files between snapshots - 3. Maintaining lightweight manifests for quick restoration - """ - - def __init__(self, workspace_path: str, snapshot_dir: Optional[str] = None): - self.workspace = Path(workspace_path).resolve() - self.snapshot_dir = Path(snapshot_dir or f"{workspace_path}.snapshots").resolve() - self.snapshots_db = self.snapshot_dir / "snapshots.json" - - # Create snapshot directory structure - self.snapshot_dir.mkdir(parents=True, exist_ok=True) - (self.snapshot_dir / "data").mkdir(exist_ok=True) + + def __init__(self, workspace_path: str, snapshot_dir: str | None = None): + self.workspace = Path(os.path.abspath(os.path.expanduser(workspace_path))) + self.snapshot_dir = Path(os.path.abspath(os.path.expanduser(snapshot_dir or (str(self.workspace) + ".snapshots")))) + self._thread_lock = threading.RLock() + self._depth = 0 + try: + self._check_locations() + if not self.workspace.exists() and not (self.snapshot_dir / "rollback.json").is_file(): + raise SnapshotError(f"Workspace directory does not exist: {self.workspace}") + self.snapshot_dir.mkdir(parents=True, exist_ok=True) + with self.transaction(): + pass + except SnapshotError: + raise + except (OSError, ValueError, TypeError) as exc: + raise SnapshotError(f"Cannot initialize checkpoint store: {exc}") from exc + + def _check_locations(self) -> None: + _check_ancestors(self.workspace) + _check_ancestors(self.snapshot_dir) + workspace = os.path.normcase(str(self.workspace)) + store = os.path.normcase(str(self.snapshot_dir)) + try: + common = os.path.commonpath((workspace, store)) + except ValueError: + common = "" # Different drives; staging stays beside workspace. + if common in (workspace, store): + raise SnapshotError("Workspace and snapshot store must not overlap") + if self.workspace == self.workspace.parent: + raise SnapshotError("A filesystem root cannot be a workspace") + + @contextmanager + def transaction(self) -> Iterator[WorkspaceSnapshotter]: + """Lock checkpoint/action/restore as a unit; nesting is safe per client. + + Independent writers remain the caller's responsibility. Different stores + targeting the same workspace are not coordinated by this lock. + """ + with self._thread_lock: + if self._depth: + self._depth += 1 + try: + yield self + finally: + self._depth -= 1 + return + lock = None + acquired = False + try: + self._check_locations() + # Inspect the stable lock path before locking. Walking mutable + # store entries here races another client's temporary files. + _check_ancestors(self.snapshot_dir / ".lock") + flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) + fd = os.open(self.snapshot_dir / ".lock", flags, 0o600) + lock = os.fdopen(fd, "r+b", buffering=0) + if os.fstat(lock.fileno()).st_size == 0: + lock.write(b"\0") + self._acquire_lock(lock) + acquired = True + self._depth = 1 + self._initialize_store() + _guard_tree(self.snapshot_dir) + self._recover_rollback() + if not self.workspace.is_dir(): + raise SnapshotError(f"Workspace directory does not exist: {self.workspace}") + yield self + except SnapshotError: + raise + except (OSError, TypeError, KeyError) as exc: + raise SnapshotError(f"Checkpoint operation failed: {exc}") from exc + finally: + self._depth = 0 + if lock is not None: + try: + if acquired: + if os.name == "nt": + import msvcrt + lock.seek(0) + msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + fcntl.flock(lock.fileno(), fcntl.LOCK_UN) + finally: + lock.close() + + @staticmethod + def _acquire_lock(lock) -> None: + deadline = time.monotonic() + 30 + while True: + try: + if os.name == "nt": + import msvcrt + lock.seek(0) + msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + return + except OSError as exc: + if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK): + raise + if time.monotonic() >= deadline: + raise SnapshotError("Timed out waiting for the checkpoint-store lock") from exc + time.sleep(0.05) + + def _initialize_store(self) -> None: + expected = {"format": "agent-workspace-checkpoints", "version": 2, "workspace": str(self.workspace)} + format_path = self.snapshot_dir / "format.json" + if not format_path.exists(): + if {p.name for p in self.snapshot_dir.iterdir()} - {".lock"}: + raise SnapshotError("Unrecognized/legacy store; choose a new empty snapshot directory") + self._atomic_json(format_path, expected) + if self._read_json(format_path) != expected: + raise SnapshotError("Unsupported store format or store bound to a different workspace") + (self.snapshot_dir / "blobs").mkdir(exist_ok=True) (self.snapshot_dir / "manifests").mkdir(exist_ok=True) - - # Load or initialize snapshots database - self.snapshots: Dict[str, SnapshotManifest] = {} - self._load_db() - - # Cache for file hashes to avoid recomputing - self._hash_cache: Dict[str, tuple] = {} # path -> (hash, mtime) - - def _load_db(self): - """Load snapshots database from disk.""" - if self.snapshots_db.exists(): - with open(self.snapshots_db, 'r') as f: - data = json.load(f) - for sid, manifest_data in data.items(): - self.snapshots[sid] = SnapshotManifest.from_dict(manifest_data) - - def _save_db(self): - """Save snapshots database to disk.""" - with open(self.snapshots_db, 'w') as f: - json.dump( - {sid: m.to_dict() for sid, m in self.snapshots.items()}, - f, indent=2 - ) - - def _compute_hash(self, filepath: Path) -> str: - """Compute SHA256 hash of a file.""" - hasher = hashlib.sha256() + + @staticmethod + def _read_json(path: Path) -> dict: + if not stat.S_ISREG(_plain_stat(path).st_mode): + raise SnapshotError(f"Expected a regular JSON file: {path}") try: - with open(filepath, 'rb') as f: - for chunk in iter(lambda: f.read(8192), b''): - hasher.update(chunk) - return hasher.hexdigest()[:16] # Use first 16 chars for brevity - except (IOError, PermissionError): - return "" - - def _get_file_info(self, filepath: Path) -> dict: - """Get file metadata and hash.""" + with path.open("r", encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError) as exc: + raise SnapshotError(f"Cannot read JSON file {path}: {exc}") from exc + if not isinstance(data, dict): + raise SnapshotError(f"Invalid JSON object: {path}") + return data + + @staticmethod + def _atomic_json(path: Path, data: dict) -> None: + temporary = path.parent / (".tmp-" + uuid.uuid4().hex) + try: + with temporary.open("x", encoding="utf-8", newline="\n") as handle: + json.dump(data, handle, sort_keys=True, indent=2, allow_nan=False) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + _sync_dir(path.parent) + finally: + if temporary.exists(): + temporary.unlink() + + @staticmethod + def _validate_id(snapshot_id: str) -> None: + if not isinstance(snapshot_id, str) or not _ID.fullmatch(snapshot_id): + raise SnapshotError("Invalid snapshot ID") + + @staticmethod + def _validate_metadata(value: Any) -> None: + if not isinstance(value, dict): + raise SnapshotError("Invalid entry metadata") + if type(value.get("mode")) is not int or not 0 <= value["mode"] <= 0o7777: + raise SnapshotError("Invalid entry mode") + if type(value.get("mtime_ns")) is not int: + raise SnapshotError("Invalid entry modification time") + + @staticmethod + def _validate_relative(relative: str) -> None: + if not isinstance(relative, str) or not relative or "\\" in relative or ":" in relative or "\0" in relative: + raise SnapshotError(f"Unsupported relative path: {relative!r}") + path = PurePosixPath(relative) + if path.is_absolute() or ".." in path.parts or path.as_posix() != relative or relative == ".": + raise SnapshotError(f"Unsafe manifest path: {relative!r}") + + def _load_manifest(self, snapshot_id: str) -> dict: + self._validate_id(snapshot_id) + path = self.snapshot_dir / "manifests" / (snapshot_id + ".json") + if not path.exists(): + raise SnapshotError(f"Snapshot not found: {snapshot_id}") + manifest = self._read_json(path) + if manifest.get("version") != 2 or manifest.get("id") != snapshot_id: + raise SnapshotError(f"Invalid manifest identity: {snapshot_id}") + timestamp = manifest.get("timestamp") + if type(timestamp) not in (int, float) or not math.isfinite(timestamp): + raise SnapshotError("Invalid manifest timestamp") + if not isinstance(manifest.get("label"), str): + raise SnapshotError("Invalid manifest label") + self._validate_metadata(manifest.get("root")) + entries = manifest.get("entries") + if not isinstance(entries, dict): + raise SnapshotError("Invalid manifest entries") + for relative, metadata in entries.items(): + self._validate_relative(relative) + self._validate_metadata(metadata) + if metadata.get("kind") not in ("file", "directory"): + raise SnapshotError(f"Invalid entry type: {relative}") + if metadata["kind"] == "file": + if not isinstance(metadata.get("hash"), str) or not _HASH.fullmatch(metadata["hash"]): + raise SnapshotError(f"Invalid blob hash: {relative}") + if type(metadata.get("size")) is not int or metadata["size"] < 0: + raise SnapshotError(f"Invalid file size: {relative}") + for parent in PurePosixPath(relative).parents: + if str(parent) != "." and entries.get(str(parent), {}).get("kind") != "directory": + raise SnapshotError(f"Missing directory entry: {parent}") + return manifest + + def _all_manifests(self) -> list[dict]: + manifests = [] + for path in sorted((self.snapshot_dir / "manifests").iterdir()): + if path.name.startswith(".tmp-"): + continue + if not path.name.endswith(".json"): + raise SnapshotError(f"Unexpected manifest-store entry: {path.name}") + manifests.append(self._load_manifest(path.stem)) + return manifests + + @staticmethod + def _identity(info: os.stat_result) -> tuple: + # On Windows, lstat and fstat can expose different ctime semantics. + # Comparing them rejected unchanged files. This is a best-effort race + # check only; the contract still requires a quiescent workspace. + identity = info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_mode + return identity if os.name == "nt" else (*identity, info.st_ctime_ns) + + @staticmethod + def _metadata(info: os.stat_result) -> dict: + return {"mode": stat.S_IMODE(info.st_mode), "mtime_ns": info.st_mtime_ns} + + def _store_file(self, source: Path) -> tuple[str, int]: + before = _plain_stat(source) + temporary = self.snapshot_dir / "blobs" / (".tmp-" + uuid.uuid4().hex) + digest = hashlib.sha256() + size = 0 try: - stat = filepath.stat() - current_mtime = stat.st_mtime - - # Check cache - cache_key = str(filepath) - if cache_key in self._hash_cache: - cached_hash, cached_mtime = self._hash_cache[cache_key] - if cached_mtime == current_mtime: - return {"hash": cached_hash, "size": stat.st_size, "mtime": current_mtime} - - # Compute new hash - file_hash = self._compute_hash(filepath) - self._hash_cache[cache_key] = (file_hash, current_mtime) - - return {"hash": file_hash, "size": stat.st_size, "mtime": current_mtime} - except (IOError, PermissionError, FileNotFoundError): - return {"hash": "", "size": 0, "mtime": 0} - + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) + with os.fdopen(os.open(source, flags), "rb") as original, temporary.open("xb") as output: + if self._identity(os.fstat(original.fileno())) != self._identity(before): + raise SnapshotError(f"File changed while opening: {source}") + while chunk := original.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + output.write(chunk) + output.flush() + os.fsync(output.fileno()) + if self._identity(_plain_stat(source)) != self._identity(before): + raise SnapshotError(f"File changed during checkpoint: {source}") + checksum = digest.hexdigest() + target = self.snapshot_dir / "blobs" / checksum + if target.exists(): + self._verify_blob(checksum, size) + else: + os.replace(temporary, target) + _sync_dir(target.parent) + return checksum, size + finally: + if temporary.exists(): + temporary.unlink() + def create_snapshot(self, label: str = "") -> str: - """ - Create a snapshot of the current workspace state. - - Returns the snapshot ID. - """ - snapshot_id = f"snapshot_{int(time.time() * 1000)}" - timestamp = time.time() - - files = {} - snapshot_data_dir = self.snapshot_dir / "data" / snapshot_id - snapshot_data_dir.mkdir(parents=True, exist_ok=True) - - # Scan workspace for all files - for filepath in self.workspace.rglob("*"): - if filepath.is_file() and ".snapshots" not in str(filepath): - rel_path = str(filepath.relative_to(self.workspace)) - - # Skip our own snapshot files - if rel_path.startswith(".snapshots"): - continue - - file_info = self._get_file_info(filepath) - if file_info["hash"]: # Only track readable files - files[rel_path] = file_info - - # Store file content using hash-based deduplication - hash_path = self.snapshot_dir / "data" / file_info["hash"] - if not hash_path.exists(): - shutil.copy2(filepath, hash_path) - - # Create manifest - manifest = SnapshotManifest( - snapshot_id=snapshot_id, - timestamp=timestamp, - label=label, - files=files - ) - - # Save manifest - manifest_path = self.snapshot_dir / "manifests" / f"{snapshot_id}.json" - with open(manifest_path, 'w') as f: - json.dump(manifest.to_dict(), f, indent=2) - - self.snapshots[snapshot_id] = manifest - self._save_db() - - return snapshot_id - + with self.transaction(): + if not isinstance(label, str): + raise SnapshotError("Snapshot label must be text") + _guard_tree(self.workspace) + root_stat = self.workspace.stat() + entries: dict[str, dict] = {} + identities = {} + for path in sorted(self.workspace.rglob("*")): + relative = path.relative_to(self.workspace).as_posix() + self._validate_relative(relative) + info = _plain_stat(path) + identities[relative] = self._identity(info) + metadata = self._metadata(info) + if stat.S_ISDIR(info.st_mode): + metadata["kind"] = "directory" + else: + checksum, size = self._store_file(path) + metadata.update(kind="file", hash=checksum, size=size) + entries[relative] = metadata + # Detect ordinary edits, not a substitute for caller quiescence. + current = {p.relative_to(self.workspace).as_posix() for p in self.workspace.rglob("*")} + if current != set(entries) or self._identity(self.workspace.stat()) != self._identity(root_stat): + raise SnapshotError("Workspace changed during checkpoint") + for relative, identity in identities.items(): + if self._identity(_plain_stat(self.workspace / relative)) != identity: + raise SnapshotError(f"Workspace changed during checkpoint: {relative}") + snapshot_id = "snapshot_" + uuid.uuid4().hex + manifest = {"version": 2, "id": snapshot_id, "timestamp": time.time(), "label": label, + "root": self._metadata(root_stat), "entries": entries} + self._atomic_json(self.snapshot_dir / "manifests" / (snapshot_id + ".json"), manifest) + return snapshot_id + + def _verify_blob(self, checksum: str, expected_size: int) -> None: + path = self.snapshot_dir / "blobs" / checksum + if not path.exists(): + raise SnapshotError(f"Missing content blob: {checksum}") + info = _plain_stat(path) + if not stat.S_ISREG(info.st_mode) or info.st_size != expected_size: + raise SnapshotError(f"Invalid content blob size/type: {checksum}") + digest = hashlib.sha256() + with path.open("rb") as handle: + while chunk := handle.read(1024 * 1024): + digest.update(chunk) + if digest.hexdigest() != checksum: + raise SnapshotError(f"Corrupt content blob: {checksum}") + + def _verify_manifest(self, manifest: dict) -> dict: + verified = {} + file_count = directory_count = total_bytes = 0 + for metadata in manifest["entries"].values(): + if metadata["kind"] == "directory": + directory_count += 1 + continue + checksum, size = metadata["hash"], metadata["size"] + if checksum in verified and verified[checksum] != size: + raise SnapshotError("Inconsistent sizes for the same content blob") + if checksum not in verified: + self._verify_blob(checksum, size) + verified[checksum] = size + file_count += 1 + total_bytes += size + return {"id": manifest["id"], "valid": True, "file_count": file_count, + "directory_count": directory_count, "total_bytes": total_bytes} + + def verify_snapshot(self, snapshot_id: str) -> dict: + with self.transaction(): + return self._verify_manifest(self._load_manifest(snapshot_id)) + + @staticmethod + def _apply_metadata(path: Path, metadata: dict) -> None: + os.utime(path, ns=(metadata["mtime_ns"], metadata["mtime_ns"])) + os.chmod(path, metadata["mode"]) + + def _build_stage(self, stage: Path, manifest: dict) -> None: + stage.mkdir(mode=0o700) + entries = manifest["entries"] + directories = [rel for rel, meta in entries.items() if meta["kind"] == "directory"] + for relative in sorted(directories, key=lambda value: (value.count("/"), value)): + (stage / relative).mkdir(mode=0o700) + for relative, metadata in entries.items(): + if metadata["kind"] != "file": + continue + target = stage / relative + source = self.snapshot_dir / "blobs" / metadata["hash"] + digest = hashlib.sha256() + with source.open("rb") as original, target.open("xb") as restored: + while chunk := original.read(1024 * 1024): + digest.update(chunk) + restored.write(chunk) + restored.flush() + os.fsync(restored.fileno()) + if digest.hexdigest() != metadata["hash"] or target.stat().st_size != metadata["size"]: + raise SnapshotError(f"Blob changed during restore: {relative}") + self._apply_metadata(target, metadata) + for relative in sorted(directories, key=lambda value: (value.count("/"), value), reverse=True): + _sync_dir(stage / relative) + self._apply_metadata(stage / relative, entries[relative]) + _sync_dir(stage) + self._apply_metadata(stage, manifest["root"]) + _sync_dir(stage.parent) + + def _journal_paths(self, journal: dict) -> tuple[Path, Path]: + token = journal.get("token") + if journal.get("version") != 1 or journal.get("workspace") != str(self.workspace): + raise SnapshotError("Rollback journal belongs to a different workspace or format") + if not isinstance(token, str) or not _TOKEN.fullmatch(token): + raise SnapshotError("Invalid rollback journal token") + if journal.get("phase") not in ("prepared", "backed_up", "installed"): + raise SnapshotError("Invalid rollback journal phase") + self._validate_id(journal.get("snapshot_id")) + return (self.workspace.parent / f".{self.workspace.name}.restore-{token}", + self.workspace.parent / f".{self.workspace.name}.backup-{token}") + + def _recover_rollback(self) -> None: + journal_path = self.snapshot_dir / "rollback.json" + if not journal_path.exists(): + return + journal = self._read_json(journal_path) + stage, backup = self._journal_paths(journal) + for candidate in (stage, backup): + if os.path.lexists(candidate): + _guard_tree(candidate) + if not candidate.is_dir(): + raise SnapshotError(f"Rollback recovery expected a directory: {candidate}") + workspace_exists = self.workspace.exists() + if backup.exists() and not workspace_exists: + os.replace(backup, self.workspace) + _sync_dir(self.workspace.parent) + _remove_tree(stage) + elif backup.exists() and workspace_exists and not stage.exists(): + # Stage-to-workspace rename committed, possibly before the journal + # update. Keep the target and finish cleanup. + _guard_tree(self.workspace) + _remove_tree(backup) + elif workspace_exists and not backup.exists(): + _remove_tree(stage) + else: + raise SnapshotError("Ambiguous recovery; workspace/stage/backup preserved for inspection") + _sync_dir(self.workspace.parent) + journal_path.unlink() + _sync_dir(self.snapshot_dir) + def rollback(self, snapshot_id: str) -> bool: - """ - Rollback workspace to a specific snapshot. - - This is the critical path - must complete in <50ms. - """ - start_time = time.perf_counter() - - if snapshot_id not in self.snapshots: - print(f"Error: Snapshot {snapshot_id} not found") - return False - - manifest = self.snapshots[snapshot_id] - - # Get current files to detect deletions - current_files = set() - for filepath in self.workspace.rglob("*"): - if filepath.is_file() and ".snapshots" not in str(filepath): - rel_path = str(filepath.relative_to(self.workspace)) - if not rel_path.startswith(".snapshots"): - current_files.add(rel_path) - - # Files to delete (exist now but not in snapshot) - snapshot_files = set(manifest.files.keys()) - files_to_delete = current_files - snapshot_files - - # Delete files that shouldn't exist - for rel_path in files_to_delete: - filepath = self.workspace / rel_path + with self.transaction(): + manifest = self._load_manifest(snapshot_id) + self._verify_manifest(manifest) # Whole preflight before mutation. + _guard_tree(self.workspace) + token = uuid.uuid4().hex + journal = {"version": 1, "token": token, "workspace": str(self.workspace), + "snapshot_id": snapshot_id, "phase": "prepared"} + stage, backup = self._journal_paths(journal) + journal_path = self.snapshot_dir / "rollback.json" try: - filepath.unlink() - except (IOError, PermissionError): - pass - - # Restore files from snapshot - for rel_path, file_info in manifest.files.items(): - filepath = self.workspace / rel_path - - # Ensure parent directory exists - filepath.parent.mkdir(parents=True, exist_ok=True) - - # Restore from hash-based storage - hash_path = self.snapshot_dir / "data" / file_info["hash"] - if hash_path.exists(): - shutil.copy2(hash_path, filepath) - - # Clear hash cache to force re-computation - self._hash_cache.clear() - - elapsed_ms = (time.perf_counter() - start_time) * 1000 - print(f"Rollback completed in {elapsed_ms:.2f}ms") - - return True - - def list_snapshots(self) -> List[Dict[str, Any]]: - """List all available snapshots.""" - result = [] - for sid, manifest in sorted( - self.snapshots.items(), - key=lambda x: x[1].timestamp - ): - result.append({ - "id": sid, - "timestamp": datetime.fromtimestamp(manifest.timestamp).isoformat(), - "label": manifest.label, - "file_count": len(manifest.files) - }) - return result - - def get_latest_snapshot(self) -> Optional[str]: - """Get the most recent snapshot ID.""" - if not self.snapshots: - return None - return max(self.snapshots.keys(), key=lambda k: self.snapshots[k].timestamp) - + self._build_stage(stage, manifest) + self._atomic_json(journal_path, journal) + os.replace(self.workspace, backup) + _sync_dir(self.workspace.parent) + journal["phase"] = "backed_up" + self._atomic_json(journal_path, journal) + os.replace(stage, self.workspace) + _sync_dir(self.workspace.parent) + journal["phase"] = "installed" + self._atomic_json(journal_path, journal) + _remove_tree(backup) + _sync_dir(self.workspace.parent) + journal_path.unlink() + _sync_dir(self.snapshot_dir) + except Exception as exc: + try: + if journal_path.exists(): + self._recover_rollback() + else: + _remove_tree(stage) + except Exception as recovery_exc: + raise SnapshotError(f"Rollback interrupted; recovery data preserved in {journal_path}: {recovery_exc}") from exc + raise SnapshotError(f"Rollback encountered an error; recovery completed: {exc}") from exc + return True + + def list_snapshots(self) -> list[dict]: + with self.transaction(): + return [{"id": item["id"], + "timestamp": datetime.fromtimestamp(item["timestamp"], timezone.utc).isoformat(), + "label": item["label"], + "file_count": sum(meta["kind"] == "file" for meta in item["entries"].values()), + "directory_count": sum(meta["kind"] == "directory" for meta in item["entries"].values())} + for item in sorted(self._all_manifests(), key=lambda item: (item["timestamp"], item["id"]))] + + def get_latest_snapshot(self) -> str | None: + with self.transaction(): + manifests = self._all_manifests() + return max(manifests, key=lambda item: (item["timestamp"], item["id"]))["id"] if manifests else None + + def _referenced_blobs(self) -> set[str]: + return {meta["hash"] for manifest in self._all_manifests() + for meta in manifest["entries"].values() if meta["kind"] == "file"} + + def _garbage_collect(self) -> None: + referenced = self._referenced_blobs() + for path in (self.snapshot_dir / "blobs").iterdir(): + if not stat.S_ISREG(_plain_stat(path).st_mode): + raise SnapshotError(f"Unexpected blob directory: {path.name}") + if not (_HASH.fullmatch(path.name) or path.name.startswith(".tmp-")): + raise SnapshotError(f"Unexpected blob-store entry: {path.name}") + if path.name not in referenced: + path.unlink() + _sync_dir(self.snapshot_dir / "blobs") + def delete_snapshot(self, snapshot_id: str) -> bool: - """Delete a snapshot.""" - if snapshot_id not in self.snapshots: - return False - - manifest = self.snapshots[snapshot_id] - - # Remove manifest - manifest_path = self.snapshot_dir / "manifests" / f"{snapshot_id}.json" - if manifest_path.exists(): - manifest_path.unlink() - - # Remove snapshot data directory - data_dir = self.snapshot_dir / "data" / snapshot_id - if data_dir.exists(): - shutil.rmtree(data_dir) - - del self.snapshots[snapshot_id] - self._save_db() - - return True - - def cleanup_old_snapshots(self, keep_last_n: int = 10): - """Remove old snapshots, keeping only the last N.""" - snapshots = sorted( - self.snapshots.keys(), - key=lambda k: self.snapshots[k].timestamp, - reverse=True - ) - - for sid in snapshots[keep_last_n:]: - self.delete_snapshot(sid) + with self.transaction(): + self._load_manifest(snapshot_id) + self._all_manifests() + (self.snapshot_dir / "manifests" / (snapshot_id + ".json")).unlink() + _sync_dir(self.snapshot_dir / "manifests") + self._garbage_collect() + return True + + def cleanup_old_snapshots(self, keep_last_n: int = 10) -> None: + with self.transaction(): + if type(keep_last_n) is not int or keep_last_n < 0: + raise SnapshotError("keep_last_n must be a nonnegative integer") + manifests = sorted(self._all_manifests(), key=lambda item: (item["timestamp"], item["id"]), reverse=True) + for manifest in manifests[keep_last_n:]: + (self.snapshot_dir / "manifests" / (manifest["id"] + ".json")).unlink() + _sync_dir(self.snapshot_dir / "manifests") + self._garbage_collect() + + def storage_stats(self) -> dict: + with self.transaction(): + manifests = self._all_manifests() + referenced = self._referenced_blobs() + blobs = [] + for path in (self.snapshot_dir / "blobs").iterdir(): + if _HASH.fullmatch(path.name): + if not stat.S_ISREG(_plain_stat(path).st_mode): + raise SnapshotError(f"Invalid blob type: {path.name}") + blobs.append(path) + return {"snapshot_count": len(manifests), "blob_count": len(blobs), + "blob_bytes": sum(path.stat().st_size for path in blobs), + "referenced_blob_count": len(referenced), + "unreferenced_blob_count": len({path.name for path in blobs} - referenced)} + + def diff_snapshots(self, before: str, after: str) -> dict[str, list[str]]: + with self.transaction(): + first = self._load_manifest(before)["entries"] + second = self._load_manifest(after)["entries"] + return {"added": sorted(second.keys() - first.keys()), + "removed": sorted(first.keys() - second.keys()), + "modified": sorted(path for path in first.keys() & second.keys() if first[path] != second[path])} def main(): - """CLI interface for the snapshot daemon.""" - import argparse - - parser = argparse.ArgumentParser(description="Workspace Snapshot Daemon") - parser.add_argument("workspace", nargs="?", default="/workspace", - help="Path to workspace directory") - parser.add_argument("--action", choices=["snapshot", "rollback", "list", "init"], - default="list", help="Action to perform") - parser.add_argument("--label", default="", help="Snapshot label") - parser.add_argument("--snapshot-id", help="Snapshot ID for rollback") - - args = parser.parse_args() - - snap = WorkspaceSnapshotter(args.workspace) - - if args.action == "snapshot": - sid = snap.create_snapshot(args.label) - print(f"Created snapshot: {sid}") - elif args.action == "rollback": - if args.snapshot_id: - snap.rollback(args.snapshot_id) - else: - latest = snap.get_latest_snapshot() - if latest: - snap.rollback(latest) - else: - print("No snapshots available") - elif args.action == "list": - snapshots = snap.list_snapshots() - if snapshots: - print(f"{'ID':<40} {'Timestamp':<25} {'Label':<20} {'Files':<10}") - print("-" * 95) - for s in snapshots: - print(f"{s['id']:<40} {s['timestamp']:<25} {s['label']:<20} {s['file_count']:<10}") - else: - print("No snapshots available") - elif args.action == "init": - print(f"Initialized snapshot system for {args.workspace}") + # The package CLI owns argument validation and nonzero error exits. + from workspace_cli import main as cli_main + return cli_main() if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/tests/test_adversarial.py b/tests/test_adversarial.py new file mode 100644 index 0000000..efdda17 --- /dev/null +++ b/tests/test_adversarial.py @@ -0,0 +1,342 @@ +"""Failure-oriented contract checks for the workspace snapshot store. + +These tests deliberately damage isolated temporary stores. They never operate on +the checkout itself. Platform features are skipped only when unavailable. +""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from snapshot_daemon import SnapshotError, WorkspaceSnapshotter + + +class AdversarialSnapshotTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="snapshot-adversarial-") + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.workspace = self.root / "workspace" + self.workspace.mkdir() + self.store = self.root / "store" + self.snap = WorkspaceSnapshotter(str(self.workspace), str(self.store)) + + def write(self, relative, content): + path = self.workspace / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + return path + + def tree(self): + """Compare observable names and file contents without relying on mtimes.""" + result = {} + for path in sorted(self.workspace.rglob("*")): + name = path.relative_to(self.workspace).as_posix() + if path.is_symlink(): + result[name] = ("symlink", os.readlink(path)) + elif path.is_dir(): + result[name] = ("directory",) + else: + result[name] = ("file", path.read_bytes()) + return result + + def make_symlink(self, target, link, directory=False): + try: + link.symlink_to(target, target_is_directory=directory) + except (NotImplementedError, OSError) as exc: + self.skipTest(f"symlink creation is unavailable: {exc}") + + def snapshot_then_change(self): + self.write("tracked.txt", b"original contents") + sid = self.snap.create_snapshot("before failure") + self.write("tracked.txt", b"uncommitted contents") + self.write("untracked.txt", b"must not be deleted on failed restore") + return sid + + def only_blob(self): + blobs = [path for path in (self.store / "blobs").iterdir() if path.is_file()] + self.assertEqual(len(blobs), 1) + return blobs[0] + + def test_same_size_and_mtime_edit_is_not_mistaken_for_unchanged_data(self): + path = self.write("tracked.txt", b"AAAA") + old = path.stat() + first = self.snap.create_snapshot("first") + path.write_bytes(b"BBBB") + os.utime(path, ns=(old.st_atime_ns, old.st_mtime_ns)) + second = self.snap.create_snapshot("same metadata, different bytes") + path.write_bytes(b"CCCC") + self.assertTrue(self.snap.rollback(second)) + self.assertEqual(path.read_bytes(), b"BBBB") + self.assertTrue(self.snap.rollback(first)) + self.assertEqual(path.read_bytes(), b"AAAA") + + def test_clients_created_before_writes_refresh_persisted_state(self): + other = WorkspaceSnapshotter(str(self.workspace), str(self.store)) + self.write("tracked.txt", b"first") + first = self.snap.create_snapshot("first client") + self.write("tracked.txt", b"second") + second = other.create_snapshot("second client") + self.assertNotEqual(first, second) + for client in (self.snap, other): + self.assertEqual({item["id"] for item in client.list_snapshots()}, {first, second}) + self.snap.delete_snapshot(first) + self.assertEqual([item["id"] for item in other.list_snapshots()], [second]) + reloaded = WorkspaceSnapshotter(str(self.workspace), str(self.store)) + self.write("tracked.txt", b"later") + self.assertTrue(reloaded.rollback(second)) + self.assertEqual((self.workspace / "tracked.txt").read_bytes(), b"second") + + def test_missing_blob_is_reported_before_workspace_mutation(self): + sid = self.snapshot_then_change() + before = self.tree() + blob = self.only_blob() + blob.chmod(0o600) + blob.unlink() + with self.assertRaises(SnapshotError): + self.snap.verify_snapshot(sid) + with self.assertRaises(SnapshotError): + self.snap.rollback(sid) + self.assertEqual(self.tree(), before) + + def test_same_size_blob_corruption_is_reported_before_mutation(self): + sid = self.snapshot_then_change() + before = self.tree() + blob = self.only_blob() + blob.chmod(0o600) + blob.write_bytes(b"X" * blob.stat().st_size) + with self.assertRaises(SnapshotError): + self.snap.verify_snapshot(sid) + with self.assertRaises(SnapshotError): + self.snap.rollback(sid) + self.assertEqual(self.tree(), before) + + def test_invalid_or_unknown_snapshot_ids_leave_workspace_unchanged(self): + self.snapshot_then_change() + before = self.tree() + ids = ("", "..", "../escape", "/absolute", "C:\\escape", "a/b", "snapshot_" + "0" * 32) + for sid in ids: + with self.subTest(snapshot_id=sid): + with self.assertRaises(SnapshotError): + self.snap.rollback(sid) + self.assertEqual(self.tree(), before) + + def test_malicious_manifest_paths_cannot_escape_workspace(self): + sid = self.snapshot_then_change() + manifest_path = self.store / "manifests" / f"{sid}.json" + original = json.loads(manifest_path.read_text(encoding="utf-8")) + self.assertIn("tracked.txt", original["entries"]) + outside = self.root / "escape.txt" + outside.write_bytes(b"outside sentinel") + before = self.tree() + for name in ("../escape.txt", "nested/../../escape.txt", str(outside), "C:\\escape.txt"): + with self.subTest(path=name): + data = json.loads(json.dumps(original)) + data["entries"][name] = data["entries"].pop("tracked.txt") + manifest_path.write_text(json.dumps(data), encoding="utf-8") + with self.assertRaises(SnapshotError): + self.snap.rollback(sid) + self.assertEqual(self.tree(), before) + self.assertEqual(outside.read_bytes(), b"outside sentinel") + + def test_truncated_manifest_never_silently_restores_partial_tree(self): + sid = self.snapshot_then_change() + before = self.tree() + manifest_path = self.store / "manifests" / f"{sid}.json" + manifest_path.write_text('{"files":', encoding="utf-8") + with self.assertRaises(SnapshotError): + self.snap.rollback(sid) + self.assertEqual(self.tree(), before) + + def test_workspace_local_snapshot_store_is_rejected(self): + with self.assertRaises(SnapshotError): + WorkspaceSnapshotter(str(self.workspace), str(self.workspace / "hidden-store")) + + def test_store_cannot_be_reused_for_a_different_workspace(self): + self.write("tracked.txt", b"first workspace") + sid = self.snap.create_snapshot("belongs to first workspace") + other_workspace = self.root / "other-workspace" + other_workspace.mkdir() + sentinel = other_workspace / "sentinel" + sentinel.write_bytes(b"second workspace") + with self.assertRaises(SnapshotError): + WorkspaceSnapshotter(str(other_workspace), str(self.store)) + self.assertEqual(sentinel.read_bytes(), b"second workspace") + self.assertTrue(self.snap.verify_snapshot(sid)["valid"]) + + def test_regular_file_symlink_is_rejected_without_following_target(self): + target = self.root / "outside.txt" + target.write_bytes(b"outside sentinel") + self.make_symlink(target, self.workspace / "link") + with self.assertRaises(SnapshotError): + self.snap.create_snapshot("unsupported link") + self.assertEqual(target.read_bytes(), b"outside sentinel") + self.assertEqual(self.snap.list_snapshots(), []) + + def test_directory_symlink_is_rejected_without_following_target(self): + target = self.root / "outside-dir" + target.mkdir() + (target / "secret.txt").write_bytes(b"outside sentinel") + self.make_symlink(target, self.workspace / "link", directory=True) + with self.assertRaises(SnapshotError): + self.snap.create_snapshot("unsupported directory link") + self.assertEqual(self.snap.list_snapshots(), []) + + def test_dangling_symlink_is_rejected_instead_of_omitted(self): + self.make_symlink(self.root / "does-not-exist", self.workspace / "dangling") + with self.assertRaises(SnapshotError): + self.snap.create_snapshot("dangling link") + self.assertEqual(self.snap.list_snapshots(), []) + + def test_blob_symlink_is_rejected_without_using_external_data(self): + sid = self.snapshot_then_change() + before = self.tree() + blob = self.only_blob() + external = self.root / "external-blob" + external.write_bytes(blob.read_bytes()) + # Probe capability first, so an unavailable feature does not corrupt this store. + probe = self.root / "probe-link" + self.make_symlink(external, probe) + probe.unlink() + blob.chmod(0o600) + blob.unlink() + blob.symlink_to(external) + with self.assertRaises(SnapshotError): + self.snap.rollback(sid) + self.assertEqual(self.tree(), before) + + @unittest.skipUnless(hasattr(os, "mkfifo"), "POSIX FIFO support is unavailable") + def test_fifo_is_rejected_promptly_instead_of_blocking_read(self): + os.mkfifo(self.workspace / "named-pipe") + script = ( + "import sys\n" + "from snapshot_daemon import WorkspaceSnapshotter, SnapshotError\n" + "try:\n" + " WorkspaceSnapshotter(sys.argv[1], sys.argv[2]).create_snapshot()\n" + "except SnapshotError:\n" + " sys.exit(0)\n" + "sys.exit(7)\n" + ) + result = subprocess.run( + [sys.executable, "-c", script, str(self.workspace), str(self.store)], + cwd=Path(__file__).resolve().parents[1], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.snap.list_snapshots(), []) + + def test_nested_transaction_releases_lock_when_user_operation_raises(self): + with self.assertRaisesRegex(ValueError, "user operation failed"): + with self.snap.transaction(): + with self.snap.transaction(): + self.write("tracked.txt", b"kept") + self.snap.create_snapshot("inside nested lock") + raise ValueError("user operation failed") + # New process must acquire the lock; same-process reentrancy could hide a leak. + script = ( + "import sys; from snapshot_daemon import WorkspaceSnapshotter; " + "s=WorkspaceSnapshotter(sys.argv[1],sys.argv[2]); " + "assert len(s.list_snapshots()) == 1" + ) + result = subprocess.run( + [sys.executable, "-c", script, str(self.workspace), str(self.store)], + cwd=Path(__file__).resolve().parents[1], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_concurrent_processes_publish_all_snapshots_without_lost_updates(self): + self.write("tracked.txt", b"shared unchanged workspace") + script = ( + "import json, sys\n" + "from snapshot_daemon import WorkspaceSnapshotter\n" + "s = WorkspaceSnapshotter(sys.argv[1], sys.argv[2])\n" + "print(json.dumps([s.create_snapshot('parallel') for _ in range(3)]))\n" + ) + processes = [] + try: + for _ in range(4): + processes.append(subprocess.Popen( + [sys.executable, "-c", script, str(self.workspace), str(self.store)], + cwd=Path(__file__).resolve().parents[1], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + )) + created = [] + for process in processes: + stdout, stderr = process.communicate(timeout=20) + self.assertEqual(process.returncode, 0, stdout + stderr) + created.extend(json.loads(stdout)) + self.assertEqual(len(set(created)), 12) + self.assertEqual({item["id"] for item in self.snap.list_snapshots()}, set(created)) + for sid in created: + self.assertTrue(self.snap.verify_snapshot(sid)["valid"]) + finally: + for process in processes: + if process.poll() is None: + process.kill() + process.communicate() + + def crash_during_restore(self, sid, crashpoint): + """Kill a subprocess after a real directory rename, without exception cleanup.""" + script = ( + "import os, sys\n" + "from pathlib import Path\n" + "import snapshot_daemon\n" + "workspace = Path(sys.argv[1]).resolve()\n" + "s = snapshot_daemon.WorkspaceSnapshotter(str(workspace), sys.argv[2])\n" + "real_replace = os.replace\n" + "def interrupted_replace(src, dst, *args, **kwargs):\n" + " real_replace(src, dst, *args, **kwargs)\n" + " old_moved = Path(src) == workspace and Path(dst) != workspace\n" + " new_installed = Path(dst) == workspace and Path(src) != workspace\n" + " if (sys.argv[4] == 'old_moved' and old_moved) or (sys.argv[4] == 'new_installed' and new_installed):\n" + " os._exit(91)\n" + "snapshot_daemon.os.replace = interrupted_replace\n" + "s.rollback(sys.argv[3])\n" + "sys.exit(7)\n" + ) + result = subprocess.run( + [sys.executable, "-c", script, str(self.workspace), str(self.store), sid, crashpoint], + cwd=Path(__file__).resolve().parents[1], + capture_output=True, + text=True, + timeout=20, + check=False, + ) + self.assertEqual(result.returncode, 91, result.stdout + result.stderr) + + def test_process_crash_after_old_tree_rename_recovers_original_workspace(self): + sid = self.snapshot_then_change() + before = self.tree() + self.crash_during_restore(sid, "old_moved") + recovered = WorkspaceSnapshotter(str(self.workspace), str(self.store)) + self.assertEqual(self.tree(), before) + self.assertFalse((self.store / "rollback.json").exists()) + self.assertTrue(recovered.verify_snapshot(sid)["valid"]) + self.assertTrue(recovered.rollback(sid)) + self.assertEqual((self.workspace / "tracked.txt").read_bytes(), b"original contents") + + def test_process_crash_after_new_tree_rename_preserves_complete_target(self): + sid = self.snapshot_then_change() + self.crash_during_restore(sid, "new_installed") + recovered = WorkspaceSnapshotter(str(self.workspace), str(self.store)) + self.assertEqual(self.tree(), {"tracked.txt": ("file", b"original contents")}) + self.assertFalse((self.store / "rollback.json").exists()) + self.assertTrue(recovered.verify_snapshot(sid)["valid"]) + self.assertTrue(recovered.rollback(sid)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_benchmark_demo.py b/tests/test_benchmark_demo.py new file mode 100644 index 0000000..ffcafa7 --- /dev/null +++ b/tests/test_benchmark_demo.py @@ -0,0 +1,68 @@ +"""Verify the public demonstrations reject incorrect or merely fast recovery.""" + +import contextlib +import io +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import benchmark +import demo + + +class BenchmarkDemoTests(unittest.TestCase): + def test_demo_recovers_real_command_damage(self): + with tempfile.TemporaryDirectory() as temporary: + result = demo.run_demo(temp_parent=temporary) + self.assertEqual(result["initial_checks_exit_code"], 0) + self.assertEqual(result["mutation_command_exit_code"], 0) + self.assertNotEqual(result["checks_after_mutation_exit_code"], 0) + self.assertEqual(result["checks_after_rollback_exit_code"], 0) + self.assertTrue(result["restoration_verified"]) + self.assertFalse(result["uses_llm"]) + self.assertEqual(list(Path(temporary).iterdir()), []) + + def test_benchmark_verifies_both_backends_and_writes_raw_results(self): + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "report.json" + with contextlib.redirect_stdout(io.StringIO()): + exit_code = benchmark.main(["--files", "4", "--size-kib", "1", + "--iterations", "2", "--seed", "9", + "--temp-parent", temporary, "--json", str(output)]) + self.assertEqual(exit_code, 0) + result = json.loads(output.read_text(encoding="utf-8")) + self.assertEqual(result["workload"]["total_file_bytes"], 4096) + self.assertEqual(set(result["results"]), {"content_store", "full_copy"}) + for backend in result["results"].values(): + self.assertEqual(len(backend["raw_samples"]), 2) + self.assertTrue(all(sample["restoration_verified"] for sample in backend["raw_samples"])) + self.assertLessEqual(backend["rollback_ms"]["p50"], backend["rollback_ms"]["p95"]) + self.assertEqual(backend["storage"]["snapshot_count"], 2) + self.assertEqual(list(Path(temporary).iterdir()), [output]) + + def test_benchmark_rejects_engine_claiming_success_without_restoring(self): + with tempfile.TemporaryDirectory() as temporary: + with patch("benchmark.WorkspaceSnapshotter") as engine: + engine.return_value.rollback.return_value = True + with self.assertRaisesRegex(AssertionError, "Restore verification failed"): + benchmark.run_benchmark(files=2, size_kib=1, iterations=1, temp_parent=temporary) + self.assertEqual(list(Path(temporary).iterdir()), []) + + def test_verifier_detects_corruption_even_when_size_and_mtime_match(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + path = root / "data.bin" + path.write_bytes(b"good") + expected = benchmark.tree_inventory(root) + mtime_ns = path.stat().st_mtime_ns + path.write_bytes(b"evil") + os.utime(path, ns=(mtime_ns, mtime_ns)) + with self.assertRaisesRegex(AssertionError, "Restore verification failed"): + benchmark.assert_restored(root, expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..8c58cd8 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,100 @@ +"""Exercise the actual CLI boundary, subprocess exit codes, and recovery.""" +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from snapshot_daemon import WorkspaceSnapshotter + + +ROOT = Path(__file__).resolve().parents[1] + + +class CommandLineTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.workspace = Path(self.temp.name) / "project" + self.workspace.mkdir() + (self.workspace / "config.txt").write_text("working", encoding="utf-8") + + def cli(self, *args, entry="workspace_cli.py"): + return subprocess.run( + [sys.executable, str(ROOT / entry), "--workspace", str(self.workspace), *args], + text=True, capture_output=True, cwd=ROOT, timeout=30, + ) + + def test_failed_command_restores_exact_state_and_exit_code(self): + (self.workspace / "empty").mkdir() + result = self.cli("run", "--", sys.executable, "-c", + "from pathlib import Path; " + "Path('config.txt').write_text('broken'); " + "Path('extra.txt').write_text('new'); " + "Path('empty').rmdir(); raise SystemExit(7)") + self.assertEqual(result.returncode, 7, result.stderr) + self.assertEqual((self.workspace / "config.txt").read_text(), "working") + self.assertFalse((self.workspace / "extra.txt").exists()) + self.assertTrue((self.workspace / "empty").is_dir()) + self.assertIn("restored", result.stderr) + self.assertEqual(len(WorkspaceSnapshotter(str(self.workspace)).list_snapshots()), 1) + + def test_successful_command_keeps_changes(self): + result = self.cli("run", "--", sys.executable, "-c", + "from pathlib import Path; Path('config.txt').write_text('improved')") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((self.workspace / "config.txt").read_text(), "improved") + + def test_init_creates_missing_workspace_and_preserves_existing(self): + first = self.cli("init") + self.assertEqual(first.returncode, 0, first.stderr) + self.assertIn("snapshot_id", json.loads(first.stdout)) + self.assertEqual((self.workspace / "config.txt").read_text(), "working") + self.workspace = Path(self.temp.name) / "new" / "nested" + second = self.cli("init") + self.assertEqual(second.returncode, 0, second.stderr) + self.assertTrue(self.workspace.is_dir()) + + def test_manual_snapshot_verify_restore_and_prune(self): + created = self.cli("snapshot", "--label", "known good") + self.assertEqual(created.returncode, 0, created.stderr) + sid = json.loads(created.stdout)["snapshot_id"] + checked = self.cli("verify", sid) + self.assertEqual(checked.returncode, 0, checked.stderr) + (self.workspace / "config.txt").write_text("broken", encoding="utf-8") + restored = self.cli("restore", sid) + self.assertEqual(restored.returncode, 0, restored.stderr) + self.assertEqual((self.workspace / "config.txt").read_text(), "working") + listing = self.cli("list") + self.assertEqual(json.loads(listing.stdout)[0]["label"], "known good") + pruned = self.cli("prune", "--keep", "0") + self.assertEqual(pruned.returncode, 0, pruned.stderr) + self.assertEqual(json.loads(pruned.stdout)["snapshot_count"], 0) + + def test_missing_checkpoint_is_an_error(self): + result = self.cli("restore", "does-not-exist") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertEqual((self.workspace / "config.txt").read_text(), "working") + + def test_missing_executable_is_an_error_and_retains_checkpoint(self): + result = self.cli("run", "--", "definitely-not-a-real-checkpoint-command") + self.assertEqual(result.returncode, 2, result.stderr) + self.assertEqual((self.workspace / "config.txt").read_text(), "working") + self.assertEqual(len(WorkspaceSnapshotter(str(self.workspace)).list_snapshots()), 1) + + def test_negative_retention_does_not_delete_history(self): + self.assertEqual(self.cli("snapshot").returncode, 0) + result = self.cli("prune", "--keep", "-1") + self.assertEqual(result.returncode, 2) + self.assertEqual(len(WorkspaceSnapshotter(str(self.workspace)).list_snapshots()), 1) + + def test_legacy_watcher_is_explicit_not_background_monitor(self): + result = self.cli("run", "--", sys.executable, "-c", "raise SystemExit(3)", + entry="watcher.py") + self.assertEqual(result.returncode, 3, result.stderr) + self.assertIn("restored", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_snapshotter.py b/tests/test_snapshotter.py new file mode 100644 index 0000000..74c95a0 --- /dev/null +++ b/tests/test_snapshotter.py @@ -0,0 +1,141 @@ +"""Core checkpoint, retention, metadata, and pre-publication failure contracts.""" +import json +import os +from pathlib import Path +import stat +import tempfile +import unittest +from unittest.mock import patch + +from snapshot_daemon import SnapshotError, WorkspaceSnapshotter + + +class SnapshotterTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.workspace = self.root / "workspace" + self.workspace.mkdir() + self.snap = WorkspaceSnapshotter(str(self.workspace)) + + def test_empty_checkpoint_restores_empty_workspace(self): + sid = self.snap.create_snapshot("empty") + (self.workspace / "nested").mkdir() + (self.workspace / "nested/file").write_bytes(b"new") + self.assertTrue(self.snap.rollback(sid)) + self.assertEqual(list(self.workspace.iterdir()), []) + + def test_shared_blobs_survive_until_last_reference_is_removed(self): + (self.workspace / "a").write_bytes(b"same") + (self.workspace / "b").write_bytes(b"same") + first = self.snap.create_snapshot("one") + second = self.snap.create_snapshot("two") + self.assertEqual(self.snap.storage_stats()["blob_count"], 1) + self.snap.delete_snapshot(first) + self.assertTrue(self.snap.verify_snapshot(second)["valid"]) + self.assertEqual(self.snap.storage_stats()["blob_count"], 1) + self.snap.delete_snapshot(second) + self.assertEqual(self.snap.storage_stats()["blob_count"], 0) + + def test_retention_keeps_newest_and_reclaims_unused_contents(self): + path = self.workspace / "version" + snapshots = [] + for version in range(4): + path.write_bytes(bytes([version])) + snapshots.append(self.snap.create_snapshot(str(version))) + self.snap.cleanup_old_snapshots(2) + self.assertEqual([s["id"] for s in self.snap.list_snapshots()], snapshots[-2:]) + self.assertEqual(self.snap.storage_stats()["blob_count"], 2) + self.assertEqual(self.snap.get_latest_snapshot(), snapshots[-1]) + + def test_snapshot_ids_do_not_depend_on_clock_resolution(self): + with patch("snapshot_daemon.time.time", return_value=1_700_000_000): + ids = {self.snap.create_snapshot() for _ in range(12)} + self.assertEqual(len(ids), 12) + self.assertEqual(len(self.snap.list_snapshots()), 12) + + def test_failed_manifest_publication_does_not_advertise_snapshot(self): + (self.workspace / "a").write_bytes(b"contents") + with patch.object(self.snap, "_atomic_json", side_effect=OSError("disk full")): + with self.assertRaises(SnapshotError): + self.snap.create_snapshot() + self.assertEqual(self.snap.list_snapshots(), []) + self.assertEqual((self.workspace / "a").read_bytes(), b"contents") + self.snap.cleanup_old_snapshots(0) + self.assertEqual(self.snap.storage_stats()["blob_count"], 0) + + def test_staging_failure_preserves_current_workspace(self): + path = self.workspace / "a" + path.write_bytes(b"before") + sid = self.snap.create_snapshot() + path.write_bytes(b"current") + + def fail(stage, manifest): + stage.mkdir() + (stage / "partial").write_bytes(b"incomplete") + raise OSError("injected staging failure") + + with patch.object(self.snap, "_build_stage", side_effect=fail): + with self.assertRaises(SnapshotError): + self.snap.rollback(sid) + self.assertEqual(path.read_bytes(), b"current") + self.assertEqual(list(self.root.glob(".workspace.restore-*")), []) + self.assertTrue(self.snap.rollback(sid)) + self.assertEqual(path.read_bytes(), b"before") + + def test_regular_file_to_directory_and_back(self): + path = self.workspace / "entry" + path.write_bytes(b"file") + first = self.snap.create_snapshot() + path.unlink() + path.mkdir() + (path / "empty").mkdir() + second = self.snap.create_snapshot() + self.snap.rollback(first) + self.assertEqual(path.read_bytes(), b"file") + self.snap.rollback(second) + self.assertTrue((path / "empty").is_dir()) + + def test_store_format_rejects_legacy_without_changing_it(self): + legacy = self.root / "legacy" + legacy.mkdir() + old = legacy / "snapshots.json" + old.write_text("{}", encoding="utf-8") + with self.assertRaisesRegex(SnapshotError, "legacy"): + WorkspaceSnapshotter(str(self.workspace), str(legacy)) + self.assertEqual(old.read_text(), "{}") + + @unittest.skipIf(os.name == "nt", "POSIX directory permissions are unavailable") + def test_readonly_directories_can_be_replaced_and_cleaned_up(self): + directory = self.workspace / "readonly" + directory.mkdir() + (directory / "file").write_bytes(b"original") + directory.chmod(0o555) + self.addCleanup(lambda: directory.chmod(0o755) if directory.exists() else None) + sid = self.snap.create_snapshot() + self.assertTrue(self.snap.rollback(sid)) + self.assertEqual((directory / "file").read_bytes(), b"original") + self.assertEqual(stat.S_IMODE(directory.stat().st_mode), 0o555) + + @unittest.skipIf(os.name == "nt", "POSIX executable modes are unavailable") + def test_identical_contents_preserve_individual_modes_and_mtimes(self): + executable = self.workspace / "executable" + ordinary = self.workspace / "ordinary" + for path in (executable, ordinary): + path.write_bytes(b"same contents") + executable.chmod(0o755) + ordinary.chmod(0o640) + stamp = 1_700_000_000_123_456_789 + os.utime(executable, ns=(stamp, stamp)) + sid = self.snap.create_snapshot() + executable.chmod(0o600) + ordinary.chmod(0o600) + self.snap.rollback(sid) + self.assertEqual(stat.S_IMODE(executable.stat().st_mode), 0o755) + self.assertEqual(stat.S_IMODE(ordinary.stat().st_mode), 0o640) + self.assertEqual(executable.stat().st_mtime_ns, stamp) + + +if __name__ == "__main__": + unittest.main() diff --git a/watcher.py b/watcher.py index 522dd2c..60679fc 100644 --- a/watcher.py +++ b/watcher.py @@ -1,196 +1,9 @@ -#!/usr/bin/env python3 -""" -File Watcher Daemon - Monitors workspace for agent actions and triggers snapshots. +"""Compatibility CLI. The after-write watcher has been retired. -This daemon watches the workspace directory for file changes and automatically -creates snapshots before major agent tool calls (code edits, file deletions, etc.). +Filesystem notifications cannot implement pre-action checkpoints. Use: +python watcher.py --workspace ./workspace run -- python action.py """ - -import time -import threading -from pathlib import Path -from typing import Callable, Optional -from watchdog.observers import Observer -from watchdog.events import ( - FileSystemEventHandler, - FileModifiedEvent, - FileCreatedEvent, - FileDeletedEvent, - FileMovedEvent, - DirDeletedEvent, - DirMovedEvent -) - -from snapshot_daemon import WorkspaceSnapshotter - - -class AgentActionHandler(FileSystemEventHandler): - """ - Handles file system events and triggers snapshots for agent actions. - - Strategy: - - On any file modification, create a snapshot with a label describing the change - - Debounce rapid changes to avoid excessive snapshots - """ - - def __init__(self, snapshotter: WorkspaceSnapshotter, - debounce_seconds: float = 0.5): - super().__init__() - self.snapshotter = snapshotter - self.debounce_seconds = debounce_seconds - self._last_snapshot_time = 0 - self._lock = threading.Lock() - self._pending_snapshot = False - - def _should_snapshot(self) -> bool: - """Check if we should create a snapshot (debouncing).""" - current_time = time.time() - return current_time - self._last_snapshot_time >= self.debounce_seconds - - def _trigger_snapshot(self, event_type: str, path: str): - """Trigger a snapshot with debouncing.""" - with self._lock: - if not self._should_snapshot(): - self._pending_snapshot = True - return - - self._pending_snapshot = False - self._last_snapshot_time = time.time() - - # Create snapshot in background thread to not block file operations - label = f"{event_type}: {Path(path).name}" - threading.Thread( - target=self._create_snapshot_thread, - args=(label,), - daemon=True - ).start() - - def _create_snapshot_thread(self, label: str): - """Create snapshot in background thread.""" - try: - self.snapshotter.create_snapshot(label) - except Exception as e: - print(f"Snapshot error: {e}") - - def on_modified(self, event): - if isinstance(event, FileModifiedEvent) and not event.is_directory: - print(f"[WATCHER] File modified: {event.src_path}") - self._trigger_snapshot("modify", event.src_path) - - def on_created(self, event): - if isinstance(event, FileCreatedEvent) and not event.is_directory: - print(f"[WATCHER] File created: {event.src_path}") - self._trigger_snapshot("create", event.src_path) - - def on_deleted(self, event): - if isinstance(event, (FileDeletedEvent, DirDeletedEvent)): - print(f"[WATCHER] {'Directory' if event.is_directory else 'File'} deleted: {event.src_path}") - self._trigger_snapshot("delete", event.src_path) - - def on_moved(self, event): - if isinstance(event, (FileMovedEvent, DirMovedEvent)): - print(f"[WATCHER] {'Directory' if event.is_directory else 'File'} moved: {event.src_path} -> {event.dest_path}") - self._trigger_snapshot("move", event.dest_path) - - -class WorkspaceWatcher: - """ - Main watcher class that monitors the workspace and creates snapshots. - """ - - def __init__(self, workspace_path: str = "/workspace"): - self.workspace_path = Path(workspace_path).resolve() - self.snapshotter = WorkspaceSnapshotter(str(self.workspace_path)) - self.observer: Optional[Observer] = None - self.handler: Optional[AgentActionHandler] = None - self._running = False - - def start(self, blocking: bool = False): - """Start watching the workspace.""" - print(f"[WATCHER] Starting workspace watcher on {self.workspace_path}") - - # Create initial snapshot - print("[WATCHER] Creating initial baseline snapshot...") - initial_id = self.snapshotter.create_snapshot("initial_baseline") - print(f"[WATCHER] Initial snapshot: {initial_id}") - - # Setup watcher - self.handler = AgentActionHandler(self.snapshotter) - self.observer = Observer() - self.observer.schedule( - self.handler, - str(self.workspace_path), - recursive=True - ) - - # Ignore snapshot directory - snapshot_path = self.snapshotter.snapshot_dir - print(f"[WATCHER] Ignoring snapshot directory: {snapshot_path}") - - self.observer.start() - self._running = True - - if blocking: - try: - while self._running: - time.sleep(1) - except KeyboardInterrupt: - self.stop() - - def stop(self): - """Stop watching the workspace.""" - print("[WATCHER] Stopping workspace watcher...") - self._running = False - if self.observer: - self.observer.stop() - self.observer.join() - self.observer = None - - def manual_snapshot(self, label: str = "") -> str: - """Manually trigger a snapshot.""" - return self.snapshotter.create_snapshot(label) - - def rollback(self, snapshot_id: Optional[str] = None) -> bool: - """Rollback to a snapshot.""" - if snapshot_id is None: - snapshot_id = self.snapshotter.get_latest_snapshot() - if snapshot_id is None: - print("[WATCHER] No snapshots available for rollback") - return False - return self.snapshotter.rollback(snapshot_id) - - def list_snapshots(self): - """List all snapshots.""" - return self.snapshotter.list_snapshots() - - -def main(): - """Run the watcher daemon.""" - import argparse - - parser = argparse.ArgumentParser(description="Workspace Watcher Daemon") - parser.add_argument("--workspace", default="/workspace", - help="Path to workspace directory") - parser.add_argument("--daemon", action="store_true", - help="Run as daemon (blocking)") - - args = parser.parse_args() - - watcher = WorkspaceWatcher(args.workspace) - - if args.daemon: - watcher.start(blocking=True) - else: - # Just initialize and show status - watcher.start(blocking=False) - print("\n[WATCHER] Watcher initialized. Run with --daemon to start monitoring.") - print(f"\nAvailable commands:") - print(f" python watcher.py --daemon # Start monitoring") - print(f" python snapshot_daemon.py --action snapshot # Manual snapshot") - print(f" python snapshot_daemon.py --action rollback # Rollback to latest") - print(f" python snapshot_daemon.py --action list # List snapshots") - watcher.stop() - +from workspace_cli import main if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/workspace_cli.py b/workspace_cli.py new file mode 100644 index 0000000..0b2f361 --- /dev/null +++ b/workspace_cli.py @@ -0,0 +1,124 @@ +"""Explicit checkpoints around foreground commands in an owned workspace.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import stat +import subprocess +import sys +from typing import Sequence + +from snapshot_daemon import SnapshotError, WorkspaceSnapshotter + + +def run_checkpointed(snapshotter: WorkspaceSnapshotter, command: Sequence[str], + label: str = "", *, quiet: bool = False) -> dict: + """Checkpoint, run, and restore on failure; preserve the command exit code. + + The command must not leave background writers behind. The store lock only + serializes cooperating clients. stdout/stderr remain attached to the caller. + """ + if not command: + raise ValueError("A command is required") + with snapshotter.transaction(): + checkpoint = snapshotter.create_snapshot(label or "before: " + " ".join(command)) + if not quiet: + print(f"Checkpoint: {checkpoint}", file=sys.stderr, flush=True) + completed = subprocess.run(list(command), cwd=snapshotter.workspace, check=False) + restored = completed.returncode != 0 + if restored: + snapshotter.rollback(checkpoint) + if not quiet: + print(f"Command failed ({completed.returncode}); restored {checkpoint}", + file=sys.stderr, flush=True) + return {"snapshot_id": checkpoint, "returncode": completed.returncode, + "restored": restored} + + +def _create_workspace(path: Path) -> None: + # Check ancestors before mkdir; resolve() would conceal links. + path = Path(os.path.abspath(path)) + for candidate in (path, *path.parents): + try: + metadata = candidate.lstat() + except FileNotFoundError: + continue + if stat.S_ISLNK(metadata.st_mode) or ( + getattr(metadata, "st_file_attributes", 0) + & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) + ): + raise SnapshotError(f"Symlink/reparse workspace path is unsupported: {candidate}") + path.mkdir(parents=True, exist_ok=True) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Verified checkpoints for agent workspaces") + parser.add_argument("--workspace", default="./workspace", help="Owned workspace directory") + parser.add_argument("--snapshot-dir", help="Store outside workspace (default: PATH.snapshots)") + sub = parser.add_subparsers(dest="action", required=True) + sub.add_parser("init", help="Create the workspace and an initial checkpoint") + snapshot = sub.add_parser("snapshot", help="Checkpoint an idle workspace") + snapshot.add_argument("--label", default="") + sub.add_parser("list", help="List checkpoints as JSON") + restore = sub.add_parser("restore", help="Restore a checkpoint; requires no active writers") + restore.add_argument("snapshot_id") + verify = sub.add_parser("verify", help="Validate a checkpoint and its stored contents") + verify.add_argument("snapshot_id") + sub.add_parser("stats", help="Show content-store usage") + prune = sub.add_parser("prune", help="Keep newest N checkpoints and collect unused data") + prune.add_argument("--keep", type=int, required=True) + run = sub.add_parser("run", help="Checkpoint, run, restore on nonzero exit") + run.add_argument("--label", default="") + run.add_argument("command", nargs=argparse.REMAINDER, + help="Use -- before the executable and its arguments") + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + try: + if args.action == "init": + _create_workspace(Path(args.workspace)) + if args.action == "prune" and args.keep < 0: + parser.error("--keep must be nonnegative") + command = getattr(args, "command", []) + if command and command[0] == "--": + command = command[1:] + if args.action == "run" and not command: + parser.error("run requires a command after --") + snap = WorkspaceSnapshotter(args.workspace, args.snapshot_dir) + if args.action == "init": + result = {"snapshot_id": snap.create_snapshot("initial_baseline")} + elif args.action == "snapshot": + result = {"snapshot_id": snap.create_snapshot(args.label)} + elif args.action == "list": + result = snap.list_snapshots() + elif args.action == "restore": + snap.rollback(args.snapshot_id) + result = {"restored": args.snapshot_id} + elif args.action == "verify": + result = snap.verify_snapshot(args.snapshot_id) + elif args.action == "stats": + result = snap.storage_stats() + elif args.action == "prune": + snap.cleanup_old_snapshots(args.keep) + result = snap.storage_stats() + else: + result = run_checkpointed(snap, command, args.label) + code = result["returncode"] + return code if code >= 0 else 128 - code + print(json.dumps(result, indent=2)) + return 0 + except (SnapshotError, OSError, ValueError) as exc: + print(f"Error: {exc}", file=sys.stderr) + return 2 + except KeyboardInterrupt: + print("Interrupted. Checkpoint retained; stop all writers before restoring.", file=sys.stderr) + return 130 + + +if __name__ == "__main__": + raise SystemExit(main()) From 03c9fc370b279e7d8cba80a4fca083a376cd2d7d Mon Sep 17 00:00:00 2001 From: Sarvesh Tamse Date: Sat, 3 Oct 2026 18:49:44 +0530 Subject: [PATCH 2/2] Normalize Windows path aliases and test store identity --- .github/workflows/tests.yml | 4 ++-- docs/VALIDATION.md | 10 ++++++---- snapshot_daemon.py | 7 +++++++ tests/test_snapshotter.py | 13 +++++++++++++ 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e5b1c0f..d608a71 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,8 +11,8 @@ jobs: python: ['3.10', '3.13'] runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 with: python-version: ${{ matrix.python }} - run: python -m pip install . diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 0b4fe7c..e82ff48 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,4 +1,4 @@ -# Observed validation — 2026-10-03 +# Observed validation — 2026-10-03 These are reproducible local observations, not a cloud-service comparison or an under-50-ms guarantee. The Windows and Linux benchmark invocations ran sequentially @@ -6,12 +6,14 @@ on one host. Neither run controlled other host activity or flushed OS caches. ## Correctness -- Windows 11 / CPython 3.13.2: 40 tests, 37 passed, 3 POSIX-only skips. -- Ubuntu on WSL2 / CPython 3.14.4: all 40 tests passed. +- Windows 11 / CPython 3.13.2: 41 tests, 38 passed, 3 POSIX-only skips. +- Ubuntu on WSL2 / CPython 3.14.4: 41 tests, 40 passed, 1 Windows-only skip. - Tests create their data in temporary directories (NTFS on Windows, tmpfs on WSL). - Tests cover actual process death between directory renames, multi-process checkpoint publication, corrupted/missing objects, symlink escapes, metadata, read-only directories, retention, and command exit codes. +- The Windows CI runner exposed equivalent short/full path spellings; a regression + test now verifies canonical store identity for Windows path aliases. - The demo independently verifies the restored fixture and reruns its checks. - A Python wheel builds successfully. The CI configuration also targets Python 3.10 and 3.13 on GitHub-hosted Linux and Windows; the local runs above do not @@ -42,7 +44,7 @@ performance. Do not use the difference between rows as a Windows/Linux compariso Five samples are insufficient to characterize production tail latency. Raw samples and context: -[Windows](results/windows-ntfs.json) · [Linux](results/linux-wsl-tmpfs.json). +[Windows](results/windows-ntfs.json) · [Linux](results/linux-wsl-tmpfs.json). The Windows temporary-directory username is redacted; measurement values are not. ## Reproduce diff --git a/snapshot_daemon.py b/snapshot_daemon.py index 7a1bfd8..67251c0 100644 --- a/snapshot_daemon.py +++ b/snapshot_daemon.py @@ -103,6 +103,13 @@ def __init__(self, workspace_path: str, snapshot_dir: str | None = None): self._thread_lock = threading.RLock() self._depth = 0 try: + # Reject links before canonicalization so resolve() cannot conceal + # an unsupported ancestor. Then normalize Windows short names and + # path spelling so equivalent clients share the same store identity. + self._check_locations() + self.workspace = self.workspace.resolve() + self.snapshot_dir = (self.snapshot_dir.resolve() if snapshot_dir is not None + else Path(str(self.workspace) + ".snapshots")) self._check_locations() if not self.workspace.exists() and not (self.snapshot_dir / "rollback.json").is_file(): raise SnapshotError(f"Workspace directory does not exist: {self.workspace}") diff --git a/tests/test_snapshotter.py b/tests/test_snapshotter.py index 74c95a0..80a28d5 100644 --- a/tests/test_snapshotter.py +++ b/tests/test_snapshotter.py @@ -106,6 +106,19 @@ def test_store_format_rejects_legacy_without_changing_it(self): WorkspaceSnapshotter(str(self.workspace), str(legacy)) self.assertEqual(old.read_text(), "{}") + @unittest.skipUnless(os.name == "nt", "Windows path aliases are unavailable") + def test_equivalent_windows_path_spelling_reopens_same_store(self): + (self.workspace / "a").write_bytes(b"original") + sid = self.snap.create_snapshot() + other = WorkspaceSnapshotter(str(self.workspace).upper(), str(self.snap.snapshot_dir).upper()) + self.assertTrue(other.verify_snapshot(sid)["valid"]) + import ctypes + buffer = ctypes.create_unicode_buffer(32768) + length = ctypes.windll.kernel32.GetShortPathNameW(str(self.workspace), buffer, len(buffer)) + if length and length < len(buffer): + alias = WorkspaceSnapshotter(buffer.value) + self.assertTrue(alias.verify_snapshot(sid)["valid"]) + @unittest.skipIf(os.name == "nt", "POSIX directory permissions are unavailable") def test_readonly_directories_can_be_replaced_and_cleaned_up(self): directory = self.workspace / "readonly"