mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
Integrate graceful Boat idle retirement and recovery
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
1e5cf7cb42
23 files changed
+902
-123
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();
|
||||
@@ -532,3 +574,29 @@ describe("Boat SSH admission", () => {
|
||||
expect(runner.execute).toHaveBeenCalledTimes(12);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("remote graceful retirement fence", () => {
|
||||
it("records the exact generation deadline and blocks late launch or generation reuse", () => {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "computer-grace-")));
|
||||
roots.push(root);
|
||||
const owners = join(root, "owners");
|
||||
const boot = join(root, "boot");
|
||||
writeFileSync(boot, "boot-id");
|
||||
const code = processProgram.replaceAll("/home/user/.paperclip-owners", owners)
|
||||
.replaceAll("/proc/sys/kernel/random/boot_id", boot);
|
||||
const invoke = (action: string, owner: Record<string, unknown>) => {
|
||||
const result = spawnSync("python3", ["-c", code], { input: JSON.stringify({ action, owner }), encoding: "utf8" });
|
||||
expect(result.status, result.stderr).toBe(0);
|
||||
return JSON.parse(result.stdout);
|
||||
};
|
||||
const owner = { id: "owned", generation: 7, phase: "retiring", retirementDeadline: "2099-01-01T00:00:00Z" };
|
||||
expect(invoke("advance", owner)).toEqual({});
|
||||
const marker = readFileSync(join(owners, "owned", "retiring.json"), "utf8");
|
||||
expect(JSON.parse(marker).deadline).toBe(Date.parse(owner.retirementDeadline));
|
||||
expect(invoke("launch", owner)).toEqual({ error: "conflict" });
|
||||
expect(invoke("advance", { ...owner, phase: "active", generation: 8 })).toEqual({ error: "conflict" });
|
||||
expect(invoke("advance", { ...owner, generation: 6 })).toEqual({ error: "conflict" });
|
||||
expect(readFileSync(join(owners, "owned", "retiring.json"), "utf8")).toBe(marker);
|
||||
});
|
||||
});
|
||||
@@ -112,7 +112,7 @@ with os.fdopen(fd,'a') as lock:
|
||||
`;
|
||||
|
||||
export const processProgram = String.raw`
|
||||
import os,sys,json,fcntl,subprocess,shutil,re
|
||||
import os,sys,json,fcntl,subprocess,shutil,re,datetime
|
||||
p=json.load(sys.stdin);base='/home/user/.paperclip-owners';os.makedirs(base,exist_ok=True)
|
||||
def retire_owner(root,oid):
|
||||
open(os.path.join(root,'retired'),'a').close()
|
||||
@@ -151,6 +151,11 @@ with open(os.path.join(root,'lock'),'a') as lock:
|
||||
if owner['generation']<generation:print(json.dumps({'error':'conflict'}));sys.exit(0)
|
||||
if p['action']=='advance':
|
||||
if os.path.exists(tombstone):print(json.dumps({'error':'conflict'}));sys.exit(0)
|
||||
retirement=os.path.join(root,'retiring.json')
|
||||
if owner.get('phase')=='retiring':
|
||||
deadline=datetime.datetime.fromisoformat(owner['retirementDeadline'].replace('Z','+00:00')).timestamp()*1000
|
||||
with open(retirement,'w') as f:json.dump({'deadline':deadline},f)
|
||||
elif os.path.exists(retirement):print(json.dumps({'error':'conflict'}));sys.exit(0)
|
||||
with open(generation_path,'w') as f:f.write(str(owner['generation']))
|
||||
print('{}')
|
||||
elif p['action']=='retire':
|
||||
@@ -162,7 +167,7 @@ with open(os.path.join(root,'lock'),'a') as lock:
|
||||
state=subprocess.run(['systemctl','--user','is-active',unit],capture_output=True,text=True).stdout.strip()
|
||||
print(json.dumps({'running':bool(valid and state=='active' and not os.path.exists(tombstone)),'claim':actual if valid else claim}))
|
||||
else:
|
||||
if os.path.exists(tombstone):print(json.dumps({'error':'conflict'}));sys.exit(0)
|
||||
if os.path.exists(tombstone) or os.path.exists(os.path.join(root,'retiring.json')):print(json.dumps({'error':'conflict'}));sys.exit(0)
|
||||
claim=owner['process'];claim['bootId']=boot
|
||||
marker=os.path.join(root,'claim.json')
|
||||
if os.path.exists(marker):
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -327,10 +327,11 @@ describe("computer ownership", () => {
|
||||
expect(f.backend.stop).toHaveBeenCalledOnce();
|
||||
},
|
||||
);
|
||||
it("preserves recoverable running owners and gives completed warm owners their idle interval", async () => {
|
||||
it("fences warm work at its deadline and bounds crashed-controller shutdown grace", async () => {
|
||||
const f = fixture();
|
||||
await f.attach();
|
||||
const binding = await f.admit();
|
||||
await binding.launch({ command: "runner" });
|
||||
f.advance(180_000);
|
||||
await f.service.reconcile();
|
||||
expect(f.backend.retire).not.toHaveBeenCalled();
|
||||
@@ -343,6 +344,13 @@ describe("computer ownership", () => {
|
||||
await f.service.reconcile();
|
||||
expect(f.backend.retire).not.toHaveBeenCalled();
|
||||
f.advance(60_001);
|
||||
await expect(f.admit()).rejects.toMatchObject({ code: "conflict" });
|
||||
await expect(binding.runner.execute({ command: "new work" })).rejects.toMatchObject({ code: "conflict" });
|
||||
await binding.process.runner.execute({ command: "close provider" });
|
||||
await f.service.reconcile();
|
||||
expect(f.backend.retire).not.toHaveBeenCalled();
|
||||
f.advance(30_000);
|
||||
await expect(binding.process.ingress()).rejects.toMatchObject({ code: "conflict" });
|
||||
await f.service.reconcile();
|
||||
expect(f.backend.retire).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -698,3 +706,107 @@ describe("computer retirement proof", () => {
|
||||
expect(f.backend.inspect).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("computer graceful retirement", () => {
|
||||
it("fences admission and ordinary execution while allowing the exact pinned process to close", async () => {
|
||||
const f = fixture();
|
||||
await f.attach();
|
||||
const binding = await f.admit();
|
||||
await binding.launch({ command: "runner" });
|
||||
let finish!: () => void;
|
||||
let entered!: () => void;
|
||||
const closing = new Promise<void>((resolve) => { finish = resolve; });
|
||||
const started = new Promise<void>((resolve) => { entered = resolve; });
|
||||
const beforeStop = vi.fn(async () => { entered(); await closing; });
|
||||
const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop });
|
||||
await started;
|
||||
expect((await f.repository.get(f.scope)).ledger.owners[0]).toMatchObject({ phase: "retiring" });
|
||||
await expect(f.admit()).rejects.toMatchObject({ code: "conflict" });
|
||||
await expect(binding.runner.execute({ command: "forbidden" })).rejects.toMatchObject({ code: "conflict" });
|
||||
await expect(binding.launch({ command: "forbidden" })).rejects.toMatchObject({ code: "conflict" });
|
||||
await binding.process.runner.execute({ command: "close" });
|
||||
await binding.process.ingress();
|
||||
expect(f.backend.retire).not.toHaveBeenCalled();
|
||||
const repeated = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop });
|
||||
finish();
|
||||
expect(await retiring).toEqual({ retired: true });
|
||||
expect(await repeated).toEqual({ retired: true });
|
||||
expect(beforeStop).toHaveBeenCalledOnce();
|
||||
expect(f.backend.retire).toHaveBeenCalledOnce();
|
||||
await expect(binding.process.ingress()).rejects.toMatchObject({ code: "conflict" });
|
||||
expect((await f.admit()).owner.ownerId).not.toBe(binding.owner.ownerId);
|
||||
});
|
||||
it("never invokes a stale generation callback and always stops after callback failure", async () => {
|
||||
const f = fixture();
|
||||
await f.attach();
|
||||
const old = await f.admit();
|
||||
await old.launch({ command: "runner" });
|
||||
await f.service.retainWarm({ ...f.scope, owner: old.owner, idleTimeoutMs: 60_000 });
|
||||
const current = await f.admit();
|
||||
const stale = vi.fn(async () => {});
|
||||
expect(await f.service.retire({ ...f.scope, owner: old.owner, beforeStop: stale })).toEqual({ retired: false });
|
||||
expect(stale).not.toHaveBeenCalled();
|
||||
expect(await f.service.retire({ ...f.scope, owner: current.owner, beforeStop: async () => { throw new Error("provider close failed"); } })).toEqual({ retired: true });
|
||||
expect(f.backend.retire).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("bounds a stalled graceful close and denies late process control", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const f = fixture();
|
||||
await f.attach();
|
||||
const binding = await f.admit();
|
||||
await binding.launch({ command: "runner" });
|
||||
let entered!: () => void;
|
||||
const started = new Promise<void>((resolve) => { entered = resolve; });
|
||||
const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop: async () => {
|
||||
entered(); await new Promise<void>(() => {});
|
||||
} });
|
||||
await started;
|
||||
f.advance(30_001);
|
||||
await expect(binding.process.runner.execute({ command: "late" })).rejects.toMatchObject({ code: "conflict" });
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(await retiring).toEqual({ retired: true });
|
||||
expect(f.backend.retire).toHaveBeenCalledOnce();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it("does not extend the original warm shutdown deadline when retirement starts late", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const f = fixture();
|
||||
await f.attach();
|
||||
const binding = await f.admit();
|
||||
await binding.launch({ command: "runner" });
|
||||
await f.service.retainWarm({ ...f.scope, owner: binding.owner, idleTimeoutMs: 60_000 });
|
||||
f.advance(80_000);
|
||||
let entered!: () => void;
|
||||
const started = new Promise<void>((resolve) => { entered = resolve; });
|
||||
const retiring = f.service.retire({ ...f.scope, owner: binding.owner, beforeStop: async () => {
|
||||
entered(); await new Promise<void>(() => {});
|
||||
} });
|
||||
await started;
|
||||
expect((await f.repository.get(f.scope)).ledger.owners[0]!.retirementDeadline).toBe("2026-10-10T12:01:30.000Z");
|
||||
f.advance(10_000);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(await retiring).toEqual({ retired: true });
|
||||
expect(f.backend.retire).toHaveBeenCalledOnce();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it("reconciles a crashed controller reservation only after its durable deadline", async () => {
|
||||
const f = fixture();
|
||||
await f.attach();
|
||||
const binding = await f.admit();
|
||||
await binding.launch({ command: "runner" });
|
||||
await f.repository.update(f.scope, (record) => {
|
||||
record.ledger.owners[0]!.phase = "retiring";
|
||||
record.ledger.owners[0]!.retirementDeadline = "2026-10-10T12:00:30.000Z";
|
||||
});
|
||||
await f.service.reconcile();
|
||||
expect(f.backend.retire).not.toHaveBeenCalled();
|
||||
await expect(f.service.retire({ ...f.scope, owner: binding.owner })).rejects.toMatchObject({ code: "conflict" });
|
||||
f.advance(30_001);
|
||||
await f.service.reconcile();
|
||||
expect(f.backend.retire).toHaveBeenCalledOnce();
|
||||
expect((await f.repository.get(f.scope)).ledger.owners[0]!.phase).toBe("retired");
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,8 @@ class ComputerSessionBusyError extends ComputerError {
|
||||
}
|
||||
}
|
||||
|
||||
// This is shutdown time only; admission and ordinary work stop at the warm deadline.
|
||||
const RETIREMENT_GRACE_MS = 30_000;
|
||||
type Scope = { companyId: string; environmentId: string };
|
||||
export function createComputerService(
|
||||
repository: ComputerRepository,
|
||||
@@ -38,6 +40,15 @@ export function createComputerService(
|
||||
ownerId: owner.id,
|
||||
generation: owner.generation,
|
||||
});
|
||||
const retirements = new Map<string, Promise<{ retired: boolean }>>();
|
||||
const retirementGraceOpen = (owner: Owner) => owner.phase === "retiring" &&
|
||||
!!owner.retirementDeadline && Date.parse(owner.retirementDeadline) > now().getTime();
|
||||
const warmShutdownGraceOpen = (owner: Owner) => owner.kind === "runner" && owner.phase === "warm" &&
|
||||
!!owner.deadline && Date.parse(owner.deadline) + RETIREMENT_GRACE_MS > now().getTime();
|
||||
const processControlAllowed = (owner: Owner) =>
|
||||
((owner.phase === "active" || owner.phase === "starting") && !expired(owner, now())) ||
|
||||
(owner.phase === "warm" && (!expired(owner, now()) || warmShutdownGraceOpen(owner))) ||
|
||||
retirementGraceOpen(owner);
|
||||
const base = (record: ComputerRecord) =>
|
||||
`/home/user/paperclip/${segment(record.companyId)}`;
|
||||
async function admitRecord<T>(
|
||||
@@ -173,14 +184,19 @@ export function createComputerService(
|
||||
const control = await backend.runner(record, { control: true });
|
||||
let pinnedProcess = owner.process ? structuredClone(owner.process) : null;
|
||||
async function processScope() {
|
||||
if (!pinnedProcess) return scoped({ ...record, owner: ownerRef });
|
||||
if (!pinnedProcess) {
|
||||
const current = await scoped({ ...record, owner: ownerRef });
|
||||
if (!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now()))
|
||||
throw new ComputerError("conflict", "Computer process capability has expired");
|
||||
return current;
|
||||
}
|
||||
const latest = await repository.get(record);
|
||||
const candidate = latest.ledger.owners.find(
|
||||
(value) => value.id === owner.id,
|
||||
);
|
||||
if (
|
||||
!candidate?.process ||
|
||||
!["active", "starting", "warm"].includes(candidate.phase) ||
|
||||
!processControlAllowed(candidate) ||
|
||||
candidate.process.nonce !== pinnedProcess.nonce ||
|
||||
candidate.process.unitName !== pinnedProcess.unitName ||
|
||||
candidate.process.bootId !== pinnedProcess.bootId ||
|
||||
@@ -200,7 +216,8 @@ export function createComputerService(
|
||||
const current = await (processScoped
|
||||
? processScope()
|
||||
: scoped({ ...record, owner: ownerRef }));
|
||||
if (!["active", "starting", "warm"].includes(current.owner.phase))
|
||||
if ((!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now())) &&
|
||||
!(processScoped && pinnedProcess && processControlAllowed(current.owner)))
|
||||
throw new ComputerError("conflict", "Computer owner is retired");
|
||||
// Start a command unit under the same owner slice while holding the remote tombstone lock.
|
||||
// The lock is released only after systemd knows the unit, so retirement cannot miss a delayed launch.
|
||||
@@ -235,6 +252,9 @@ try:
|
||||
with open(root+'/lock','a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
if os.path.exists(root+'/retired'):raise RuntimeError('computer owner retired')
|
||||
if os.path.exists(root+'/retiring.json'):
|
||||
with open(root+'/retiring.json') as retirement:deadline=json.load(retirement)['deadline']
|
||||
if not p.get('processClaim') or time.time()*1000>=deadline:raise RuntimeError('computer owner is retiring')
|
||||
if p.get('processClaim'):
|
||||
claim=json.load(open(root+'/claim.json'))
|
||||
if any(claim[k]!=p['processClaim'][k] for k in ['nonce','unitName','bootId','launchGeneration']) or claim['bootId']!=open('/proc/sys/kernel/random/boot_id').read().strip():raise RuntimeError('computer process superseded')
|
||||
@@ -347,7 +367,7 @@ finally:
|
||||
},
|
||||
async ingress(input?: { port?: number; path?: string }) {
|
||||
const current = await scoped({ ...record, owner: ownerRef });
|
||||
if (current.owner.phase === "retired")
|
||||
if (!["active", "starting", "warm"].includes(current.owner.phase) || expired(current.owner, now()))
|
||||
throw new ComputerError("conflict", "Computer owner retired");
|
||||
return backend.ingress(
|
||||
current.record,
|
||||
@@ -389,10 +409,7 @@ finally:
|
||||
if (owner && owner.phase !== "warm")
|
||||
throw new ComputerSessionBusyError(owner.runId, owner.agentId);
|
||||
if (owner && expired(owner, now()))
|
||||
throw new ComputerError(
|
||||
"conflict",
|
||||
"Computer warm session is retiring",
|
||||
);
|
||||
throw new ComputerSessionBusyError(owner.runId, owner.agentId);
|
||||
if (owner) {
|
||||
owner.generation++;
|
||||
owner.phase = "starting";
|
||||
@@ -504,19 +521,53 @@ finally:
|
||||
owner.runId === input.runId,
|
||||
);
|
||||
}
|
||||
async function retire(input: Scope & { owner: OwnerRef }) {
|
||||
async function retire(input: Scope & { owner: OwnerRef; beforeStop?: () => Promise<void> }) {
|
||||
const key = `${input.companyId}:${input.environmentId}:${input.owner.computerId}:${input.owner.ownerId}:${input.owner.generation}`;
|
||||
const existing = retirements.get(key);
|
||||
if (existing) return existing;
|
||||
const pending = performRetirement(input);
|
||||
retirements.set(key, pending);
|
||||
try { return await pending; }
|
||||
finally { if (retirements.get(key) === pending) retirements.delete(key); }
|
||||
}
|
||||
async function performRetirement(input: Scope & { owner: OwnerRef; beforeStop?: () => Promise<void> }) {
|
||||
const state = await repository.update(input, (record) => {
|
||||
const owner = record.ledger.owners.find(
|
||||
(value) => value.id === input.owner.ownerId,
|
||||
);
|
||||
const owner = record.ledger.owners.find((value) => value.id === input.owner.ownerId);
|
||||
if (record.id !== input.owner.computerId || !owner)
|
||||
throw new ComputerError("not_found", "Computer owner not found");
|
||||
if (owner.generation !== input.owner.generation) return null;
|
||||
if (owner.phase !== "retired") owner.phase = "retiring";
|
||||
return { record: structuredClone(record), owner: structuredClone(owner) };
|
||||
if (retirementGraceOpen(owner))
|
||||
throw new ComputerError("conflict", "Computer graceful retirement is pending");
|
||||
const retirementDeadline = owner.phase === "warm" && owner.deadline
|
||||
? Math.min(now().getTime() + RETIREMENT_GRACE_MS, Date.parse(owner.deadline) + RETIREMENT_GRACE_MS)
|
||||
: now().getTime() + RETIREMENT_GRACE_MS;
|
||||
const graceful = owner.phase !== "retiring" && owner.phase !== "retired" &&
|
||||
owner.kind === "runner" && !!owner.process && !!input.beforeStop && retirementDeadline > now().getTime();
|
||||
if (owner.phase !== "retired") {
|
||||
owner.phase = "retiring";
|
||||
owner.retirementDeadline = graceful ? new Date(retirementDeadline).toISOString() : null;
|
||||
}
|
||||
return { record: structuredClone(record), owner: structuredClone(owner), graceful };
|
||||
});
|
||||
if (!state) return { retired: false };
|
||||
if (state.owner.phase === "retired") return { retired: true };
|
||||
if (state.graceful) {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
(async () => {
|
||||
await backend.advance(state.record, state.owner);
|
||||
if (retirementGraceOpen(state.owner)) await input.beforeStop!();
|
||||
})(),
|
||||
new Promise<void>((resolve) => { timer = setTimeout(resolve, Math.max(0, Date.parse(state.owner.retirementDeadline!) - now().getTime())); }),
|
||||
]);
|
||||
} catch {
|
||||
// Graceful provider shutdown is best effort; physical retirement is mandatory.
|
||||
} finally { if (timer) clearTimeout(timer); }
|
||||
await repository.update(input, (record) => {
|
||||
exactOwner(record, input.owner).retirementDeadline = null;
|
||||
});
|
||||
}
|
||||
if (state.owner.kind === "runner") {
|
||||
const status = await backend.inspect(state.record);
|
||||
if (!["stopped", "archived"].includes(status.state))
|
||||
@@ -526,6 +577,7 @@ finally:
|
||||
const owner = exactOwner(record, input.owner);
|
||||
owner.phase = "retired";
|
||||
owner.deadline = null;
|
||||
owner.retirementDeadline = null;
|
||||
});
|
||||
return { retired: true };
|
||||
}
|
||||
@@ -885,7 +937,8 @@ finally:
|
||||
}
|
||||
record = await repository.get(record);
|
||||
for (const owner of liveOwners(record.ledger))
|
||||
if (owner.phase === "retiring" || expired(owner, now()))
|
||||
if (owner.phase === "retiring" ? !retirementGraceOpen(owner)
|
||||
: expired(owner, now()) && !warmShutdownGraceOpen(owner))
|
||||
await retire({ ...record, owner: ref(record, owner) });
|
||||
await repository.update(record, (current) => {
|
||||
current.ledger.owners = current.ledger.owners.filter(
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface Owner {
|
||||
port: number;
|
||||
deadline: string | null;
|
||||
absoluteDeadline: string | null;
|
||||
/** Bounded graceful shutdown reservation; only pinned process control remains valid. */
|
||||
retirementDeadline?: string | null;
|
||||
process: ProcessClaim | null;
|
||||
}
|
||||
export interface Ledger {
|
||||
|
||||
@@ -121,8 +121,8 @@ export async function computerExecutionTarget(db: Db, lease: EnvironmentLease, i
|
||||
workspaceRealization: { mode: "in_place", authoritativeRoot: binding.remoteCwd, pathAliases: [], outboundRestorePaths: [] },
|
||||
launch: binding.launch, inspectProcess: binding.inspectProcess,
|
||||
retainWarm: (idleTimeoutMs) => computers.retainWarm({ ...scope, owner, idleTimeoutMs }),
|
||||
retire: async () => {
|
||||
const result = await computers.retire({ ...scope, owner });
|
||||
retire: async (options) => {
|
||||
const result = await computers.retire({ ...scope, owner, beforeStop: options?.beforeStop });
|
||||
if (result.retired) await environmentService(db).releaseLease(lease.id, "released", { cleanupStatus: "success",
|
||||
remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }) });
|
||||
return result.retired;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { nativeSessionBootstrapTimeoutMs } from "./native-session-executor.js";
|
||||
import { compareAndSealRetiredComputerCheckpoint, retiredComputerCheckpointIsSettled, retireUnlaunchedComputerAttempt, nativeSessionBootstrapTimeoutMs } from "./native-session-executor.js";
|
||||
import { prepareHeartbeatGitHubLaunchers } from "../heartbeat-github-launchers.js";
|
||||
import { gunzipSync } from "node:zlib";
|
||||
import { configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js";
|
||||
@@ -7698,7 +7698,7 @@ describe("native warm session supervision", () => {
|
||||
const name = `computer-owner-${suffix}`;
|
||||
const current = { ...execution, binding: { ...execution.binding, runId: name, agentId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1;
|
||||
const close = vi.fn(async () => undefined), retainWarm = vi.fn(async () => undefined), retire = vi.fn(async () => true);
|
||||
const close = vi.fn(async () => undefined), retainWarm = vi.fn(async () => undefined), retire = vi.fn(async (options?: { beforeStop?: () => Promise<void> }) => { await options?.beforeStop?.(); return true; });
|
||||
const target = { kind: "remote" as const, transport: "computer" as const, environmentId: "shared-computer",
|
||||
remoteCwd: `/home/user/${name}`, listenerPort: suffix === "a" ? 45001 : 45002,
|
||||
resourceAuthority: { kind: "computer-owner", computerId: "computer", ownerId: name, generation: 1 },
|
||||
@@ -7731,7 +7731,7 @@ describe("native warm session supervision", () => {
|
||||
const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, agentId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1;
|
||||
const firstClose = vi.fn(async () => undefined), secondClose = vi.fn(async () => undefined);
|
||||
const firstRetire = vi.fn(async () => true), secondRetire = vi.fn(async () => true);
|
||||
const firstRetire = vi.fn(async (options?: { beforeStop?: () => Promise<void> }) => { await options?.beforeStop?.(); return true; }), secondRetire = vi.fn(async (options?: { beforeStop?: () => Promise<void> }) => { await options?.beforeStop?.(); return true; });
|
||||
const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: `/home/user/${name}`,
|
||||
resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: "prior-owner", generation: 1 },
|
||||
retainWarm: vi.fn(async () => undefined), retire: firstRetire };
|
||||
@@ -7768,7 +7768,7 @@ describe("native warm session supervision", () => {
|
||||
const detachControllerForRestart = vi.fn(async () => undefined);
|
||||
const session = { close, detachControllerForRestart };
|
||||
let generation = 1;
|
||||
const retire = vi.fn(async () => generation === 1);
|
||||
const retire = vi.fn(async (options?: { beforeStop?: () => Promise<void> }) => { if (generation !== 1) return false; await options?.beforeStop?.(); return true; });
|
||||
const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: `/home/user/${name}`,
|
||||
resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 },
|
||||
retainWarm: vi.fn(async () => undefined), retire };
|
||||
@@ -7796,14 +7796,14 @@ describe("native warm session supervision", () => {
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
expect(detachControllerForRestart).not.toHaveBeenCalled();
|
||||
const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } };
|
||||
const nextRetire = vi.fn(async () => true);
|
||||
const nextRetire = vi.fn(async (options?: { beforeStop?: () => Promise<void> }) => { await options?.beforeStop?.(); return true; });
|
||||
await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: name,
|
||||
runnerEnvironment: await environmentForRun(next.binding.runId),
|
||||
runnerExecutionTarget: { ...target, resourceAuthority: { ...target.resourceAuthority, generation: 2 }, retire: nextRetire } as never });
|
||||
await closeWarmNativeSessionsForRun({ runId: next.binding.runId, reason: "fixture cleanup" });
|
||||
expect(nextRetire).toHaveBeenCalledOnce();
|
||||
expect(detachControllerForRestart).toHaveBeenCalledOnce();
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
expect(detachControllerForRestart).not.toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
@@ -13512,6 +13512,49 @@ describe("runnerd provider runtime wiring", () => {
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it("keeps computer checkpoints remote through close and the next session preparation", async () => {
|
||||
const remoteRoot = "/remote/persistent-agent";
|
||||
const runnerId = "persistent-computer-runner";
|
||||
const runnerState = { schema: "paperclip.runner.durable.state.v1", lifecycle: "suspended", runnerInstanceId: runnerId,
|
||||
normalizedSessionId: execution.session.normalizedSessionId, runId: execution.binding.runId };
|
||||
const providerState = { schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "session_open", threadId: "durable-thread",
|
||||
activeProviderTurnId: null, config: { provider: "codex", driver: "codex_app_server" } };
|
||||
const syncOut = vi.fn(async () => { throw new Error("persistent checkpoint must not copy back"); });
|
||||
const syncIn = vi.fn(async () => { throw new Error("persistent checkpoint must not restore host history"); });
|
||||
const remoteExecute = vi.fn(async (command: { command: string; args?: string[] }) => {
|
||||
const script = command.args?.[1] ?? "";
|
||||
let stdout = "";
|
||||
if (command.args?.[0] === "--build-metadata") stdout = JSON.stringify({
|
||||
schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", packageName: "@paperclipai/paperclip-runner",
|
||||
binaryContractVersion: 2, durableSessionCapabilities: ["unlimited_runtime", "connection_lease_renewal"], prpTransportModes: ["listen_ws"],
|
||||
});
|
||||
else if (command.args?.[0] === "--version") stdout = "codex-cli 0.160.0";
|
||||
else if (script.includes("command -v paperclip-runnerd")) stdout = "/usr/bin/paperclip-runnerd\n";
|
||||
else if (script.includes("command -v codex")) stdout = "/usr/bin/codex\n";
|
||||
else if (script.includes("base64 <")) stdout = Buffer.from(JSON.stringify(script.endsWith("codex-provider-state.json'") ? providerState : runnerState)).toString("base64");
|
||||
if (script.includes("tar ")) throw new Error("persistent checkpoint must not archive");
|
||||
return { exitCode: 0, timedOut: false, signal: null, stdout, stderr: "" };
|
||||
});
|
||||
const target = { kind: "remote", transport: "computer", environmentId: "environment", leaseId: "lease", providerKey: "boat",
|
||||
remoteCwd: remoteRoot, listenerPort: 43127, effectiveCapabilities: { runnerWebSocketIngress: true },
|
||||
fileAuthority: { kind: "remote-persistent", root: remoteRoot, agentHome: remoteRoot, placementId: "placement" },
|
||||
runner: { execute: remoteExecute, syncIn, syncOut }, processRunner: { execute: remoteExecute, syncIn, syncOut },
|
||||
getRunnerIngressEndpoint: async () => ({ url: "wss://example.test/runner", close: async () => undefined }) };
|
||||
await createRunnerdBackend({ db: leaseDb(execution), execution, runnerInstanceId: runnerId,
|
||||
runnerIngressAuthorized: true, runnerExecutionTarget: target as never });
|
||||
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
|
||||
const transport = state.createTransport.mock.calls.at(-1)![0] as RunnerTransportOptions & {
|
||||
controlPlaneRegistration: (authority: unknown) => Promise<{ checkpoint: (settlement: string) => Promise<void> }>;
|
||||
prepareExternalRunnerState: () => Promise<void>;
|
||||
};
|
||||
const registration = await transport.controlPlaneRegistration({});
|
||||
await expect(registration.checkpoint("settled")).resolves.toBeUndefined();
|
||||
expect(remoteExecute.mock.calls.some(([command]) => command.args?.[1]?.endsWith("codex-provider-state.json'"))).toBe(true);
|
||||
await expect(transport.prepareExternalRunnerState()).resolves.toBeUndefined();
|
||||
expect(syncOut).not.toHaveBeenCalled(); expect(syncIn).not.toHaveBeenCalled();
|
||||
await expect(access(join(transport.stateDirectory!, "failover-backups", "current"))).rejects.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ override: undefined, expected: "@openai/codex@0.160.0" },
|
||||
{ override: "@openai/codex@0.159.0", expected: "@openai/codex@0.159.0" },
|
||||
@@ -13792,3 +13835,145 @@ describe("computer provider-pack bootstrap policy", () => {
|
||||
expect(nativeSessionBootstrapTimeoutMs(provider, target)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computer idle authority transition", () => {
|
||||
function settled() {
|
||||
const identity = { runId: execution.binding.runId, normalizedSessionId: execution.session.normalizedSessionId!,
|
||||
runnerInstanceId: "prior-runner", environmentLeaseId: "prior-lease", turnId: "turn", itemId: "item" };
|
||||
const current = { ...execution, binding: { ...execution.binding, runId: "next-run" } };
|
||||
const checkpoint = { driverKind: "codex_app_server", providerSessionId: "thread", activeTurnId: null,
|
||||
pendingRuntimeRequests: [], identity: { ...execution.binding, sessionId: execution.session.normalizedSessionId } };
|
||||
return { identity, execution: current, priorExecution: execution,
|
||||
runner: { schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "ready", outbox: [], pendingTerminalDelivery: null },
|
||||
control: { identity, commands: [{ status: "completed" }], committedEvents: [{ eventType: "run.terminal", envelope: identity }] },
|
||||
provider: { schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "session_open", threadId: "thread",
|
||||
config: { provider: "codex", driver: "codex_app_server" }, activeProviderTurnId: null, completedTurnAuthoritative: true },
|
||||
checkpoint, currentCheckpoint: { ...checkpoint, identity: { ...checkpoint.identity, runId: current.binding.runId } } };
|
||||
}
|
||||
|
||||
it("requires a terminal provider checkpoint with matching prior and successor scope", () => {
|
||||
expect(retiredComputerCheckpointIsSettled(settled())).toBe(true);
|
||||
});
|
||||
it.each(["pending-command", "pending-event", "unsettled-provider", "wrong-run", "wrong-thread", "active-turn", "config-change", "acpx"])(
|
||||
"does not manufacture suspension from %s evidence", (condition) => {
|
||||
const input = settled();
|
||||
if (condition === "pending-command") input.control.commands[0]!.status = "pending";
|
||||
if (condition === "pending-event") (input.runner.outbox as unknown[]).push({ event: "unacked" });
|
||||
if (condition === "unsettled-provider") input.provider.completedTurnAuthoritative = false;
|
||||
if (condition === "wrong-run") input.currentCheckpoint.identity.runId = "foreign";
|
||||
if (condition === "wrong-thread") input.currentCheckpoint.providerSessionId = "foreign";
|
||||
if (condition === "active-turn") Object.assign(input.currentCheckpoint, { activeTurnId: "active" });
|
||||
if (condition === "config-change") input.execution = { ...input.execution, provider: { ...input.execution.provider, model: "changed" } };
|
||||
if (condition === "acpx") input.execution = { ...input.execution, provider: { ...input.execution.provider, kind: "acpx" } } as typeof input.execution;
|
||||
expect(retiredComputerCheckpointIsSettled(input)).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["unchanged", "runner-changed", "provider-changed", "symlink", "interrupted"])(
|
||||
"atomically seals only the unchanged remote bytes (%s)", async (condition) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "computer-retired-cas-"));
|
||||
const runnerPath = join(root, "runner.json"), providerPath = join(root, "provider.json");
|
||||
const runnerBytes = Buffer.from(JSON.stringify(settled().runner)), providerBytes = Buffer.from(JSON.stringify(settled().provider));
|
||||
await writeFile(runnerPath, runnerBytes); await writeFile(providerPath, providerBytes);
|
||||
const runner = { execute: async (command: { command: string; args?: string[] }) => {
|
||||
if (condition === "runner-changed") await writeFile(runnerPath, JSON.stringify({ lifecycle: "active" }));
|
||||
if (condition === "provider-changed") await writeFile(providerPath, JSON.stringify({ activeTurn: "new" }));
|
||||
if (condition === "symlink") { await rm(runnerPath); await symlink(providerPath, runnerPath); }
|
||||
if (condition === "interrupted") return { exitCode: null, signal: "SIGTERM", timedOut: true, stdout: "", stderr: "" };
|
||||
try { return { exitCode: 0, signal: null, timedOut: false, stderr: "", stdout: execFileSync(command.command, command.args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
|
||||
catch { return { exitCode: 1, signal: null, timedOut: false, stdout: "", stderr: "CAS refused" }; }
|
||||
} };
|
||||
try {
|
||||
const action = compareAndSealRetiredComputerCheckpoint({ runner: runner as never, runnerPath, providerPath, runnerBytes, providerBytes });
|
||||
if (condition === "unchanged") {
|
||||
await expect(action).resolves.toBeUndefined();
|
||||
expect(JSON.parse(await readFile(runnerPath, "utf8"))).toEqual({ ...settled().runner, lifecycle: "suspended" });
|
||||
} else {
|
||||
await expect(action).rejects.toThrow("runner_remote_retirement_checkpoint_cas_failed");
|
||||
expect(JSON.parse(await readFile(runnerPath, "utf8")).lifecycle).not.toBe("suspended");
|
||||
}
|
||||
expect((await readdir(root)).filter(name => name.startsWith(".retired-checkpoint-"))).toEqual([]);
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it.each(["unlaunched", "launched", "claimed", "unknown", "superseded"])(
|
||||
"permits same-run admission retry only after exact prelaunch retirement (%s)", async condition => {
|
||||
let active = true;
|
||||
const retire = vi.fn(async () => { if (condition === "superseded") return false; active = false; return true; });
|
||||
const inspectProcess = vi.fn(async () => {
|
||||
if (condition === "unknown") throw new Error("inspection unavailable");
|
||||
return { running: false, claim: condition === "claimed" ? { nonce: "prior-process" } : null };
|
||||
});
|
||||
const target = { kind: "remote", transport: "computer", inspectProcess, retire } as never;
|
||||
const action = retireUnlaunchedComputerAttempt(target, condition === "launched");
|
||||
if (["unknown", "superseded"].includes(condition)) await expect(action).rejects.toThrow();
|
||||
else await expect(action).resolves.toBeUndefined();
|
||||
const admitSameRun = () => { if (active) throw new Error("Computer session already has an active turn"); };
|
||||
if (condition === "unlaunched") expect(admitSameRun).not.toThrow();
|
||||
else expect(admitSameRun).toThrow("active turn");
|
||||
if (["launched", "claimed", "unknown"].includes(condition)) expect(retire).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("computer graceful idle reservation", () => {
|
||||
it.each(["codex", "acpx"])("suspends %s before retiring descendants and admits the next idle turn", async kind => {
|
||||
const name = `graceful-idle-${kind}`;
|
||||
const current = { ...execution, binding: { ...execution.binding, runId: `${name}-one`, agentId: name },
|
||||
provider: kind === "codex" ? execution.provider : { kind: "acpx", agent: "claude", model: null },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1;
|
||||
let phase = "active";
|
||||
let checkpoint = "ready";
|
||||
const close = vi.fn(async () => { expect(phase).toBe("retiring"); checkpoint = "suspended"; });
|
||||
const target = { kind: "remote", transport: "computer", environmentId: name, remoteCwd: "/remote/agent",
|
||||
resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 },
|
||||
retainWarm: async () => { phase = "warm"; },
|
||||
retire: vi.fn(async (options?: { beforeStop?: () => Promise<void> }) => {
|
||||
phase = "retiring";
|
||||
await options?.beforeStop?.();
|
||||
expect(checkpoint).toBe("suspended");
|
||||
phase = "retired";
|
||||
return true;
|
||||
}) };
|
||||
const result = { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: name,
|
||||
normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", nativeEventCount: 1,
|
||||
highestContiguousSourceSeq: 1, usage: null };
|
||||
state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.({ close }); return result; })
|
||||
.mockImplementationOnce(async options => { expect(options.existingSession).toBeUndefined(); expect(checkpoint).toBe("suspended"); return result; });
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
try {
|
||||
await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name, runnerExecutionTarget: target as never });
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(phase).toBe("retired"); expect(close).toHaveBeenCalledOnce();
|
||||
const next = { ...current, binding: { ...current.binding, runId: `${name}-two` } };
|
||||
await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: `${name}-fresh`,
|
||||
runnerExecutionTarget: { ...target, resourceAuthority: { ...target.resourceAuthority, ownerId: "new-owner" } } as never });
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it.each(["failed-close", "expired-reservation", "superseded"])("does not report clean close when %s", async condition => {
|
||||
const name = `graceful-${condition}`;
|
||||
const current = { ...execution, binding: { ...execution.binding, runId: name, agentId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 } } } as NativeExecutionInputV1;
|
||||
const close = vi.fn(async () => { throw new Error("protocol close failed"); });
|
||||
const detach = vi.fn(async () => undefined);
|
||||
let retired = false;
|
||||
const retire = vi.fn(async (options?: { beforeStop?: () => Promise<void> }) => {
|
||||
if (condition === "superseded") return false;
|
||||
if (condition === "failed-close") await options?.beforeStop?.().catch(() => undefined);
|
||||
retired = true;
|
||||
return true;
|
||||
});
|
||||
state.execute.mockReset().mockImplementationOnce(async options => { await options.onSession?.({ close, detachControllerForRestart: detach });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, turnId: name,
|
||||
normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1", nativeEventCount: 1,
|
||||
highestContiguousSourceSeq: 1, usage: null }; });
|
||||
await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name,
|
||||
runnerExecutionTarget: { kind: "remote", transport: "computer", environmentId: name, remoteCwd: "/remote/agent",
|
||||
resourceAuthority: { kind: "computer-owner", computerId: name, ownerId: name, generation: 1 },
|
||||
retainWarm: async () => undefined, retire } as never });
|
||||
const result = await closeWarmNativeSessionsForRun({ runId: name, reason: "cancel exact task" });
|
||||
expect(result.failed).toBe(1);
|
||||
expect(retired).toBe(condition !== "superseded");
|
||||
if (condition === "superseded") { expect(close).not.toHaveBeenCalled(); expect(detach).not.toHaveBeenCalled(); }
|
||||
else expect(detach).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -473,35 +473,51 @@ type WarmNativeSession = {
|
||||
lastActivityAt: string;
|
||||
};
|
||||
|
||||
/** A scoped preparation failure is retryable only after exact retirement fences
|
||||
* queued commands. A process claim or invoked launcher keeps normal recovery. */
|
||||
export async function retireUnlaunchedComputerAttempt(
|
||||
target: AdapterExecutionTarget | null | undefined,
|
||||
launchAttempted: boolean,
|
||||
): Promise<void> {
|
||||
if (target?.kind !== "remote" || target.transport !== "computer" || launchAttempted) return;
|
||||
const process = await target.inspectProcess();
|
||||
if (process.running || process.claim !== null) return;
|
||||
if (!(await target.retire())) throw new NativeSessionCleanupQuarantinedError();
|
||||
}
|
||||
|
||||
class ComputerOwnerSupersededError extends Error {
|
||||
constructor() { super("computer_owner_retirement_superseded"); }
|
||||
}
|
||||
|
||||
async function closeWarmNativeSession(entry: WarmNativeSession, reason: string, preserveInstructionsForRunId?: string) {
|
||||
// Computer admission can advance while an old idle timer is firing. Only
|
||||
// the exact durable owner may stop the runner or its controller transport.
|
||||
if (entry.computerTarget && !(await entry.computerTarget.retire())) {
|
||||
let closeFailure: unknown;
|
||||
let closeCompleted = false;
|
||||
const close = async () => {
|
||||
try { await entry.session.close({ reason }); closeCompleted = true; }
|
||||
catch (error) { closeFailure = error; throw error; }
|
||||
};
|
||||
// Reserve the exact generation before protocol close. A winning admission
|
||||
// must never receive a stale controller's suspend/kill command. The module
|
||||
// always hard-retires descendants after the bounded graceful window.
|
||||
if (entry.computerTarget && !(await entry.computerTarget.retire({ beforeStop: close }))) {
|
||||
throw new ComputerOwnerSupersededError();
|
||||
}
|
||||
// Revoke before awaiting process retirement/checkpoint IO.
|
||||
const stopping = entry.githubAccess?.stop();
|
||||
try {
|
||||
try {
|
||||
if (entry.computerTarget && entry.session.detachControllerForRestart) {
|
||||
await entry.session.detachControllerForRestart();
|
||||
} else {
|
||||
await entry.session.close({ reason });
|
||||
if (!entry.computerTarget) await close();
|
||||
if (closeFailure || !closeCompleted) {
|
||||
await entry.session.detachControllerForRestart?.();
|
||||
throw closeFailure ?? new NativeSessionCleanupQuarantinedError();
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
} catch (error) {
|
||||
try { await entry.instructionWorkingCopy?.retirementFailed?.(); }
|
||||
catch (receiptError) { throw new AggregateError([error, receiptError], "Warm instruction retirement and receipt both failed"); }
|
||||
throw error;
|
||||
}
|
||||
await entry.instructionWorkingCopy?.collectStopped();
|
||||
if (entry.instructionCopy?.runId !== preserveInstructionsForRunId) await entry.instructionCopy?.collectStopped();
|
||||
}
|
||||
finally { await stopping; }
|
||||
} finally { await stopping; }
|
||||
}
|
||||
|
||||
const warmNativeSessions = new Map<string, WarmNativeSession>();
|
||||
@@ -8746,6 +8762,8 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
},
|
||||
}
|
||||
: input.execution;
|
||||
let remoteLaunchAttempted = false;
|
||||
let remoteBackendPreparationStarted = false;
|
||||
const leaseRenewal = startNativeSessionExecutionLeaseRenewal({
|
||||
db: input.db,
|
||||
runId: input.execution.binding.runId,
|
||||
@@ -8773,6 +8791,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
input.db,
|
||||
input.execution.binding,
|
||||
);
|
||||
remoteBackendPreparationStarted = input.useRunnerd === true && input.backend === undefined;
|
||||
const runnerdBackend =
|
||||
input.useRunnerd && input.backend === undefined
|
||||
? await createRunnerdBackend({
|
||||
@@ -8783,6 +8802,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
execution: input.execution,
|
||||
runnerInstanceId: effectiveRunnerInstanceId,
|
||||
durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId,
|
||||
onRemoteLaunchAttempt: () => { remoteLaunchAttempted = true; },
|
||||
trace,
|
||||
toolTrace,
|
||||
})
|
||||
@@ -9168,6 +9188,15 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
// with a retry or release the still-live runner's lease.
|
||||
throw new NativeControllerDetachedForRestartError();
|
||||
}
|
||||
if (remoteBackendPreparationStarted) {
|
||||
try {
|
||||
await retireUnlaunchedComputerAttempt(input.runnerExecutionTarget, remoteLaunchAttempted);
|
||||
} catch {
|
||||
// Failure to establish the exact tombstone leaves queued commands or
|
||||
// a lost launch acknowledgement ambiguous. Never retry that owner.
|
||||
error = new NativeSessionCleanupQuarantinedError();
|
||||
}
|
||||
}
|
||||
const protocolIntegrityFailure =
|
||||
error instanceof NativeSessionProtocolIntegrityError ? error : null;
|
||||
const ownershipUnverified =
|
||||
@@ -10823,6 +10852,134 @@ export async function syncRemoteRunnerDirectoryOut(input: {
|
||||
}
|
||||
}
|
||||
|
||||
/** A dead computer runner may retain a ready checkpoint after controller loss.
|
||||
* Match the local quiescent-recovery proof before sealing it for normal rotation.
|
||||
*/
|
||||
export function retiredComputerCheckpointIsSettled(input: {
|
||||
execution: NativeExecutionInput;
|
||||
priorExecution: NativeExecutionInput;
|
||||
identity: RunnerdDurableIdentity;
|
||||
runner: Record<string, unknown>;
|
||||
control: Record<string, unknown>;
|
||||
provider: Record<string, unknown>;
|
||||
checkpoint: Record<string, unknown>;
|
||||
currentCheckpoint: Record<string, unknown>;
|
||||
}): boolean {
|
||||
const { execution, priorExecution, identity, runner, control, provider, checkpoint, currentCheckpoint } = input;
|
||||
if (execution.provider.kind !== "codex" || priorExecution.provider.kind !== "codex") return false;
|
||||
const events = control.committedEvents;
|
||||
const commands = control.commands;
|
||||
const terminal = record(record(Array.isArray(events) ? events.at(-1) : null).envelope);
|
||||
const fields = ["runId", "normalizedSessionId", "runnerInstanceId", "environmentLeaseId", "turnId", "itemId"] as const;
|
||||
if (runner.schema !== RUNNERD_STATE_SCHEMA || runner.lifecycle !== "ready" ||
|
||||
fields.some(key => runner[key] !== identity[key] || record(control.identity)[key] !== identity[key]) ||
|
||||
!Array.isArray(runner.outbox) || runner.outbox.length !== 0 || runner.pendingTerminalDelivery !== null ||
|
||||
!Array.isArray(commands) || commands.some(command => record(command).status !== "completed") ||
|
||||
!Array.isArray(events) || record(events.at(-1)).eventType !== "run.terminal" ||
|
||||
terminal.runId !== identity.runId || terminal.normalizedSessionId !== identity.normalizedSessionId ||
|
||||
provider.completedTurnAuthoritative !== true || priorExecution.binding.runId !== identity.runId ||
|
||||
priorExecution.binding.issueId !== execution.binding.issueId ||
|
||||
nativeSessionScopeKey(priorExecution) !== nativeSessionScopeKey(execution) ||
|
||||
nativeSessionConfigDigest(priorExecution) !== nativeSessionConfigDigest(execution)) return false;
|
||||
const providerIdentity = providerSessionIdentityFromDurableProviderState({ execution: priorExecution, providerState: provider });
|
||||
if (!providerIdentity.providerSessionId) return false;
|
||||
return [checkpoint, currentCheckpoint].every((value, index) => {
|
||||
const binding = record(value.identity);
|
||||
return value.providerSessionId === providerIdentity.providerSessionId &&
|
||||
value.driverKind === priorExecution.session.driverKind && value.activeTurnId === null &&
|
||||
Array.isArray(value.pendingRuntimeRequests) && value.pendingRuntimeRequests.length === 0 &&
|
||||
binding.runId === (index === 0 ? identity.runId : execution.binding.runId) &&
|
||||
binding.sessionId === identity.normalizedSessionId && binding.companyId === execution.binding.companyId &&
|
||||
binding.agentId === execution.binding.agentId && binding.issueId === execution.binding.issueId;
|
||||
});
|
||||
}
|
||||
|
||||
async function sealRetiredComputerRunnerState(input: {
|
||||
db: Db; execution: NativeExecutionInput; root: string;
|
||||
target: Extract<AdapterExecutionTarget, { transport: "computer" }>;
|
||||
runner: CommandManagedRuntimeRunner; stateDirectory: string;
|
||||
}): Promise<void> {
|
||||
const identity = readRunnerdDurableIdentity(input.root);
|
||||
if (!identity || identity.runId === input.execution.binding.runId || input.execution.provider.kind !== "codex") return;
|
||||
if (!durableIdentityMatchesSession(identity, input.execution)) throw new Error("runner_remote_retirement_scope_mismatch");
|
||||
const controlPath = resolve(input.root, "control-plane", "control-plane-state.json");
|
||||
const controlBytes = readBoundedNativeFile(controlPath, NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "recovery_state_too_large");
|
||||
const runnerPath = posix.join(input.stateDirectory, "runner-state.json");
|
||||
const providerPath = posix.join(input.stateDirectory, runnerProviderStateFilename(input.execution));
|
||||
const read = await input.runner.execute({ command: "python3", args: ["-c", String.raw`
|
||||
import sys,os,stat,json,base64
|
||||
rows=[]
|
||||
for p in sys.argv[1:]:
|
||||
s=os.lstat(p)
|
||||
if not stat.S_ISREG(s.st_mode) or s.st_size>16777216:raise RuntimeError('unsafe recovery state')
|
||||
with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:data=f.read(16777217)
|
||||
if len(data)>16777216:raise RuntimeError('unsafe recovery state')
|
||||
rows.append(base64.b64encode(data).decode())
|
||||
print(json.dumps(rows))`, runnerPath, providerPath], bypassSession: true, timeoutMs: 10_000 });
|
||||
if (read.exitCode !== 0 || read.timedOut) throw new Error("runner_remote_retirement_state_unavailable");
|
||||
const [runnerBytes, providerBytes] = (JSON.parse(read.stdout) as string[]).map(value => Buffer.from(value, "base64"));
|
||||
const runner = record(JSON.parse(runnerBytes!.toString("utf8")));
|
||||
if (runner.lifecycle === "suspended") return;
|
||||
const runs = await input.db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, runnerProfileJson: heartbeatRuns.runnerProfileJson })
|
||||
.from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.execution.binding.companyId),
|
||||
eq(heartbeatRuns.agentId, input.execution.binding.agentId),
|
||||
inArray(heartbeatRuns.id, [identity.runId, input.execution.binding.runId])));
|
||||
const prior = runs.find(run => run.id === identity.runId);
|
||||
const current = runs.find(run => run.id === input.execution.binding.runId);
|
||||
if (!prior || !current || !TERMINAL_HEARTBEAT_RUN_STATUSES.has(prior.status))
|
||||
throw new Error("runner_remote_retirement_authority_unverified");
|
||||
const profile = record(prior.runnerProfileJson);
|
||||
const previous = parseNativeExecutionInput(profile.nativeExecutionInput);
|
||||
if (!retiredComputerCheckpointIsSettled({ execution: input.execution, priorExecution: previous, identity, runner,
|
||||
control: record(JSON.parse(controlBytes.toString("utf8"))), provider: record(JSON.parse(providerBytes!.toString("utf8"))),
|
||||
checkpoint: record(profile.sessionCheckpoint), currentCheckpoint: record(record(current.runnerProfileJson).sessionCheckpoint) }) ||
|
||||
await verifyPriorRunnerdStateForSessionScope({ db: input.db, root: input.root, identity, execution: input.execution,
|
||||
allowVerifiedBackup: false, allowRetainedWarmRunner: false, remoteRunnerState: true, runnerExecutionTarget: input.target }) !== "verified")
|
||||
throw new Error("runner_remote_retirement_checkpoint_unsettled");
|
||||
// Recheck exact durable retirement after all awaited reads; never infer death
|
||||
// from a missing PID or turn status. The compare-and-swap preserves ambiguity.
|
||||
const workspace = readNativeComputerWorkspaceReference(profile.nativeComputerWorkspace);
|
||||
if (!workspace || !input.target.environmentId || !(await computerService(input.db).isRetired({
|
||||
companyId: input.execution.binding.companyId, environmentId: input.target.environmentId,
|
||||
owner: workspace.computerOwner, agentId: input.execution.binding.agentId, runId: identity.runId,
|
||||
})) || !controlBytes.equals(readBoundedNativeFile(controlPath, NATIVE_CONTROL_PLANE_STATE_MAX_BYTES, "recovery_state_too_large")))
|
||||
throw new Error("runner_remote_retirement_evidence_changed");
|
||||
await compareAndSealRetiredComputerCheckpoint({ runner: input.runner, runnerPath, providerPath,
|
||||
runnerBytes: runnerBytes!, providerBytes: providerBytes! });
|
||||
}
|
||||
|
||||
/** Exact retirement is checked by the caller; publication must still compare
|
||||
* the complete bytes so a changed or interrupted checkpoint is never rotated. */
|
||||
export async function compareAndSealRetiredComputerCheckpoint(input: {
|
||||
runner: CommandManagedRuntimeRunner; runnerPath: string; providerPath: string;
|
||||
runnerBytes: Buffer; providerBytes: Buffer;
|
||||
}): Promise<void> {
|
||||
const result = await input.runner.execute({ command: "python3", args: ["-c", String.raw`
|
||||
import sys,os,stat,json,hashlib,tempfile
|
||||
runner,provider,expected_runner,expected_provider=sys.argv[1:]
|
||||
for p,digest in [(runner,expected_runner),(provider,expected_provider)]:
|
||||
s=os.lstat(p)
|
||||
if not stat.S_ISREG(s.st_mode) or s.st_size>16777216:raise RuntimeError('unsafe recovery state')
|
||||
with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:data=f.read(16777217)
|
||||
if len(data)>16777216:raise RuntimeError('unsafe recovery state')
|
||||
if hashlib.sha256(data).hexdigest()!=digest:raise RuntimeError('recovery evidence changed')
|
||||
if p==runner:state=json.loads(data)
|
||||
state['lifecycle']='suspended'
|
||||
fd,tmp=tempfile.mkstemp(prefix='.retired-checkpoint-',dir=os.path.dirname(runner))
|
||||
try:
|
||||
with os.fdopen(fd,'w') as f:json.dump(state,f,separators=(',',':'));f.flush();os.fsync(f.fileno())
|
||||
# Recheck immediately before publication, including the provider checkpoint.
|
||||
for p,digest in [(runner,expected_runner),(provider,expected_provider)]:
|
||||
with os.fdopen(os.open(p,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:current=f.read(16777217)
|
||||
if hashlib.sha256(current).hexdigest()!=digest:raise RuntimeError('recovery evidence changed')
|
||||
os.replace(tmp,runner)
|
||||
finally:
|
||||
if os.path.exists(tmp):os.unlink(tmp)
|
||||
`, input.runnerPath, input.providerPath, createHash("sha256").update(input.runnerBytes).digest("hex"), createHash("sha256").update(input.providerBytes).digest("hex")],
|
||||
bypassSession: true, timeoutMs: 10_000 });
|
||||
if (result.exitCode !== 0 || result.timedOut) throw new Error("runner_remote_retirement_checkpoint_cas_failed");
|
||||
}
|
||||
|
||||
async function readRemoteRunnerState(input: {
|
||||
runner: CommandManagedRuntimeRunner;
|
||||
stateDirectory: string;
|
||||
@@ -11100,9 +11257,11 @@ export function createRemoteRunnerProcessLauncher(input: {
|
||||
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
|
||||
trace?: NativeRunTrace;
|
||||
onRunnerProcessSpawned?: () => void;
|
||||
onLaunchAttempt?: () => void;
|
||||
}): (spec: RunnerProcessLaunchSpec) => RunnerProcessHandle {
|
||||
const runner = input.runner;
|
||||
return (spec) => {
|
||||
input.onLaunchAttempt?.();
|
||||
let launchedIdentity: {
|
||||
nonce: string;
|
||||
pid: number;
|
||||
@@ -11404,6 +11563,7 @@ export async function createRunnerdBackend(input: {
|
||||
chatAttachmentReadScope?: NativeChatAttachmentReadScope;
|
||||
restartRecovery?: NativeRestartRecoveryClaim;
|
||||
durableEnvironmentLeaseId?: string;
|
||||
onRemoteLaunchAttempt?: () => void;
|
||||
onSpawn?: (meta: {
|
||||
pid: number;
|
||||
processGroupId: number | null;
|
||||
@@ -13064,6 +13224,10 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
if (incompleteFailure) throw incompleteFailure;
|
||||
return;
|
||||
}
|
||||
// The computer ledger and exact remote placement are the recovery authority.
|
||||
// Its durable provider state stays on the persistent machine; importing the
|
||||
// sandbox archive would create a second authority and delay bounded shutdown.
|
||||
if (remoteTarget?.transport === "computer") return;
|
||||
const backupSpanAttributes = {
|
||||
provider: input.execution.provider.kind,
|
||||
harness: input.execution.session.driverKind,
|
||||
@@ -13207,6 +13371,10 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
runnerIngressAuthorized: input.runnerIngressAuthorized === true,
|
||||
});
|
||||
await ensureRemoteRunner(false);
|
||||
if (remoteTarget.transport === "computer" && remoteStateDirectory) {
|
||||
await sealRetiredComputerRunnerState({ db: input.db, execution: input.execution, root,
|
||||
target: remoteTarget, runner: remoteCommandRunner, stateDirectory: remoteStateDirectory });
|
||||
}
|
||||
}
|
||||
: undefined;
|
||||
const archiveExternalRunnerState =
|
||||
@@ -13277,6 +13445,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
onLog: input.onLog,
|
||||
trace: input.trace,
|
||||
onRunnerProcessSpawned: () => resolveRemoteRunnerProcessSpawned?.(),
|
||||
onLaunchAttempt: input.onRemoteLaunchAttempt,
|
||||
})
|
||||
: undefined;
|
||||
const runnerExecution: NativeExecutionInput = remoteTarget
|
||||
|
||||
Reference in new issue
Block a user