Reclaim abandoned computer home uploads from durable receipts

Persist exact upload ownership before staging, renew a five-minute inactivity lease per chunk, and reclaim verified expired uploads on seed or home admission. Preserve active uploads and unrelated directories, and fence delayed writes and aborts after replacement.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-10 11:31:56 -05:00
1 parent cd1bfc1aa0
commit b6f8c44f9f
2 files changed
+160 -61

No files matched your search

@@ -180,13 +180,13 @@ describe("confined computer files", () => {
const chunk = Buffer.alloc(1024 * 1024, 19);
for (const offset of [0, chunk.length]) expect(f.call({ action: "seed-chunk", seedId, path: "memory/data", offset, base64: chunk.toString("base64") })).toEqual({});
expect(existsSync(f.root)).toBe(false);
const staging = readdirSync(f.temp).find(name => name.startsWith(".paperclip-seed-"))!;
const staging = readdirSync(f.temp).find(name => name.startsWith(".paperclip-seed-") && statSync(join(f.temp, name)).isDirectory())!;
expect(statSync(join(f.temp, staging)).mode & 0o777).toBe(0o700);
expect(statSync(join(f.temp, staging, "tree", "memory", "data")).mode & 0o777).toBe(0o600);
expect(f.call({ action: "seed-chunk", seedId, path: "memory/data", offset: 0, base64: "" })).toEqual({ error: "conflict" });
expect(f.call({ action: "seed-commit", seedId })).toEqual({ seeded: true });
expect(readFileSync(join(f.root, "memory", "data"))).toEqual(Buffer.concat([chunk, chunk]));
expect(readdirSync(f.temp)).toEqual(["home"]);
expect(readdirSync(f.temp)).toEqual([".paperclip-seed-home.lock", "home"]);
expect(f.call({ action: "seed-begin", seedId: randomUUID() })).toEqual({ started: false });
const g = fixture(); const partial = randomUUID();
g.call({ action: "seed-begin", seedId: partial });
@@ -194,7 +194,7 @@ describe("confined computer files", () => {
expect(g.call({ action: "seed-chunk", seedId: partial, path: "large", offset: 0, base64: Buffer.alloc(1024 * 1024 + 1).toString("base64") })).toEqual({ error: "invalid" });
expect(g.call({ action: "seed-abort", seedId: partial })).toEqual({});
expect(existsSync(g.root)).toBe(false);
expect(readdirSync(g.temp)).toEqual([]);
expect(readdirSync(g.temp)).toEqual([".paperclip-seed-home.lock"]);
});
it("does not replace a home created while its initial upload was in progress", () => {
const f = fixture(); const seedId = randomUUID();
@@ -203,7 +203,49 @@ describe("confined computer files", () => {
mkdirSync(f.root);
expect(f.call({ action: "seed-commit", seedId })).toEqual({ seeded: false });
expect(readdirSync(f.root)).toEqual([]);
expect(readdirSync(f.temp)).toEqual(["home"]);
expect(readdirSync(f.temp)).toEqual([".paperclip-seed-home.lock", "home"]);
});
it("reclaims only the expired receipted upload after an interrupted seed", () => {
const f = fixture(); const first = randomUUID(); const next = randomUUID();
const receiptPath = join(f.temp, ".paperclip-seed-home.json");
const oldStage = join(f.temp, `.paperclip-seed-home-${first}`);
const unrelated = join(f.temp, `.paperclip-seed-home-${randomUUID()}`);
mkdirSync(unrelated); writeFileSync(join(unrelated, "user-file"), "keep");
expect(f.call({ action: "seed-begin", seedId: first })).toEqual({ started: true });
expect(f.call({ action: "seed-chunk", seedId: first, path: "partial", offset: 0, base64: Buffer.alloc(1024 * 1024).toString("base64") })).toEqual({});
expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ error: "conflict" });
const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
expect(receipt.seedId).toBe(first); expect(receipt.updatedAt).toBeGreaterThan(0);
writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: Date.now() / 1000 - 180 }));
expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ error: "conflict" });
writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: 0 }));
expect(f.call({ action: "seed-begin", seedId: next })).toEqual({ started: true });
expect(existsSync(oldStage)).toBe(false);
expect(f.call({ action: "seed-chunk", seedId: first, path: "late", offset: 0, base64: "" })).toEqual({ error: "conflict" });
expect(readFileSync(join(unrelated, "user-file"), "utf8")).toBe("keep");
expect(f.call({ action: "seed-abort", seedId: first })).toEqual({});
expect(JSON.parse(readFileSync(receiptPath, "utf8")).seedId).toBe(next);
expect(f.call({ action: "seed-chunk", seedId: next, path: "complete", offset: 0, base64: Buffer.from("done").toString("base64") })).toEqual({});
expect(f.call({ action: "seed-commit", seedId: next })).toEqual({ seeded: true });
expect(readFileSync(join(f.root, "complete"), "utf8")).toBe("done");
expect(existsSync(receiptPath)).toBe(false);
});
it("cleans abandoned upload receipts on home admission but preserves unverified content", () => {
const f = fixture(); const seedId = randomUUID();
const receiptPath = join(f.temp, ".paperclip-seed-home.json");
const stage = join(f.temp, `.paperclip-seed-home-${seedId}`);
f.call({ action: "seed-begin", seedId });
f.call({ action: "seed-chunk", seedId, path: "partial", offset: 0, base64: Buffer.from("partial").toString("base64") });
mkdirSync(f.root); writeFileSync(join(f.root, "user-file"), "keep");
const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
writeFileSync(receiptPath, JSON.stringify({ ...receipt, updatedAt: 0 }));
writeFileSync(join(stage, "owner.json"), JSON.stringify({ purpose: "user-owned" }));
expect(f.call({ action: "list", limit: 1 })).toEqual({ error: "invalid" });
expect(readFileSync(join(stage, "tree", "partial"), "utf8")).toBe("partial");
writeFileSync(join(stage, "owner.json"), JSON.stringify({ purpose: receipt.purpose, root: receipt.root, seedId }));
expect(f.call({ action: "list", limit: 1 }).entries[0].name).toBe("user-file");
expect(existsSync(stage)).toBe(false); expect(existsSync(receiptPath)).toBe(false);
expect(readFileSync(join(f.root, "user-file"), "utf8")).toBe("keep");
});
it("hashes and deletes files over the read limit while fencing changed bytes", () => {
const f = fixture();
@@ -109,68 +109,125 @@ def directory(parts,create=False,start=None):
except BaseException:os.close(fd);raise
# Initial uploads stay in a private sibling until a no-replace rename publishes them.
# Each request carries at most one bounded chunk, never the whole home.
if act in ('seed-begin','seed-chunk','seed-commit','seed-abort'):
import uuid,ctypes,errno
token=p.get('seedId','')
seed_actions=('seed-begin','seed-chunk','seed-commit','seed-abort')
# The durable receipt names one exact upload. Root listings (including home
# admission) reclaim expired uploads even after a controller crash or publish.
if act in seed_actions or (act=='list' and not p.get('path') and os.path.lexists(os.path.join(os.path.dirname(root),'.paperclip-seed-'+os.path.basename(root)+'.json'))):
import uuid,ctypes,errno,time,math
parentfd=None;leasefd=None;stagefd=None
try:
if str(uuid.UUID(token))!=token:fail('invalid')
except (ValueError,TypeError,AttributeError):fail('invalid')
parentfd=directory(os.path.dirname(root).split('/'),create=True)
name=os.path.basename(root);staging='.paperclip-seed-'+name+'-'+token
stagefd=None;lockfd=None
try:
if act=='seed-abort':
try:shutil.rmtree(staging,dir_fd=parentfd)
except FileNotFoundError:pass
print('{}');sys.exit(0)
if act=='seed-begin':
try:
existing=os.stat(name,dir_fd=parentfd,follow_symlinks=False)
if not stat.S_ISDIR(existing.st_mode):fail('invalid')
print(json.dumps({'started':False}));sys.exit(0)
except FileNotFoundError:pass
os.mkdir(staging,0o700,dir_fd=parentfd)
stagefd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd)
lockfd=os.open('lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600,dir_fd=stagefd)
fcntl.flock(lockfd,fcntl.LOCK_EX)
if act=='seed-begin':
os.mkdir('tree',0o700,dir_fd=stagefd)
print(json.dumps({'started':True}))
elif act=='seed-chunk':
relative=p.get('path','');safe(relative)
parts=[part for part in relative.split('/') if part not in ('','.')]
if not parts:fail('invalid')
data=base64.b64decode(p['base64'],validate=True);offset=p.get('offset')
if len(data)>1024*1024 or type(offset)!=int or offset<0 or offset+len(data)>256*1024*1024:fail('invalid')
destfd=directory(['tree']+parts[:-1],create=True,start=stagefd)
try:fd=os.open(parts[-1],os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW,0o600,dir_fd=destfd)
finally:os.close(destfd)
with os.fdopen(fd,'r+b') as f:
parentfd=directory(os.path.dirname(root).split('/'),create=act in seed_actions)
name=os.path.basename(root);receipt_name='.paperclip-seed-'+name+'.json'
leasefd=os.open('.paperclip-seed-'+name+'.lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600,dir_fd=parentfd)
info=os.fstat(leasefd)
if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid')
fcntl.flock(leasefd,fcntl.LOCK_EX)
def read_metadata(directory_fd,name):
fd=os.open(name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=directory_fd)
with os.fdopen(fd,'rb') as f:
info=os.fstat(f.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid')
if info.st_size!=offset:fail('conflict')
f.seek(offset);f.write(data)
print('{}')
else:
libc=ctypes.CDLL(None,use_errno=True)
if hasattr(libc,'renameat2'):status=libc.renameat2(stagefd,b'tree',parentfd,os.fsencode(name),1)
elif hasattr(libc,'renameatx_np'):status=libc.renameatx_np(stagefd,b'tree',parentfd,os.fsencode(name),4)
else:fail('invalid')
if status!=0:
code=ctypes.get_errno()
if code not in (errno.EEXIST,errno.ENOTEMPTY):raise OSError(code,os.strerror(code))
if not stat.S_ISDIR(os.stat(name,dir_fd=parentfd,follow_symlinks=False).st_mode):fail('invalid')
print(json.dumps({'seeded':status==0}))
if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1 or info.st_size>4096:fail('invalid')
return json.loads(f.read(4097))
def save_receipt(value):
if value is None:
try:os.unlink(receipt_name,dir_fd=parentfd)
except FileNotFoundError:pass
else:
temporary=receipt_name+'.tmp'
fd=os.open(temporary,os.O_CREAT|os.O_WRONLY|os.O_NOFOLLOW,0o600,dir_fd=parentfd)
with os.fdopen(fd,'wb') as f:
info=os.fstat(f.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid')
f.truncate(0);f.write(json.dumps(value).encode());f.flush();os.fsync(f.fileno())
os.rename(temporary,receipt_name,src_dir_fd=parentfd,dst_dir_fd=parentfd)
os.fsync(parentfd)
def identity(token):return {'purpose':'paperclip-initial-home-v1','root':root,'seedId':token}
def remove_receipted_upload(receipt):
staging='.paperclip-seed-'+name+'-'+receipt['seedId']
try:fd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd)
except FileNotFoundError:return
try:
try:marker=read_metadata(fd,'owner.json')
except FileNotFoundError:
# Receipt is durable before mkdir. An interrupted begin can only leave
# an empty directory here; never recursively remove unmarked content.
os.rmdir(staging,dir_fd=parentfd);return
if marker!=identity(receipt['seedId']):fail('invalid')
finally:os.close(fd)
shutil.rmtree(staging,dir_fd=parentfd)
try:receipt=read_metadata(parentfd,receipt_name)
except FileNotFoundError:receipt=None
if receipt is not None:
if not isinstance(receipt,dict) or receipt.get('purpose')!='paperclip-initial-home-v1' or receipt.get('root')!=root:fail('invalid')
if str(uuid.UUID(receipt.get('seedId','')))!=receipt['seedId']:fail('invalid')
updated=receipt.get('updatedAt')
if not isinstance(updated,(int,float)) or not math.isfinite(updated):fail('invalid')
# Exceeds the 120s queued+executing backend deadline, with restart margin.
if time.time()-updated>300:
remove_receipted_upload(receipt);save_receipt(None);receipt=None
if act in seed_actions:
token=p.get('seedId','')
if str(uuid.UUID(token))!=token:fail('invalid')
staging='.paperclip-seed-'+name+'-'+token
if act=='seed-begin':
try:
existing=os.stat(name,dir_fd=parentfd,follow_symlinks=False)
if not stat.S_ISDIR(existing.st_mode):fail('invalid')
print(json.dumps({'started':False}));sys.exit(0)
except FileNotFoundError:pass
if receipt is not None:fail('conflict')
# Reserve only an absent random path before persisting its exact identity.
try:os.stat(staging,dir_fd=parentfd,follow_symlinks=False);fail('conflict')
except FileNotFoundError:pass
receipt={**identity(token),'updatedAt':time.time()};save_receipt(receipt)
os.mkdir(staging,0o700,dir_fd=parentfd)
stagefd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd)
markerfd=os.open('owner.json',os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600,dir_fd=stagefd)
with os.fdopen(markerfd,'wb') as f:f.write(json.dumps(identity(token)).encode());f.flush();os.fsync(f.fileno())
os.mkdir('tree',0o700,dir_fd=stagefd)
print(json.dumps({'started':True}))
elif act=='seed-abort':
if receipt is not None and receipt['seedId']==token:
remove_receipted_upload(receipt);save_receipt(None)
print('{}')
else:
if receipt is None or receipt['seedId']!=token:fail('conflict')
stagefd=os.open(staging,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parentfd)
if read_metadata(stagefd,'owner.json')!=identity(token):fail('invalid')
if act=='seed-chunk':
relative=p.get('path','');safe(relative)
parts=[part for part in relative.split('/') if part not in ('','.')]
if not parts:fail('invalid')
data=base64.b64decode(p['base64'],validate=True);offset=p.get('offset')
if len(data)>1024*1024 or type(offset)!=int or offset<0 or offset+len(data)>256*1024*1024:fail('invalid')
destfd=directory(['tree']+parts[:-1],create=True,start=stagefd)
try:fd=os.open(parts[-1],os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW,0o600,dir_fd=destfd)
finally:os.close(destfd)
with os.fdopen(fd,'r+b') as f:
info=os.fstat(f.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_nlink!=1:fail('invalid')
if info.st_size!=offset:fail('conflict')
f.seek(offset);f.write(data)
receipt['updatedAt']=time.time();save_receipt(receipt)
print('{}')
else:
libc=ctypes.CDLL(None,use_errno=True)
if hasattr(libc,'renameat2'):status=libc.renameat2(stagefd,b'tree',parentfd,os.fsencode(name),1)
elif hasattr(libc,'renameatx_np'):status=libc.renameatx_np(stagefd,b'tree',parentfd,os.fsencode(name),4)
else:fail('invalid')
if status!=0:
code=ctypes.get_errno()
if code not in (errno.EEXIST,errno.ENOTEMPTY):raise OSError(code,os.strerror(code))
if not stat.S_ISDIR(os.stat(name,dir_fd=parentfd,follow_symlinks=False).st_mode):fail('invalid')
remove_receipted_upload(receipt);save_receipt(None)
print(json.dumps({'seeded':status==0}))
except FileNotFoundError:fail('not_found')
except (OSError,ValueError):fail('invalid')
except (OSError,ValueError,TypeError,AttributeError):fail('invalid')
finally:
if lockfd is not None:os.close(lockfd)
if stagefd is not None:os.close(stagefd)
if act=='seed-commit':
try:shutil.rmtree(staging,dir_fd=parentfd)
except FileNotFoundError:pass
os.close(parentfd)
sys.exit(0)
if leasefd is not None:os.close(leasefd)
if parentfd is not None:os.close(parentfd)
if act in seed_actions:sys.exit(0)
try:rootfd=directory(root.split('/'))
except FileNotFoundError:fail('not_found')
except OSError:fail('invalid')