The user wants to build a monorepo remote cache with specific requirements:
Monorepo: It needs to handle multiple projects/packages within a single repository.
Remote Cache: It needs to store build artifacts remotely to speed up builds across different machines/CI runs.
Hermetic Toolchains: The build process must be isolated from the host system's environment (tools, libraries) to ensure reproducibility.
Sandboxing: The build execution needs to happen in a restricted environment (filesystem, network) to prevent side effects and enforce hermeticity.
This is a significant undertaking, essentially building a mini-Bazel or a custom build system backend. I need to provide a conceptual architecture and a concrete implementation strategy.
High-Level Architecture:
Client (The CLI/Runner):
Calculates the hash of inputs (source files, dependencies, environment configuration).
Checks the remote cache.
If miss: Executes the build in a sandbox using a hermetic toolchain.
Uploads artifacts to the cache.
If hit: Downloads artifacts.
Server (The Cache):
Stores blobs (content-addressable storage - CAS).
Stores action results (metadata mapping input hashes to output hashes).
Sandboxing/Hermeticity Layer:
Docker, Firecracker, or strict OS-level namespaces (Linux namespaces/chroot).
Toolchain management (downloading specific compiler versions).
Key Components to Design:
Content-Addressable Storage (CAS):
This is the backbone. Files are stored by their SHA-256 hash.
Prevents duplication.
Concept: Put(blob) -> hash, Get(hash) -> blob.
Action Graph & Execution:
Define a "Task" or "Action".
Inputs: List of file hashes.
Command: The shell command to run.
Outputs: Expected file paths to capture.
Hermeticity (The "Hard" Part):
We cannot use /usr/bin/gcc because it might differ on the user's laptop vs. CI.
We need a mechanism to declare toolchains (e.g., a JSON file specifying URLs to download Node.js/GCC).
These toolchains are mounted into the sandbox at a specific path (e.g., /opt/tools).
Sandboxing:
To ensure hermeticity, we must prevent network access (unless allowed) and access to host files.
Simple implementation: Docker containers.
Advanced implementation:bubblewrap or nsjail (Linux specific).
Implementation Plan (Python + S3/Local Storage + Docker):
Why Python? Easy to read, good libraries.
Why S3/Local? Standard storage backends.
Why Docker? Easiest way to demonstrate hermeticity and sandboxing without writing C code for Linux namespaces.
Drafting the Code Structure:
cache_server.py: A simple Flask/FastAPI server implementing a REST API for CAS.
client.py:
hash_inputs(): Walk directory, hash files.
query_cache(): Ask server.
executor.py: If miss, run Docker container.
upload(): Send results to server.
Refining the "Hermetic Toolchain" Aspect:
I need to show how the toolchain is hermetic.
Assume a toolchain.json exists. It describes an image (e.g., docker pull gcc:12) or a tarball to download.
The client mounts the source code read-only into the container.
The container has only the declared tools.
Refining the "Sandboxing" Aspect:
The container runs without network (mostly).
The container runs as a non-root user (optional but good).
Let's simplify the scope for a single prompt response:
I will build a Remote Build Execution (RBE) style system.
Protocol: Simple REST (mimicking REAPI concepts but simplified).
Storage: Local filesystem (simulating S3/GCS) for the server.
Isolation: Docker (for sandboxing + hermeticity).
Step-by-Step Implementation Guide:
The Protocol (CAS & Action Cache):
POST /cas/<hash>: Upload blob.
GET /cas/<hash>: Download blob.
GET /action/<hash>: Check if build command ran before.
POST /action/<hash>: Store result metadata.
The Toolchain Definition:
A YAML file defining the Docker image and the command path.
The Client Logic:
Compute input hash (Source + Toolchain ID + Command).
Check Action Cache.
If HIT: Download outputs from CAS.
If MISS:
Pack inputs into tarball.
Run Docker container (mount tarball, run command, extract outputs).
Upload outputs to CAS.
Update Action Cache.
Writing the Code (Mental Draft):
Server: Flask. 100 lines.
Client: Python script. 150 lines.
Sandbox: Docker SDK for Python.
Self-Correction/Edge Cases:
Large files: Streaming is better, but for a prototype, loading into memory is easier to code. I'll stick to simple logic but mention streaming.
OS Compatibility: Docker solves the "it works on my machine" issue, but the client script itself needs to run Python. I'll assume the host has Python and Docker.
Structuring the Output:
Architecture Overview: Explain the CAS, Action Cache, and Executor.
Prerequisites: Docker, Python.
Step 1: The Cache Server (Storage Layer).
Step 2: The Client/Worker (Compute Layer).
Step 3: Defining Hermetic Toolchains.
Step 4: Running the Sandbox.
Example Usage.
Let's refine the "Hermetic Toolchain" part.
Ideally, the toolchain is identified by a hash. If I change the Docker image tag, the hash changes. This invalidates the cache. Perfect.
Let's write the response.
Building a production-grade remote cache with hermetic build capabilities is a complex engineering task. Below is a complete, simplified architecture and implementation guide for a system we'll call "MonoCache".
This solution consists of three parts:
The Server: A high-performance content-addressable storage (CAS) and action cache.
The Client: A local CLI that calculates hashes, checks the cache, and triggers builds.
The Sandbox: A Docker-based execution environment to ensure hermeticity (reproducibility).
System Architecture
Content Addressable Storage (CAS): Files are stored by their SHA-256 hash.
Action Cache: Maps a command's inputs + environment hash to the output artifact hash.
Hermeticity: achieved by running all commands inside a specific Docker container with no network access.
Sandboxing: The Docker container ensures the process cannot write to arbitrary locations on the host.
This server implements a simplified version of the standard Remote Execution API (REAPI). It exposes endpoints to upload blobs, check for existence, and store action results.
Create server.py:
python
import os
import hashlib
import json
from fastapi import FastAPI, UploadFile, File, HTTPException, Response
from fastapi.responses import FileResponse
from pathlib import Path
app = FastAPI()
# Configuration
STORAGE_DIR = Path("./remote_cache")
CAS_DIR = STORAGE_DIR / "cas" # Stores raw files (blobs)
AC_DIR = STORAGE_DIR / "action_cache" Stores metadata (Action Results)
# Ensure directories exist
CAS_DIR.mkdir(parents=True, exist_ok=True)
AC_DIR.mkdir(parents=True, exist_ok=True)
# --- Content Addressable Storage (CAS) ---
def get_cas_path(hash_key: str) -> Path:
# Store files in subdirs to avoid too many files in one dir
return CAS_DIR / hash_key[:2] / hash_key
@app.post("/cas/upload")
async def upload_blob(file: UploadFile = File(...)):
"""Uploads a file. Content-addressable by hash provided in header."""
# In a real system, you'd stream this and verify the hash as it comes in.
# For simplicity, we calculate hash here or trust the filename/header.
# Let's assume the client sends the hash in the filename or header.
# Calculate hash on the fly
sha256 = hashlib.sha256()
contents = await file.read()
sha256.update(contents)
hash_key = sha256.hexdigest()
file_path = get_cas_path(hash_key)
if not file_path.exists():
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "wb") as f:
f.write(contents)
return {"hash": hash_key, "status": "uploaded"}
@app.head("/cas/{hash_key}")
async def check_blob(hash_key: str):
"""Check if blob exists (Cache Hit)."""
if get_cas_path(hash_key).exists():
return Response(status_code=200)
return Response(status_code=404)
@app.get("/cas/{hash_key}")
async def download_blob(hash_key: str):
"""Download a blob."""
file_path = get_cas_path(hash_key)
if not file_path.exists():
raise HTTPException(status_code=404, detail="Blob not found")
return FileResponse(file_path)
# --- Action Cache ---
@app.post("/ac/store")
async def store_action_result(data: dict):
"""
Stores the mapping: ActionHash -> OutputFileHashes
"""
action_hash = data.get("action_hash")
result = data.get("result") # e.g., {"stdout": "...", "outputs": {"out.bin": "hash123"}}
ac_path = AC_DIR / f"{action_hash}.json"
with open(ac_path, "w") as f:
json.dump(result, f)
return {"status": "stored"}
@app.get("/ac/{action_hash}")
async def get_action_result(action_hash: str):
"""Retrieves the result of a previously run action."""
ac_path = AC_DIR / f"{action_hash}.json"
if not ac_path.exists():
raise HTTPException(status_code=404, detail="Action not cached")
with open(ac_path, "r") as f:
return json.load(f)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8080)
Delete the local output to simulate a clean machine:
bash
rm program
python ../client.py build
Output:
Client calculates hashes (Action Hash is identical).
Client checks Server (200 OK).
Client downloads program binary directly.
Docker is never executed.
Key Concepts Explained
1. Hermetic Toolchains
In a non-hermetic build, you use gcc installed on your laptop. If you update your OS, gcc versions change, and the build might break or produce different binaries.
In this system, the toolchain is defined strictly by the Docker Image (gcc:11). The "Environment Hash" in client.py is derived from this image name. If you change the image to gcc:12, the hash changes, the cache misses automatically, and it forces a rebuild with the new toolchain.
2. Sandboxing
The client.py executes Docker with --network none.
Why? This prevents your build from fetching dependencies (like pip install or curl) dynamically during the build.
Benefit: If a build works today, it will work in 5 years, because it cannot reach out to the internet to grab a dependency that might disappear or change. All inputs must be declared and provided locally.
3. Remote Caching Strategy
We used a Separation of Concerns:
CAS (Content Addressable Storage): Stores the actual bits. Deduplicates files globally (if two projects have the same main.c, it is stored only once).