Storage for AI agents: files, workspaces, and recovery
An AI agent storage guide from temporary files and Kubernetes volumes to tenant authorization, signed downloads, memory poisoning and recovery.
Sources & version details
In this article
Follow a report from upload to recovery
A customer uploads 200 MiB of documents. An agent extracts text, joins it against a 1 GiB catalog, and produces a 20 MiB report with source references. The worker disappears after uploading the report but before the application records completion. A replacement must recover from durable state without exposing another tenant’s files or publishing a second report. Use this example to decide where each byte belongs, estimate capacity, trace a write through the OS, and design a recoverable publication protocol.
The prerequisites are a process and its file descriptors, a filesystem mount, and a database transaction. A file descriptor is a process-local handle to an open object. A mount attaches a filesystem to a path in the process’s namespace. A transaction defines which updates become visible or fail together inside one system. A lease provides time-limited ownership. A fencing token is a generation which the resource also checks before accepting a write. These concepts let an agent manipulate data through tools without giving the model direct access to host storage.
Classify bytes by lifetime and authority
Start with who may read or write each class, which component owns it, and what happens if the machine disappears. With transient computation, keep only the necessary inputs and reports durable. A multi-day coding agent may need a persistent checkout, but that introduces retention, stale dependency and concurrent-write questions. For a small analysis over already durable data, stream the documents and avoid materializing an entire shared workspace.
| Class | Typical backing | Authority and lifetime |
|---|---|---|
| Weights, optimizer and training state | CPU/GPU memory while running, local NVMe cache, immutable object shards | Training version and checkpoint manifest control recovery |
| KV cache, activations and temporary tensors | GPU RAM, optionally CPU or disk offload | Inference or training runtime owns mutable state; usually rebuildable |
| Uploaded inputs and canonical datasets | Versioned object storage or governed data lake | Tenant, object version and checksum govern read access |
| Scratch and intermediate files | Private process directory, local SSD, tmpfs, Kubernetes emptyDir | Owned by one run or attempt; expiration is expected |
| Workspace or shared mounts | POSIX volume, block-backed filesystem, network file service | Snapshot, access mode and reclaim policy define survival |
| Run state, leases, receipts and user memory | Transactional database; versioned object storage for large bodies | Different records may have different retention and deletion rules |
| Retrieval indexes and embedding caches | Index engine or derived files | Rebuild from authorized sources, model and index versions; propagate deletions |
| Published outputs and evidence | Immutable objects plus a durable result pointer | Visible only after a committed manifest and an authorized download |
Logical paths inside the sandbox can be /work/input for read-only snapshots, /work/scratch for writable intermediates, and /work/out for unpublished candidates. A path in a tool response refers to that tool’s environment, so a downloader needs either an authorized handle from the same environment or a published artifact identifier. Agent memory means selected records used in future runs. It is separately governed from scratch, conversation history, vector indexes and model weights.
What actually happens when a file is written
On Linux a pathname lookup resolves directory entries and symbolic links inside a mount namespace. The inode carries filesystem identity and metadata, while the descriptor continues to refer to the opened object if its name changes. Ordinary buffered writes may dirty the page cache and return before storage acknowledges persistence. A successful close or application-level flush alone therefore says little about power-loss recovery. Filesystems journal or otherwise order different kinds of updates. Pillai et al. documented why crash-consistent applications must reason about the persistence properties of actual filesystems and configurations.
For a trusted single filesystem, create a temporary file in the destination directory, write and validate it, call fsync on the file, atomically replace the target with rename or os.replace, then synchronize the containing directory. Rename changes name visibility atomically on the same filesystem. Across mounts, it generally fails rather than implementing an atomic move. On Linux a directory sync is needed for the rename’s directory entry to survive a crash on filesystems that support this protocol. A failed sync after rename leaves an uncertain outcome and requires inspection. Remote mounts, FUSE adapters, weakened device flush guarantees and transactional storage require their own documented contracts.
A container image commonly has read-only lower layers with a writable overlay. Modifying an existing file may copy it into the upper layer. Putting large spill or checkpoints there can unexpectedly tax the node and tie survival to the container. A mount at the scratch path gives a deliberate resource and lifecycle boundary. In a browser, the origin private file system (OPFS) offers origin-scoped files subject to browser quotas and clearing or eviction behavior. It can hold a local cache; users still need an explicit durable export or synchronization pathway if recovery matters.
Create, budget and delete temporary data
Use a fresh private directory per attempt, owned by the service identity with restrictive permissions and a controlled parent that the agent cannot modify. Use TemporaryDirectory or mkdtemp rather than choosing a name and creating it later. Randomness helps avoid name collisions. Kernel-enforced identity and directory scope supply the access boundary. /tmp is a convention, not a durability promise. A sticky shared directory limits some deletion operations and does not privatize readable files. An unlinked file can continue occupying space while descriptors remain open. A crash can leave named files behind even when ordinary exits clean up.
Disk-backed scratch is suitable for larger, rebuildable spills. tmpfs is memory-backed and can consume memory allowance; on Linux it may also use swap where configured, so a RAM-backed mount alone does not guarantee data never reaches disk. Reserve headroom and bound both bytes and file count, since millions of tiny files can exhaust inodes with free bytes left. On Kubernetes, a disk-backed emptyDir normally survives a container restart within the same Pod and disappears when that Pod is removed. The memory-backed variant consumes memory, not disk ephemeral-storage quota. Set resource requests and limits for writable layers, logs and local ephemeral storage, and decide how eviction or ENOSPC returns a retryable result. For a cluster-wide recovery guarantee, write the needed state to a store with the required failure-domain guarantees.
Peak scratch is simultaneous live data, including overlap during transforms. Here the 200 MiB input, 600 MiB decoded text, 1 GiB spill and 20 MiB candidate can coexist. That is 1,844 MiB, about 1.80 GiB. A 25% reserve makes the budget 2,305 MiB per run. Six concurrent attempts need up to 13,830 MiB, about 13.51 GiB, for this workload alone. Set the concurrency limit against guaranteed usable capacity. Stream and partition inputs to reduce overlap. A janitor should use run state, lease generation and age to exclude live attempts, rather than deleting arbitrary files based on age alone. Track deletion from replicas, versions, backups and derived indexes separately. TTL makes data eligible for deletion; the system still needs evidence that deletion completed.
Match the storage interface to the data path
Block storage presents addressable blocks; a filesystem or database supplies the layout, recovery and coordination. A local NVMe drive offers low-latency random I/O but can share the host’s failure domain. A Kubernetes PVC requests a volume through a storage class. Access modes, topology, attachment, filesystem semantics, snapshots and reclaim policy all affect whether a worker can resume elsewhere. A network filesystem is useful for shared POSIX-like access. Validate the mount's actual locking, rename and cache behavior before sharing a mutable database or using it as a coordination primitive.
Object storage suits large, immutable inputs and outputs read by key or range. Prefixes organize keys. They have different semantics from POSIX directories. Design around per-object APIs rather than assuming an atomic rename or transaction across several keys. Amazon S3 documents strong read-after-write consistency, conditional writes and integrity checks. These do not couple a database transaction to a blob upload. Check provider, API and configuration where semantics matter. An ETag used as a version precondition need not be a content hash. Use the provider's supported checksum or compute and verify a digest independently. Bound multipart uploads and expire incomplete uploads.
For the catalog, stream or scan only required Parquet partitions and row groups, keeping row IDs and the schema version. Column projection avoids reading unused data. Predicate pushdown can skip row groups when statistics justify pruning. A hash join, sort or aggregation can spill if its working set exceeds memory. Set the engine's spill directory, quotas and concurrency and measure actual scratch high-water marks. SQLite WAL is practical for same-host transactional metadata when its constraints fit. Keep the database and WAL together, use a supported backup mechanism, and use a remote transactional database when independent workers need shared state. A vector index accelerates retrieval but is a derived representation. Retain canonical source controls and check authorization during retrieval, even if the index is fast.
For training, stage compressed shards near workers, prefetch only bounded batches, and track accelerator idle time alongside storage throughput. Checkpoint all necessary shards, step, model and optimizer state, and any required progress or random-state information. Publish a checkpoint manifest only after all required shards are available and verified. Resharding support, such as in PyTorch Distributed Checkpoint, is distinct from a storage-layer guarantee. In inference, a warm weights cache or KV cache can save loading or recomputation. Match model, tokenizer, configuration and tenant access before reusing cached state. GPU RAM holds live tensors and has its own independent capacity budget.
Architecture for a result that survives worker loss
In this reference design, the orchestrator receives an authenticated tenant and immutable input references. It assigns a run ID and attempts a lease transaction. Inside an isolated worker, tools get narrowly scoped handles. They mount authorized inputs read-only, stream through scratch, and produce a bounded candidate. A separate publisher, outside the worker’s mutation boundary, verifies size, schema, digest and access before uploading or adopting an immutable blob. The state store atomically checks operation ID, tenant, policy epoch, active lease generation and run status when it records the result pointer. A downloader rechecks current permissions before streaming that object. The public result exists when the pointer commits.
An upload without a pointer produces an orphan, not a published result. A retry can reuse verified content for the same tenant. The identity of the work should bind the operation ID to fixed input versions and expected output type. If a committed reply is lost, look up its receipt before repeating a side effect. A valid retry returns the same receipt. An expired worker cannot publish after another attempt acquired a newer generation. Cancellation and publication race at the metadata transaction boundary: if cancellation wins, late candidates remain unpublished; if publication wins, revocation or supersession is a separate operation. Timeouts can be ambiguous, so consult the durable record instead of assuming rollback. For multi-file artifacts, list immutable component IDs and checksums in a versioned manifest and atomically move the application’s pointer, keeping older versions only as retention permits.
The two stores have separate failure domains. Audit records should distinguish attempt, authorization decision, uploaded object, committed result and observed download. Minimize payloads and credentials in logs. A repair process may expire unreferenced candidates after a grace period, retry uploads under a new lease, and reconcile pointer/object mismatches. Rollback repoints to a verified authorized version when the product allows it. It cannot undo an already disclosed download.
Identify who can read, write, publish, and restore
Use the document-report example to draw the trust boundaries. A PDF and its extracted text are untrusted inputs. The authenticated request, the tenant’s ACL, the run lease, and the retention policy come from the control plane. The worker can read the input snapshot and write scratch. A separate publisher can submit a validated report. A download broker decides whether the current caller may open the committed report. A backup operator needs a distinct role with a separate audit trail. Each handoff changes which identity is allowed to do what.
| Identity | Allowed operation | Enforced at |
|---|---|---|
| Requesting user | Start a run with input versions they can read | Application API and source authorization |
| One execution attempt | Read the authorized manifest and write to its scratch or staging prefix | Sandbox mount and scoped storage policy |
| Publisher | Check candidate integrity and commit one result pointer for the active run | Publication service and transaction |
| Download recipient | Read one committed artifact under current policy | Download broker or narrowly scoped signed link |
| Restore operator | Rehydrate into a fenced environment and apply current policy before release | Recovery control plane, independent of worker credentials |
Derive tenant, subject and role from verified identity, then bind each permit to the run, operation, immutable object/version, policy revision and expiry. The worker supplies a proposed operation. The service derives the authority and checks it where the bytes are read or written. Keep broad storage and signing credentials outside the sandbox. A worker with upload rights cannot infer permission to list a bucket, publish an object, or mint a user download. If using database row-level security, test with the actual service role and disable unnecessary bypass privileges. PostgreSQL's superusers and roles with BYPASSRLS bypass these policies, and owners normally bypass them unless forced to follow them.
Decide when permissions must be fresh. A manifest records what a run was allowed to see when it started, and current policy governs later reads, writes, and publication. The example uses a per-tenant policy revision. Updates persist the new revision independently of worker leases and invalidate derived access state. For a policy decision and a metadata commit to be atomic, their revision fence must be checked in the same transactional authority. A check against a remote policy service followed by a write to a separate database leaves a race. Treat policy timeouts as denial for sensitive reads, exports and publication, and hold the work for an explicitly governed retry.
Locate the weak points along the file lifecycle
| Boundary | How it fails | Where to enforce the invariant |
|---|---|---|
| Upload and quarantine | Unverified file type, archives that exhaust resources, vulnerable parser; text that tries to direct the Agent | Accept staging only; verify size, type and checksums; parse in a low-privilege process with resource ceilings; release only a versioned manifest |
| Path resolution and temporary files | Symlink or archive entry crosses the workspace boundary; old bytes survive worker cleanup | Server-owned handles, constrained opens under a trusted directory, per-attempt scratch, quotas and teardown |
| Mount, token and network | A legitimate tool can read a mounted secret or send a file to an unauthorized destination | Read-only input mounts, writable scratch only, no ambient credentials, egress and connector policy checked at the destination boundary |
| Metadata and object versions | Application trusts a model-supplied tenant or later loads a file version different from the approved one | Authorized tenant and version in every lookup, scoped roles, immutable manifests, checks at both source read and publish |
| Output and download | Unpublished staging file becomes reachable; copied signed URL keeps granting access | Separate validator/publisher; private staging; authorize at download; narrow key, verb and expiry when signing |
| Memory, cache and index | Text becomes a standing instruction; cached access persists after revocation; a derived chunk leaks across tenants | Separate observations from trusted policy; attach source/version, visibility, expiry and trust label; authorize before loading candidate content into the model |
| Logs and support exports | URLs, tokens, excerpts and filenames appear in traces, dumps and debugging bundles | Record allowed fields only; sanitize before export; protect separate audience and retention policy; audit support access |
| Backup, snapshot and restore | Old jobs or ACLs come back; copied volumes retain data beyond the workspace lifetime | Recover offline; replay revocation and deletion records before serving; inventory every replica, version and retained backup |
| Resource and availability limits | Byte, inode, object, decompression, upload-part or throughput ceilings are exhausted | Streaming caps per attempt and tenant, reject before work, cancellation and bounded retries, separately governed orphan collection |
The first priorities depend on the workload. For a customer document Agent, start with cross-tenant reads and overly broad worker credentials, then export and link delivery, then memory and restore paths that preserve rejected or revoked data. For an Agent receiving public archives, move parser containment and quotas into the first group. The illustrative table is a review model. It supplies no occurrence rates or product rankings.
Set the isolation boundary for the code that will actually run. A private directory and non-root user reduce accidental exposure. Namespace isolation, a read-only root, capability restrictions and a syscall policy reduce the container's reach, while containers still share a kernel. Choose a separate sandbox or stronger hypervisor boundary when tenants run untrusted arbitrary code. Treat host mounts, container engine sockets, default service tokens, shared writable volumes and network connectors as separately privileged interfaces. A microVM does not validate file contents or decide whether a tool is allowed to export a report.
At ingress, a scanner cannot decide whether extracted text has instruction authority. Keep the raw upload quarantined, extract under constrained privileges, and attach source and trust metadata to accepted content. A document may support a factual answer while the tool controller still rejects any request embedded inside it to expand access or change routing. Use a separate memory-write policy. In the running example, a statement about a customer preference can be a time-limited, reviewed observation with a source. It cannot become an authorization rule or shared instruction merely because the model put it in a summary.
Chen et al. studied how compromised persistent memory or knowledge bases affect later agent behavior in AgentPoison, published at NeurIPS 2024. The result is evidence under the tested systems and tasks. The defensive decision fixture below illustrates where to enforce trust labels and review.
On the read path, apply the authorization scope before retrieval where possible and recheck candidate IDs with the authoritative ACL before reading content. Tenant prefixes or namespaces narrow the search space. Shared embeddings, caches and indices also need identity-aware partitioning and invalidation. Hashes check byte identity. A digest, score or sanitized text does not carry the access rights or authority of its source. On the output path, enforce rules on generated reports and on data leaving through connectors, logs, callbacks and debugging exports.
Validate the consumer of each stored object as well as the uploader. Serve untrusted HTML and SVG as downloads or preview them under an isolated origin and a restrictive browser policy that keeps application cookies and credentials outside the preview. Model checkpoints and tool bundles are another boundary. Verify provenance and an approved digest before loading. PyTorch warns that torch.load uses an unpickler and should only read trusted data. Prefer restricted formats and load in a disposable environment when processing externally supplied assets. A valid format still needs memory and disk quotas.
Classify originals, staging, outputs and logs independently. Apply transport protection and encryption at rest according to each data class, with key-use rights separate from storage administration where needed. A worker authorized to decrypt can still copy readable bytes. Decide where plaintext may appear before enabling swap, core dumps, persistent workspace snapshots or third-party diagnostics, and protect those locations as their own stores.
Control revocation, deletion, and restore
A signed S3 URL is a bearer grant constrained by the signer, operation, key and validity. Treat it as a secret. A direct download service does not consult an application's separate ACL for every request unless it is integrated to do so. For sensitive data, use a private broker that checks current rights when opening the stream. Prefer a small expiry for links when direct object delivery is acceptable, keep them out of logs and URLs passed to downstream applications, and test the effect of credential invalidation and provider-side policies. A stream already accepted may continue. Read-time denial cannot recall bytes a recipient already received.
In the example, suppose a tenant revokes access at t = 0. A link valid for 300 s had been issued 30 s earlier. A new direct download may still start for up to 270 s if no provider-side restriction shortens the window. A broker that reads from one permission cache with a 30 s maximum age and no additional propagation delay limits that stale window to at most 30 s. An authoritative lookup for each new request removes that cache component, with availability and latency trade-offs. Write separate service objectives for denying new reads, interrupting in-flight work, and purging stored copies. In production, include replication and notification latency, clock skew and any additional caches when measuring the bound.
Record a deletion as an authoritative tombstone before asynchronous cleanup. The example's source PDF can have extracted text, an embedding, a summary, a cached result, a report referencing it, and snapshot copies. Maintain a dependency inventory keyed by tenant and immutable input version. Removing the current object name can leave prior versions in a versioned bucket. Abandoned multipart uploads have separate cleanup. Legal holds or contractual retention may prohibit early physical purge. Track logical denial, derived-state purge and backup expiry separately, with receipts and exceptions. NIST SP 800-88 Rev. 2 supplies sanitization guidance; neither ordinary file removal nor key deletion alone proves all copies are gone.
Recover in stages. Restore the data into an isolated target, apply current ACLs and tombstones before making anything queryable, rebuild only authorized derived data, and release through the same export broker. Do not replay external side effects from restored queues without checking their operation IDs and current policy. For operations, monitor denied cross-tenant requests, grants still usable after revocation, purge age by store, and objects or parts without a committed reference. Log identity, revision and outcome with opaque object IDs, omitting payloads and credentials. Define whose action is required when any stage stalls, and block risky publication rather than infer release from quiet logs.
Plan performance and compare products by responsibility
For short tasks, uploading and restoring gigabytes can dominate compute. Below is an idealized serial budget with 1 GiB of reads at a sustained 200 MiB/s and 20 MiB of writes at 100 MiB/s. The data-transfer terms alone sum to 5.32 seconds. Serialization, opens, TLS, queueing, retries and metadata commits add work. Parallelism can overlap phases, but constrained bandwidth changes the effective rates. Measure cold versus warm runs, p95 open and commit latency, and read amplification. Cost per completed run includes operations, retention in GiB-months, transferred GiB and paid runtime, as well as the work wasted by failed attempts. Versioning and retention for deleted data require separate cost and compliance decisions.
| Deployment option | Control point and buyer | What still needs a design |
|---|---|---|
| OpenAI-hosted agent sandbox | Agent platform team integrates session files and publishes turn artifacts under the documented output path | Session filesystem and published output have distinct lifecycles. Confirm quotas, retention and download authorization |
| Anthropic code execution | Product team enables the hosted tool and connects supported input/output files | Scope sandbox reuse, data policy and application-level result ownership |
| E2B or Daytona sandbox | Platform team provisions workspaces. E2B documents sandbox lifecycle options; Daytona exposes separate shared volumes | Verify stop/restart semantics, tenant isolation, consistency and who can mount the data |
| Modal Volumes | ML infrastructure team shares datasets, model artifacts or checkpoints with containers | Follow commit and reload semantics for visibility; coordinate concurrent writers at the application layer |
| Kubernetes plus object storage and a database | SRE/platform team owns compute isolation, mount boundaries and result publication | More control and integration effort. Validate failure handling and measure per-run storage and network costs |
A sandbox supplier’s docs establish supported interfaces, not independent performance rankings or organization-specific privacy guarantees. Buyers should compare isolation, custody, restore time and failure modes under their own workload. Exact vendor billing and retention should come from current terms for the chosen deployment. An opportunity for a specialized storage layer is a resumable, tenant-scoped artifact workflow across different runtimes. Its value can be measured by reproducible outputs after failures, audit completeness and mean recovery time. The test bar includes application authority and data lifecycle, beyond mounting a volume.
Practice and verification
Run the browser lab or download the JavaScript for Node.js 20+. It uses fixed synthetic data, no packages, no network and no seed. Compare a worker that writes and publishes without an idempotent, fenced commit against the reference protocol. Feed both the same trace with the same two candidate attempts. The lab simulates storage interfaces in memory. Its counts are correctness observables, not throughput or durability benchmarks. The single-host Python exercise shows the separate atomic-replacement pattern on a trusted Linux filesystem with Python 3.10+. It stages fixed bytes, injects a pre-replace error, and verifies the old output remains visible and staging is removed. It cannot simulate power-loss persistence or a distributed transaction.
Expected in the reference arm: one commit for normal, orphan recovery, lost response and expired worker; zero on cancellation and cross-tenant input. The lost reply replays one receipt. Cancellation leaves one unpublished blob. The orphan case reuses an uploaded object before it can become permanently orphaned. These are synthetic results.
node -e "import('./agent-storage-lab.mjs').then(m => console.log(m.compareStorage('lost-ack')))"
JavaScript
// Synthetic, single-result fixture. Expected identity comes from the trusted publisher.
export const cases = ['clean', 'orphan', 'lost-ack', 'expired', 'cancelled', 'wrong-tenant'];
const request = {tenant:'tenant-a', epoch:3, generation:1, object:'report-v1'};
const next = {...request, generation:2};
function createStore(guarded) {
const objects = new Set();
const receipts = [];
let generation = 1;
let active = true;
let rejected = 0;
let replayed = 0;
const key = candidate => candidate.tenant + ':' + candidate.object;
return {
upload(candidate) {
if (guarded && (candidate.tenant !== request.tenant || candidate.epoch !== request.epoch)) {
rejected++;
return;
}
objects.add(key(candidate));
},
publish(candidate) {
if (guarded) {
if (!active || candidate.tenant !== request.tenant || candidate.epoch !== request.epoch ||
!objects.has(key(candidate))) {
rejected++;
return;
}
const receipt = receipts[0];
if (receipt) {
if (receipt.key === key(candidate)) replayed++;
else rejected++;
return;
}
if (candidate.generation !== generation) {
rejected++;
return;
}
}
receipts.push({key:key(candidate), generation:candidate.generation});
},
nextLease() { generation = 2; },
cancel() { active = false; },
report() {
const referenced = new Set(receipts.map(receipt => receipt.key));
return {writes:receipts.length, orphaned:[...objects].filter(key => !referenced.has(key)).length,
rejected, replayed};
},
};
}
function run(scenario, guarded) {
const store = createStore(guarded);
const candidate = scenario === 'wrong-tenant' ? {...request,tenant:'tenant-b'} : request;
store.upload(candidate);
if (scenario === 'lost-ack') store.publish(request);
if (scenario === 'cancelled') store.cancel();
if (['expired','orphan','lost-ack'].includes(scenario)) store.nextLease();
if (scenario !== 'orphan') store.publish(candidate);
if (scenario === 'orphan' || scenario === 'expired') {
store.upload(next);
store.publish(next);
}
return store.report();
}
export function compareStorage(scenario) {
if (!cases.includes(scenario)) throw new RangeError('Unknown scenario');
return [run(scenario,false), run(scenario,true)];
}
const permitted = {
action: 'read', tenant: 'tenant-a', owner: 'tenant-a', version: 'v1', requestedVersion: 'v1',
policyAvailable: true, issuedRevision: 1, currentRevision: 1, committed: true,
now: 60, linkExpiresAt: 270, reviewed: true, sourceRecorded: true, promoteToPolicy: false,
tombstone: false, restoredPolicy: true, projectedMiB: 80, quotaMiB: 128,
};
const boundaryFixtures = {
allowed: {},
tenant: {tenant:'tenant-b'},
revoked: {action:'download',currentRevision:2},
staged: {action:'download',committed:false},
memory: {action:'remember',reviewed:false},
restore: {action:'restore',tombstone:true},
quota: {action:'write',projectedMiB:160},
timeout: {policyAvailable:false},
};
export const boundaryCases = Object.keys(boundaryFixtures);
export function compareStorageBoundary(scenario, overrides = {}) {
if (!Object.hasOwn(boundaryFixtures,scenario)) throw new RangeError('Unknown boundary case');
const state={...permitted,...boundaryFixtures[scenario],...overrides};
const baseline=state.action!=='download' || state.now<state.linkExpiresAt;
const current=state.policyAvailable && state.tenant===state.owner &&
state.requestedVersion===state.version && state.issuedRevision===state.currentRevision;
const stageAllows={
read: true,
download: state.committed,
remember: state.reviewed && state.sourceRecorded && !state.promoteToPolicy,
restore: state.restoredPolicy && !state.tombstone,
write: state.projectedMiB<=state.quotaMiB,
};
return [baseline, current && Object.hasOwn(stageAllows,state.action) && stageAllows[state.action]];
}
for (const lab of globalThis.document?.querySelectorAll('[data-storage-lab]') ?? []) {
const [baseline, guarded, writes, orphaned, rejected, replayed] = JSON.parse(lab.dataset.labels);
const select = lab.querySelector('select');
const output = lab.querySelector('output');
const update = () => {
output.textContent = compareStorage(select.value).map((result,i)=>
[i===0?baseline:guarded, writes+' '+result.writes, orphaned+' '+result.orphaned,
rejected+' '+result.rejected, replayed+' '+result.replayed].join(' · ')).join('\n');
};
select.addEventListener('change',update);
update();
}
for (const lab of globalThis.document?.querySelectorAll('[data-storage-boundary-lab]') ?? []) {
const [baseline, checked, allow, deny]=JSON.parse(lab.dataset.labels);
const select=lab.querySelector('select');
const output=lab.querySelector('output');
const update=()=>{
const [before,after]=compareStorageBoundary(select.value);
output.textContent=baseline+' · '+(before?allow:deny)+'\n'+checked+' · '+(after?allow:deny);
};
select.addEventListener('change',update);
update();
}
python3 -B agent-storage-local.py
Python
"""Linux, standard library. Single writer and a trusted destination directory."""
import os
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
def publish(directory, content, fail_before_replace=False):
destination = directory / "report.txt"
staged = None
try:
with NamedTemporaryFile(dir=directory, prefix=".report-", delete=False) as file:
staged = Path(file.name)
file.write(content)
file.flush()
os.fsync(file.fileno())
if fail_before_replace:
raise RuntimeError("fixture: worker stopped before publication")
os.replace(staged, destination)
folder = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(folder)
finally:
os.close(folder)
finally:
if staged is not None:
staged.unlink(missing_ok=True)
if __name__ == "__main__":
with TemporaryDirectory() as folder:
directory = Path(folder)
publish(directory, b"old report\n")
try:
publish(directory, b"revised report\n", fail_before_replace=True)
except RuntimeError as error:
print(error)
assert (directory / "report.txt").read_bytes() == b"old report\n"
assert list(directory.glob(".report-*")) == []
publish(directory, b"revised report\n")
assert (directory / "report.txt").read_bytes() == b"revised report\n"
print("PASS: old result preserved, staging cleaned, revised result visible")
Reproduce authorization and data-lifecycle decisions
Both arms allow the legitimate read. In the seven negative cases, the baseline accepts and the independent checks deny. The download is attempted 60 s after revocation, during the link’s remaining 270 s. The quota case writes 160 MiB with a 128 MiB limit. Choose each case and identify the enforcing component. Then change one input at a time, such as reviewing the observation or moving the write below the quota. This deterministic fixture models decisions, with no parser, cloud storage, network, or real files.
Print all boundary decisions on your own machine
node -e "import('./agent-storage-lab.mjs').then(m => m.boundaryCases.forEach(c => console.log(c, m.compareStorageBoundary(c))))"
Original mock interview questions, independent of company hiring
When does a file replacement survive power loss?
Hint 1
Separate a name switch from persistent writes.
Hint 2
What owns the directory entry?
Answer and reasoning
Stage on the same filesystem, synchronize the file, replace the name atomically and synchronize the directory. Validate the actual filesystem and device; a directory sync error leaves the outcome uncertain.
A worker uploaded successfully, then disappeared. Can you return a download link?
Hint 1
Locate the durable decision.
Hint 2
An object might exist without a pointer.
Answer and reasoning
Only a committed receipt and current authorization can release the artifact. With no receipt, a worker with a new lease can adopt the validated candidate, then commit it.
Six workers need 2,305 MiB each. Can they use 12 GiB of scratch?
Hint 1
Convert GiB to MiB.
Hint 2
Include concurrently live files and reserve.
Answer and reasoning
12 GiB is 12,288 MiB. Six require 13,830 MiB. Limit to five at the stated per-run budget, or reduce live data per worker. Logs and other node overhead reduce this illustrative ceiling.
How do you verify that workspace resume respects a changed policy?
Hint 1
Freeze the input manifest and vary only the policy epoch.
Hint 2
Check both commit and download.
Answer and reasoning
Expire old leases, refuse late commits and revalidate the pointer before serving. Replay a previously allowed operation with a new policy, and verify the call and audit outcome without loading another tenant’s data.
A report is in a backup. How do you stop a restore from making it visible again?
Hint 1
Find where the current deletion record lives.
Hint 2
Trace both new downloads and rebuilt indices.
Answer and reasoning
Restore without traffic, replay the current policy and tombstones, rebuild authorized derivatives only, and test the download path before release. Keep a ledger of which copies remain until expiry and which were purged.
Scoring from 1 to 5
Award 1 for naming the relevant layer, 2 for its contract, 3 for tracing the worked case, 4 for handling a failure, and 5 for a fair verification plan with stated limits.
References and educational links
- Pillai et al. · All File Systems Are Not Created Equal · OSDI 2014 · USENIXhttps://www.usenix.org/conference/osdi14/technical-sessions/presentation/pillai · PDFhttps://www.usenix.org/system/files/conference/osdi14/osdi14-paper-pillai.pdf
- Agache et al. · Firecracker · NSDI 2020 · USENIXhttps://www.usenix.org/conference/nsdi20/presentation/agache · PDFhttps://www.usenix.org/system/files/nsdi20-paper-agache.pdf · GitHubhttps://github.com/firecracker-microvm/firecracker
- Linux · fsync / rename / openat2 / OverlayFS · fsynchttps://man7.org/linux/man-pages/man2/fsync.2.html · renamehttps://man7.org/linux/man-pages/man2/rename.2.html · openat2https://man7.org/linux/man-pages/man2/openat2.2.html · OverlayFShttps://docs.kernel.org/filesystems/overlayfs.html
- Python tempfile · Kubernetes volumes and ephemeral storage · tempfilehttps://docs.python.org/3/library/tempfile.html · Volumeshttps://kubernetes.io/docs/reference/storage/volume-types/ · Ephemeral storagehttps://kubernetes.io/docs/concepts/storage/ephemeral-storage/
- Amazon S3 · consistency, conditional writes and integrity · S3https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html · Conditional writeshttps://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html · Checksumshttps://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html
- Parquet · SQLite WAL · DuckDB · PyTorch Distributed Checkpoint · Parquethttps://parquet.apache.org/docs/file-format/ · SQLitehttps://www.sqlite.org/wal.html · DuckDBhttps://duckdb.org/docs/current/guides/performance/how_to_tune_workloads.html · PyTorchhttps://docs.pytorch.org/docs/2.15/distributed.checkpoint.html
- MDN · Origin private file system · OPFShttps://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system
- OpenAI agent files and artifacts · Anthropic code execution · OpenAIhttps://developers.openai.com/api/docs/guides/agents-api/environments/files · Anthropichttps://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool
- E2B persistence · Daytona volumes · Modal Volumes · E2Bhttps://docs.e2b.dev/sandbox/persistence · Daytonahttps://www.daytona.io/docs/en/volumes/ · Modalhttps://modal.com/docs/guide/volumes
- OWASP · File Upload Cheat Sheet and ASI06: Memory & Context Poisoning · OWASP File Uploadhttps://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html · OWASP ASI06https://genai.owasp.org/agentic-applications-2026/asi06-memory-context-poisoning/
- OpenAI sandbox security · Kubernetes Pod Security Standards · OpenAIhttps://developers.openai.com/api/docs/guides/agents-api/environments/security · Kuberneteshttps://kubernetes.io/docs/concepts/security/pod-security-standards/
- PostgreSQL · Row Security Policies · PostgreSQLhttps://www.postgresql.org/docs/current/ddl-rowsecurity.html
- Amazon S3 · Presigned URLs, object versions and abandoned uploads · S3 signed URLshttps://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html · S3 versionshttps://docs.aws.amazon.com/AmazonS3/latest/userguide/DeletingObjectVersions.html · S3 multiparthttps://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-abort-incomplete-mpu-lifecycle-config.html
- NIST SP 800-88 Rev. 2 · Guidelines for Media Sanitization · September 2025 · NISThttps://csrc.nist.gov/pubs/sp/800/88/r2/final · DOIhttps://doi.org/10.6028/NIST.SP.800-88r2
- Chen, Xiang, Xiao, Song and Li · AgentPoison · NeurIPS 2024 · NeurIPShttps://proceedings.neurips.cc/paper_files/paper/2024/hash/eb113910e9c3f6242541c1652e30dfd6-Abstract-Conference.html · PDFhttps://proceedings.neurips.cc/paper_files/paper/2024/file/eb113910e9c3f6242541c1652e30dfd6-Paper-Conference.pdf · arXivhttps://arxiv.org/abs/2407.12784
- MDN CSP sandbox · PyTorch 2.15 torch.load · MDNhttps://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/sandbox · PyTorchhttps://docs.pytorch.org/docs/2.15/generated/torch.load.html