@staix/agent-research 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +107 -0
- package/README.md +255 -24
- package/package.json +2 -2
- package/src/cli.ts +117 -10
- package/src/commands-table.ts +39 -8
- package/src/commands.ts +192 -32
- package/src/exp/attempts.ts +500 -65
- package/src/exp/executor.ts +235 -12
- package/src/exp/final.ts +1 -1
- package/src/exp/logs.ts +25 -12
- package/src/exp/metrics.ts +6 -5
- package/src/exp/pipeline.ts +92 -0
- package/src/exp/protocol.ts +85 -18
- package/src/exp/retention-script.ts +649 -0
- package/src/exp/retention.ts +70 -0
- package/src/exp/reuse-admission.ts +63 -0
- package/src/exp/reuse-contract.ts +48 -0
- package/src/exp/reuse-runtime.ts +87 -0
- package/src/exp/reuse.ts +87 -0
- package/src/exp/selection.ts +1 -1
- package/src/exp/snapshot.ts +3 -3
- package/src/exp/stages.ts +117 -0
- package/src/harness/experience-source.ts +34 -0
- package/src/harness/experience.ts +206 -0
- package/src/harness/hub-guidance.ts +140 -0
- package/src/harness/hub-reference.ts +18 -0
- package/src/harness/lesson-candidates.ts +162 -0
- package/src/harness/limits.ts +2 -0
- package/src/harness/privacy.ts +4 -0
- package/src/harness/receipts.ts +84 -0
- package/src/harness/rounds.ts +198 -0
- package/src/harness/transitions.ts +152 -0
- package/src/lit/candidates.ts +13 -5
- package/src/lit/cards.ts +55 -4
- package/src/lit/flow.ts +82 -0
- package/src/lit/queries.ts +62 -0
- package/src/manifest.ts +13 -6
- package/src/mcp-tools.ts +123 -25
- package/src/mcp.ts +4 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +17 -8
- package/src/memory/evidence-local.ts +77 -0
- package/src/memory/evidence.ts +39 -0
- package/src/memory/lessons.ts +4 -2
- package/src/memory/skill-check.ts +56 -0
- package/src/memory/skill-format.ts +77 -0
- package/src/memory/skills.ts +72 -26
- package/src/memory/source-budget.ts +11 -0
- package/src/memory/vault-cards.ts +226 -0
- package/src/paper/build.ts +16 -7
- package/src/paper/check.ts +37 -10
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +16 -1
- package/src/paper/plan.ts +170 -0
- package/src/paper/point-evidence.ts +63 -0
- package/src/paper/points.ts +83 -0
- package/src/paper/review.ts +102 -9
- package/src/paper/scopes.ts +51 -0
- package/src/plan/definition.ts +5 -1
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +5 -0
- package/src/playbook.ts +35 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +55 -27
- package/src/study.ts +54 -14
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +263 -6
- package/src/ui/plugin.ts +68 -10
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
/** Isolated executor program: receives one bounded request, never emits payload bytes or host paths. */
|
|
2
|
+
export const RETENTION_SCRIPT = String.raw`
|
|
3
|
+
import os,sys,json,re,stat,hashlib,uuid,fcntl,datetime
|
|
4
|
+
MAX_BYTES=256*1024*1024
|
|
5
|
+
MAX_META=256*1024
|
|
6
|
+
MAX_ADMIN=256*1024
|
|
7
|
+
ARCHIVE_BYTES=64*1024
|
|
8
|
+
MAX_FILES=500
|
|
9
|
+
STATE_BYTES=1024*1024
|
|
10
|
+
CAP=1024*1024*1024
|
|
11
|
+
LOOKUP_RECORDS=10000
|
|
12
|
+
LOOKUP_METADATA=4*1024*1024
|
|
13
|
+
|
|
14
|
+
def fail(message):
|
|
15
|
+
raise ValueError(message)
|
|
16
|
+
def encoded(value):
|
|
17
|
+
return json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=True).encode()
|
|
18
|
+
def digest(data):
|
|
19
|
+
return hashlib.sha256(data).hexdigest()
|
|
20
|
+
def ident(value,kind='name'):
|
|
21
|
+
pattern=r'[a-f0-9]{16}' if kind=='attempt' else r'[A-Za-z0-9][A-Za-z0-9_-]{0,79}' if kind=='study' else r'[a-z][a-z0-9_-]{0,31}'
|
|
22
|
+
if not isinstance(value,str) or not re.fullmatch(pattern,value) or value in ('constructor','prototype','__proto__'):
|
|
23
|
+
fail('invalid '+kind+' identity')
|
|
24
|
+
return value
|
|
25
|
+
def hexhash(value):
|
|
26
|
+
if not isinstance(value,str) or not re.fullmatch(r'[a-f0-9]{64}',value): fail('invalid digest identity')
|
|
27
|
+
return value
|
|
28
|
+
def relative(value):
|
|
29
|
+
if not isinstance(value,str) or not value or len(value.encode())>4096 or value.startswith('/') or chr(92) in value or any(ord(c)<32 or ord(c)==127 for c in value) or any(p in ('','.','..') for p in value.split('/')):
|
|
30
|
+
fail('unsafe declared relative path')
|
|
31
|
+
return value
|
|
32
|
+
def stamp(st):
|
|
33
|
+
return (st.st_dev,st.st_ino,st.st_size,st.st_mtime_ns,st.st_ctime_ns,st.st_mode,st.st_nlink)
|
|
34
|
+
def physical(path,private=False):
|
|
35
|
+
if not os.path.isabs(path) or os.path.normpath(path)!=path or os.path.realpath(path)!=path: fail('nonphysical executor directory')
|
|
36
|
+
st=os.lstat(path)
|
|
37
|
+
if not stat.S_ISDIR(st.st_mode) or st.st_uid!=os.getuid() or (private and stat.S_IMODE(st.st_mode)!=0o700): fail('executor directory ownership or mode refused')
|
|
38
|
+
return path
|
|
39
|
+
def mkdir(path):
|
|
40
|
+
try: os.mkdir(path,0o700)
|
|
41
|
+
except FileExistsError: pass
|
|
42
|
+
return physical(path,True)
|
|
43
|
+
def within(path,root):
|
|
44
|
+
if not isinstance(path,str) or not path.startswith(root+'/') or os.path.normpath(path)!=path or os.path.realpath(path)!=path: fail('path escapes attempt workspace')
|
|
45
|
+
parent=os.path.dirname(path)
|
|
46
|
+
physical(parent)
|
|
47
|
+
return path
|
|
48
|
+
def read_bytes(path,bound):
|
|
49
|
+
fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK)
|
|
50
|
+
try:
|
|
51
|
+
before=os.fstat(fd)
|
|
52
|
+
if not stat.S_ISREG(before.st_mode) or before.st_nlink!=1 or before.st_size>bound: fail('nonregular or oversized retained metadata')
|
|
53
|
+
chunks=[]; count=0
|
|
54
|
+
while True:
|
|
55
|
+
chunk=os.read(fd,min(65536,bound-count+1))
|
|
56
|
+
if not chunk: break
|
|
57
|
+
count+=len(chunk)
|
|
58
|
+
if count>bound: fail('retained metadata exceeds bound')
|
|
59
|
+
chunks.append(chunk)
|
|
60
|
+
if stamp(before)!=stamp(os.fstat(fd)): fail('retained metadata changed during read')
|
|
61
|
+
return b''.join(chunks)
|
|
62
|
+
finally: os.close(fd)
|
|
63
|
+
def syncdir(path):
|
|
64
|
+
fd=os.open(path,os.O_RDONLY)
|
|
65
|
+
try: os.fsync(fd)
|
|
66
|
+
finally: os.close(fd)
|
|
67
|
+
def atomic(path,value,bound,pending=None):
|
|
68
|
+
data=encoded(value)
|
|
69
|
+
if len(data)>bound: fail('retention metadata bound exceeded')
|
|
70
|
+
tmp=pending if pending is not None else path+'.'+uuid.uuid4().hex+'.tmp'
|
|
71
|
+
if pending is not None and os.path.lexists(tmp):
|
|
72
|
+
st=os.lstat(tmp)
|
|
73
|
+
if not stat.S_ISREG(st.st_mode) or st.st_nlink!=1 or st.st_uid!=os.getuid() or st.st_size>bound: fail('unsafe interrupted metadata write')
|
|
74
|
+
os.unlink(tmp)
|
|
75
|
+
fd=os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
|
76
|
+
try:
|
|
77
|
+
with os.fdopen(fd,'wb') as f: f.write(data);f.flush();os.fsync(f.fileno())
|
|
78
|
+
os.replace(tmp,path);syncdir(os.path.dirname(path))
|
|
79
|
+
finally:
|
|
80
|
+
if os.path.exists(tmp): os.unlink(tmp)
|
|
81
|
+
def inventory(root,copy_to=None,max_bytes=MAX_BYTES,max_files=MAX_FILES,max_directories=1000,code=False):
|
|
82
|
+
files=[]; directories=[]; count=0; total=0
|
|
83
|
+
def walk(path,rel,depth):
|
|
84
|
+
nonlocal count,total
|
|
85
|
+
if depth>64: fail('artifact nesting exceeds bound')
|
|
86
|
+
before=os.lstat(path)
|
|
87
|
+
if (stat.S_ISLNK(before.st_mode) and not code) or before.st_uid!=os.getuid(): fail('artifact link or ownership refused')
|
|
88
|
+
if stat.S_ISDIR(before.st_mode):
|
|
89
|
+
if len(directories)>=max_directories: fail('artifact directory bound exceeded')
|
|
90
|
+
if rel: directories.append(rel)
|
|
91
|
+
if copy_to is not None and rel: os.mkdir(os.path.join(copy_to,rel),0o700)
|
|
92
|
+
entries=[]
|
|
93
|
+
with os.scandir(path) as stream:
|
|
94
|
+
for entry in stream:
|
|
95
|
+
if len(entries)>=max_files+max_directories: fail('artifact entry bound exceeded')
|
|
96
|
+
entries.append(entry.name)
|
|
97
|
+
for entry in sorted(entries):
|
|
98
|
+
child=entry if not rel else rel+'/'+entry
|
|
99
|
+
if code:
|
|
100
|
+
if len(os.fsencode(child))>4096: fail('code snapshot path bound exceeded')
|
|
101
|
+
else: relative(child)
|
|
102
|
+
walk(os.path.join(path,entry),child,depth+1)
|
|
103
|
+
elif code and stat.S_ISLNK(before.st_mode):
|
|
104
|
+
if count>=max_files: fail('code snapshot entry bound exceeded')
|
|
105
|
+
target=os.fsencode(os.readlink(path));count+=1;total+=len(target)
|
|
106
|
+
if total>max_bytes: fail('code snapshot payload bound exceeded')
|
|
107
|
+
files.append({'path':rel,'bytes':len(target),'sha256':digest(target),'kind':'symlink'})
|
|
108
|
+
elif stat.S_ISREG(before.st_mode):
|
|
109
|
+
if before.st_nlink!=1 or count>=max_files or before.st_size>max_bytes-total: fail('artifact file or payload bound exceeded')
|
|
110
|
+
count+=1; amount=0; h=hashlib.sha256()
|
|
111
|
+
fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK)
|
|
112
|
+
target=None
|
|
113
|
+
try:
|
|
114
|
+
if stamp(os.fstat(fd))!=stamp(before): fail('artifact changed before read')
|
|
115
|
+
if copy_to is not None:
|
|
116
|
+
target=open(os.path.join(copy_to,rel),'xb')
|
|
117
|
+
os.fchmod(target.fileno(),0o400)
|
|
118
|
+
while True:
|
|
119
|
+
chunk=os.read(fd,min(65536,max_bytes-total-amount+1))
|
|
120
|
+
if not chunk: break
|
|
121
|
+
amount+=len(chunk)
|
|
122
|
+
if amount>before.st_size or amount>max_bytes-total: fail('artifact grew during read')
|
|
123
|
+
h.update(chunk)
|
|
124
|
+
if target: target.write(chunk)
|
|
125
|
+
if amount!=before.st_size or stamp(os.fstat(fd))!=stamp(before): fail('artifact changed during read')
|
|
126
|
+
if target: target.flush();os.fsync(target.fileno())
|
|
127
|
+
finally:
|
|
128
|
+
os.close(fd)
|
|
129
|
+
if target: target.close()
|
|
130
|
+
total+=amount;record={'path':rel,'bytes':amount,'sha256':h.hexdigest()}
|
|
131
|
+
if code: record['mode']=stat.S_IMODE(before.st_mode)
|
|
132
|
+
files.append(record)
|
|
133
|
+
else: fail('artifact special file refused')
|
|
134
|
+
if stamp(os.lstat(path))!=stamp(before): fail('artifact changed during verification')
|
|
135
|
+
physical(root)
|
|
136
|
+
walk(root,'',0)
|
|
137
|
+
return sorted(files,key=lambda item:item['path']), sorted(directories),total
|
|
138
|
+
|
|
139
|
+
def bounded_copy(source,target=None):
|
|
140
|
+
st=os.lstat(source)
|
|
141
|
+
if stat.S_ISDIR(st.st_mode):
|
|
142
|
+
if target is not None: os.mkdir(target,0o700)
|
|
143
|
+
return inventory(source,target)
|
|
144
|
+
if not stat.S_ISREG(st.st_mode): fail('input must be a regular file or directory')
|
|
145
|
+
# Reuse the same bounded file copier without accepting siblings.
|
|
146
|
+
parent=os.path.dirname(source); name=os.path.basename(source)
|
|
147
|
+
fd=os.open(source,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK)
|
|
148
|
+
try:
|
|
149
|
+
before=os.fstat(fd)
|
|
150
|
+
if stamp(before)!=stamp(st) or st.st_nlink!=1 or st.st_uid!=os.getuid() or st.st_size>MAX_BYTES: fail('unsafe input file')
|
|
151
|
+
h=hashlib.sha256();size=0
|
|
152
|
+
out=open(target,'xb') if target is not None else None
|
|
153
|
+
try:
|
|
154
|
+
if out: os.fchmod(out.fileno(),0o400)
|
|
155
|
+
while True:
|
|
156
|
+
chunk=os.read(fd,min(65536,MAX_BYTES-size+1))
|
|
157
|
+
if not chunk: break
|
|
158
|
+
size+=len(chunk)
|
|
159
|
+
if size>st.st_size or size>MAX_BYTES: fail('input grew during copy')
|
|
160
|
+
h.update(chunk)
|
|
161
|
+
if out: out.write(chunk)
|
|
162
|
+
if out: out.flush();os.fsync(out.fileno())
|
|
163
|
+
finally:
|
|
164
|
+
if out: out.close()
|
|
165
|
+
if size!=st.st_size or stamp(before)!=stamp(os.fstat(fd)) or stamp(st)!=stamp(os.lstat(source)): fail('input changed during copy')
|
|
166
|
+
return [{'path':'','bytes':size,'sha256':h.hexdigest()}],[],size
|
|
167
|
+
finally: os.close(fd)
|
|
168
|
+
def selected_inventory(root,paths):
|
|
169
|
+
files=[];directories=set();total=0
|
|
170
|
+
for path in paths:
|
|
171
|
+
part,dirs,size=bounded_copy(within(os.path.join(root,path),root))
|
|
172
|
+
total+=size
|
|
173
|
+
for item in part:
|
|
174
|
+
files.append({**item,'path':path+('/'+item['path'] if item['path'] else '')})
|
|
175
|
+
if stat.S_ISDIR(os.lstat(os.path.join(root,path)).st_mode): directories.add(path)
|
|
176
|
+
for directory in dirs: directories.add(path+'/'+directory)
|
|
177
|
+
components=path.split('/')
|
|
178
|
+
for count in range(1,len(components)): directories.add('/'.join(components[:count]))
|
|
179
|
+
if len(files)>MAX_FILES or total>MAX_BYTES: fail('aggregate output bound exceeded')
|
|
180
|
+
return sorted(files,key=lambda item:item['path']),sorted(directories),total
|
|
181
|
+
|
|
182
|
+
def writable_remove(path):
|
|
183
|
+
# Disposal validates structure without rereading payload or imposing a second payload limit on sidecars.
|
|
184
|
+
if os.path.realpath(path)!=path: fail('unsafe disposal path')
|
|
185
|
+
count=0
|
|
186
|
+
for root,dirs,files in os.walk(path,topdown=True,followlinks=False):
|
|
187
|
+
count+=len(dirs)+len(files)
|
|
188
|
+
if count>3000 or os.path.realpath(root)!=root: fail('unsafe disposal tree')
|
|
189
|
+
os.chmod(root,0o700)
|
|
190
|
+
for name in dirs:
|
|
191
|
+
st=os.lstat(os.path.join(root,name))
|
|
192
|
+
if not stat.S_ISDIR(st.st_mode): fail('unsafe disposal directory')
|
|
193
|
+
for name in files:
|
|
194
|
+
st=os.lstat(os.path.join(root,name))
|
|
195
|
+
if not stat.S_ISREG(st.st_mode) or st.st_nlink!=1: fail('unsafe disposal file')
|
|
196
|
+
for root,dirs,files in os.walk(path,topdown=False,followlinks=False):
|
|
197
|
+
for file in files: os.unlink(os.path.join(root,file))
|
|
198
|
+
for directory in dirs: os.rmdir(os.path.join(root,directory))
|
|
199
|
+
os.rmdir(path)
|
|
200
|
+
def freeze_dirs(root):
|
|
201
|
+
for base,dirs,files in os.walk(root,topdown=False,followlinks=False): os.chmod(base,0o500)
|
|
202
|
+
def key(ref):
|
|
203
|
+
return ident(ref['attemptId'],'attempt')+'/'+ident(ref['stage'])
|
|
204
|
+
def ref_for(entry):
|
|
205
|
+
return {'attemptId':entry['attemptId'],'stage':entry['stage'],'sha256':entry['sha256']}
|
|
206
|
+
def archive_path(store,aid):
|
|
207
|
+
ident(aid,'attempt')
|
|
208
|
+
return os.path.join(store,'archive',aid[:2],aid+'.json')
|
|
209
|
+
def immutable(path,value,bound=MAX_META,pending=None):
|
|
210
|
+
if os.path.lexists(path):
|
|
211
|
+
if read_bytes(path,bound)!=encoded(value): fail('immutable retention provenance mismatch')
|
|
212
|
+
else:
|
|
213
|
+
atomic(path,value,bound,pending);os.chmod(path,0o400)
|
|
214
|
+
def read_archive(store,aid):
|
|
215
|
+
path=archive_path(store,aid)
|
|
216
|
+
if not os.path.lexists(path): return None
|
|
217
|
+
if os.path.realpath(path)!=path: fail('unsafe retention archive path')
|
|
218
|
+
record=json.loads(read_bytes(path,ARCHIVE_BYTES))
|
|
219
|
+
if record.get('v')!=1 or record.get('attemptId')!=aid or not isinstance(record.get('entries'),dict): fail('invalid retention archive shard')
|
|
220
|
+
return record
|
|
221
|
+
def archives(store):
|
|
222
|
+
base=os.path.join(store,'archive')
|
|
223
|
+
if not os.path.lexists(base): return
|
|
224
|
+
physical(base,True);count=0
|
|
225
|
+
with os.scandir(base) as prefixes:
|
|
226
|
+
for prefix in prefixes:
|
|
227
|
+
if not re.fullmatch(r'[a-f0-9]{2}',prefix.name): fail('invalid retention archive prefix')
|
|
228
|
+
physical(prefix.path,True)
|
|
229
|
+
with os.scandir(prefix.path) as records:
|
|
230
|
+
for item in records:
|
|
231
|
+
# Older interrupted writers used same-directory shard temporaries. They are not published shards.
|
|
232
|
+
if re.fullmatch(r'[a-f0-9]{16}\.json\.[a-f0-9]{32}\.tmp',item.name) and item.name[:2]==prefix.name:
|
|
233
|
+
st=os.lstat(item.path)
|
|
234
|
+
if not stat.S_ISREG(st.st_mode) or st.st_nlink!=1 or st.st_uid!=os.getuid() or st.st_size>ARCHIVE_BYTES: fail('unsafe interrupted archive write')
|
|
235
|
+
count+=1
|
|
236
|
+
if count>1000000: fail('retention archive exceeds bounded record count; archive this study before adding evidence')
|
|
237
|
+
continue
|
|
238
|
+
if not re.fullmatch(r'[a-f0-9]{16}\.json',item.name) or item.name[:2]!=prefix.name: fail('invalid retention archive filename')
|
|
239
|
+
count+=1
|
|
240
|
+
if count>1000000: fail('retention archive exceeds bounded record count; archive this study before adding evidence')
|
|
241
|
+
aid=item.name[:-5]
|
|
242
|
+
yield aid,read_archive(store,aid)
|
|
243
|
+
def effective_entry(entry,store):
|
|
244
|
+
result=dict(entry);result['_adminBytes']=0;root=os.path.join(store,'objects',ident(entry['attemptId'],'attempt'),ident(entry['stage']))
|
|
245
|
+
for name in ('tombstone','disposed'):
|
|
246
|
+
marker=os.path.join(root,name+'.json')
|
|
247
|
+
if os.path.lexists(marker):
|
|
248
|
+
if os.path.realpath(marker)!=marker: fail('unsafe retention disposal provenance')
|
|
249
|
+
marker_bytes=read_bytes(marker,4096);result['_adminBytes']+=len(marker_bytes)
|
|
250
|
+
record=json.loads(marker_bytes)
|
|
251
|
+
if record!={'v':1,'ref':ref_for(entry)}: fail('retention disposal provenance mismatch')
|
|
252
|
+
result['tombstone']=True
|
|
253
|
+
if name=='disposed':
|
|
254
|
+
if os.path.lexists(os.path.join(root,'data')): fail('disposed retention payload unexpectedly remains')
|
|
255
|
+
result['bytes']=result['metadataBytes']
|
|
256
|
+
return result
|
|
257
|
+
def all_entries(state,store):
|
|
258
|
+
for entry in state['entries'].values(): yield effective_entry(entry,store)
|
|
259
|
+
for aid,record in archives(store):
|
|
260
|
+
if aid in state['attempts']: continue
|
|
261
|
+
for entry in record['entries'].values(): yield effective_entry(entry,store)
|
|
262
|
+
def find_entry(ref,state,store):
|
|
263
|
+
k=key(ref)
|
|
264
|
+
entry=state['entries'].get(k)
|
|
265
|
+
if entry is None:
|
|
266
|
+
archive=read_archive(store,ref['attemptId'])
|
|
267
|
+
entry=archive['entries'].get(k) if archive else None
|
|
268
|
+
if entry and (entry['attemptId']!=ref['attemptId'] or entry['stage']!=ref['stage']): fail('retention index provenance mismatch')
|
|
269
|
+
return effective_entry(entry,store) if entry else None
|
|
270
|
+
def compact(state,store):
|
|
271
|
+
released=[aid for aid,a in state['attempts'].items() if not a['active'] and a['reservation']==0]
|
|
272
|
+
if not released: return
|
|
273
|
+
base=mkdir(os.path.join(store,'archive'))
|
|
274
|
+
for aid in released:
|
|
275
|
+
entries={k:e for k,e in state['entries'].items() if e['attemptId']==aid}
|
|
276
|
+
if len(entries)>16: fail('unsupported released attempt stage count; retain the original index for compatible recovery')
|
|
277
|
+
record={'v':1,'attemptId':aid,'reservation':state['attempts'][aid],'entries':entries}
|
|
278
|
+
prefix=mkdir(os.path.join(base,aid[:2]));quarantine=mkdir(os.path.join(store,'quarantine'))
|
|
279
|
+
immutable(archive_path(store,aid),record,ARCHIVE_BYTES,os.path.join(quarantine,'archive-'+aid+'.pending'))
|
|
280
|
+
# Publishing a shard before removing its active-index rows is crash-safe: readers deduplicate by attempt id.
|
|
281
|
+
for aid in released: del state['attempts'][aid]
|
|
282
|
+
state['entries']={k:e for k,e in state['entries'].items() if e['attemptId'] not in released}
|
|
283
|
+
|
|
284
|
+
def manifest_for(ref,state,store):
|
|
285
|
+
k=key(ref);hexhash(ref['sha256'])
|
|
286
|
+
entry=find_entry(ref,state,store)
|
|
287
|
+
if not entry or entry['tombstone'] or entry['sha256']!=ref['sha256']: fail('retained source missing, pruned or digest mismatch')
|
|
288
|
+
root=physical(os.path.join(store,'objects',entry['attemptId'],entry['stage']))
|
|
289
|
+
raw=read_bytes(os.path.join(root,'manifest.json'),MAX_META)
|
|
290
|
+
if digest(raw)!=ref['sha256']: fail('retained manifest integrity mismatch')
|
|
291
|
+
manifest=json.loads(raw)
|
|
292
|
+
if manifest.get('v')!=1: fail('unsupported retained manifest')
|
|
293
|
+
if manifest['studyId']!=study or manifest['attemptId']!=entry['attemptId'] or manifest['stage']!=entry['stage']: fail('retained manifest identity mismatch')
|
|
294
|
+
if not isinstance(manifest.get('outputs'),dict) or len(manifest['outputs'])>32: fail('invalid retained output declaration')
|
|
295
|
+
for port,path in manifest['outputs'].items(): ident(port);relative(path)
|
|
296
|
+
files,directories,total=inventory(os.path.join(root,'data'))
|
|
297
|
+
if files!=manifest['files'] or directories!=manifest['directories']: fail('retained payload integrity mismatch')
|
|
298
|
+
return manifest,root
|
|
299
|
+
|
|
300
|
+
class LookupLimit(Exception): pass
|
|
301
|
+
def reuse_entries(state,store):
|
|
302
|
+
count=0;records=0;metadata=0
|
|
303
|
+
for entry in state['entries'].values():
|
|
304
|
+
count+=1;e=effective_entry(entry,store);metadata+=len(encoded(e))+e.get('_adminBytes',0)
|
|
305
|
+
if count>LOOKUP_RECORDS or metadata>LOOKUP_METADATA: raise LookupLimit()
|
|
306
|
+
yield e
|
|
307
|
+
for aid,record in archives(store):
|
|
308
|
+
records+=1;metadata+=len(encoded(record))
|
|
309
|
+
if records>LOOKUP_RECORDS or metadata>LOOKUP_METADATA: raise LookupLimit()
|
|
310
|
+
if aid in state['attempts']: continue
|
|
311
|
+
for entry in record['entries'].values():
|
|
312
|
+
count+=1;e=effective_entry(entry,store);metadata+=len(encoded(e))+e.get('_adminBytes',0)
|
|
313
|
+
if count>LOOKUP_RECORDS or metadata>LOOKUP_METADATA: raise LookupLimit()
|
|
314
|
+
yield e
|
|
315
|
+
|
|
316
|
+
def lookup_identity(raw):
|
|
317
|
+
fields={'definitionHash','inputHashes','codeTree','image','argvHash','envHash','seed','producerVersion'}
|
|
318
|
+
if not isinstance(raw,dict) or set(raw)!=fields: fail('invalid reuse execution identity')
|
|
319
|
+
for field in ('definitionHash','argvHash','envHash'): hexhash(raw[field])
|
|
320
|
+
if not isinstance(raw['codeTree'],str) or not re.fullmatch(r'[a-f0-9]{40}|[a-f0-9]{64}',raw['codeTree']): fail('invalid reuse code tree')
|
|
321
|
+
if not isinstance(raw['image'],str) or len(raw['image'])>512 or not re.search(r'@sha256:[a-f0-9]{64}$',raw['image']): fail('invalid reuse image')
|
|
322
|
+
if type(raw['seed'])!=int or not isinstance(raw['producerVersion'],str) or not raw['producerVersion'] or len(raw['producerVersion'])>128: fail('invalid reuse version or seed')
|
|
323
|
+
if not isinstance(raw['inputHashes'],dict) or len(raw['inputHashes'])>32: fail('invalid reuse input identities')
|
|
324
|
+
for port,value in raw['inputHashes'].items(): ident(port);hexhash(value)
|
|
325
|
+
return raw
|
|
326
|
+
|
|
327
|
+
def reuse_source(ref,q,state,store):
|
|
328
|
+
entry=find_entry(ref,state,store)
|
|
329
|
+
if not entry: return None,'missing'
|
|
330
|
+
if entry['tombstone']: return None,'pruned'
|
|
331
|
+
if entry['attemptId']==q['attemptId'] or state['attempts'].get(entry['attemptId'],{}).get('active',False): return None,'ineligible-source'
|
|
332
|
+
manifest,_=manifest_for(ref,state,store)
|
|
333
|
+
if 'reuseKey' not in manifest: return None,'unsupported'
|
|
334
|
+
if manifest['reuseKey']!=q['key']: return None,'corrupt'
|
|
335
|
+
observation=manifest.get('observed')
|
|
336
|
+
if not isinstance(observation,dict) or type(observation.get('exitCode'))!=int or observation['exitCode']!=0 or not isinstance(observation.get('containerId'),str) or not re.fullmatch(r'[a-f0-9]{64}',observation['containerId']) or not isinstance(observation.get('endedAt'),str): return None,'corrupt'
|
|
337
|
+
try: datetime.datetime.fromisoformat(observation['endedAt'].replace('Z','+00:00'))
|
|
338
|
+
except Exception: return None,'corrupt'
|
|
339
|
+
if manifest['stage']!=q['stage'] or manifest['identity']!=q['expected'] or manifest['outputs']!=q['outputs']: return None,'ineligible-source'
|
|
340
|
+
return manifest,None
|
|
341
|
+
|
|
342
|
+
def perform(q):
|
|
343
|
+
global study
|
|
344
|
+
if not isinstance(q,dict): fail('request object required')
|
|
345
|
+
study=ident(q.get('studyId'),'study');op=q.get('op')
|
|
346
|
+
if op not in ('reserve','release','seal','verify','materialize','inspect','prune','snapshot','lookup'): fail('unsupported retention operation')
|
|
347
|
+
base=physical(sys.argv[1],True)
|
|
348
|
+
study_root=os.path.join(base,study);store=os.path.join(study_root,'.retained')
|
|
349
|
+
if op=='reserve':
|
|
350
|
+
amount=q.get('reservationBytes',MAX_BYTES+MAX_META+MAX_ADMIN)
|
|
351
|
+
if type(amount)!=int or amount<1 or amount>MAX_BYTES+MAX_META+MAX_ADMIN: fail('invalid retention cap or reservation')
|
|
352
|
+
requested_cap=q.get('capBytes',CAP)
|
|
353
|
+
if type(requested_cap)!=int or requested_cap<1 or requested_cap>1024*CAP: fail('invalid retention cap or reservation')
|
|
354
|
+
# New-store admission has no prior state: reject impossible capacity before any directory creation.
|
|
355
|
+
if not os.path.lexists(os.path.join(store,'state.json')) and amount>requested_cap: fail('study retention cap full; prune explicit evidence or raise cap before admission')
|
|
356
|
+
if op=='inspect' and (not os.path.lexists(study_root) or not os.path.lexists(store)):
|
|
357
|
+
return {'op':op,'entries':[],'reservations':[],'usedBytes':0,'reservedBytes':0,'capBytes':CAP}
|
|
358
|
+
if op=='reserve':
|
|
359
|
+
study_root=mkdir(study_root);store=mkdir(store)
|
|
360
|
+
for name in ('objects','quarantine'): mkdir(os.path.join(store,name))
|
|
361
|
+
else: physical(study_root,True);physical(store,True)
|
|
362
|
+
lock=os.path.join(store,'lock')
|
|
363
|
+
try:
|
|
364
|
+
lock_fd=os.open(lock,os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW,0o600)
|
|
365
|
+
lock_stat=os.fstat(lock_fd)
|
|
366
|
+
if not stat.S_ISREG(lock_stat.st_mode) or lock_stat.st_nlink!=1 or lock_stat.st_uid!=os.getuid(): fail('invalid retention lock')
|
|
367
|
+
try: fcntl.flock(lock_fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
|
368
|
+
except BlockingIOError: fail('retention operation busy; retry after the current owner finishes')
|
|
369
|
+
except ValueError: raise
|
|
370
|
+
except Exception: fail('retention operation active or invalid lock; reconcile its owner before retrying')
|
|
371
|
+
try:
|
|
372
|
+
state_path=os.path.join(store,'state.json')
|
|
373
|
+
if os.path.exists(state_path): state=json.loads(read_bytes(state_path,STATE_BYTES))
|
|
374
|
+
else: state={'v':1,'capBytes':CAP,'attempts':{},'entries':{}}
|
|
375
|
+
if state.get('v')!=1: fail('unsupported retention state')
|
|
376
|
+
def save():
|
|
377
|
+
compact(state,store);atomic(state_path,state,STATE_BYTES)
|
|
378
|
+
if op not in ('inspect','verify','snapshot','lookup'): compact(state,store)
|
|
379
|
+
def usage():
|
|
380
|
+
used=0;administrative=0
|
|
381
|
+
for entry in all_entries(state,store): used+=entry['bytes'];administrative+=entry.get('_adminBytes',0)
|
|
382
|
+
administrative+=sum(os.lstat(archive_path(store,aid)).st_size for aid,_ in archives(store))
|
|
383
|
+
used+=administrative
|
|
384
|
+
remaining=0
|
|
385
|
+
for aid,a in state['attempts'].items():
|
|
386
|
+
own=sum(e['bytes'] for e in state['entries'].values() if e['attemptId']==aid and not e['tombstone'])
|
|
387
|
+
remaining+=max(0,a['reservation']-own)
|
|
388
|
+
return used,remaining,administrative
|
|
389
|
+
if op=='reserve':
|
|
390
|
+
aid=ident(q.get('attemptId'),'attempt');amount=q.get('reservationBytes',MAX_BYTES+MAX_META+MAX_ADMIN);cap=q.get('capBytes',state['capBytes'])
|
|
391
|
+
if type(amount)!=int or amount<1 or amount>MAX_BYTES+MAX_META+MAX_ADMIN or type(cap)!=int or cap<1 or cap>1024*CAP: fail('invalid retention cap or reservation')
|
|
392
|
+
if read_archive(store,aid) is not None and aid not in state['attempts']: fail('completed reservation cannot be reopened')
|
|
393
|
+
if aid in state['attempts']:
|
|
394
|
+
if not state['attempts'][aid]['active']: fail('completed reservation cannot be reopened')
|
|
395
|
+
if state['attempts'][aid]['reservation']!=amount or state['capBytes']!=cap: fail('reservation identity changed during duplicate admission')
|
|
396
|
+
return {'op':op}
|
|
397
|
+
used,reserved,administrative=usage()
|
|
398
|
+
if used+reserved+amount>cap: fail('study retention cap full; prune explicit evidence or raise cap before admission')
|
|
399
|
+
state['capBytes']=cap;state['attempts'][aid]={'reservation':amount,'active':True,'consumers':[]};save()
|
|
400
|
+
return {'op':op}
|
|
401
|
+
if op=='release':
|
|
402
|
+
aid=ident(q.get('attemptId'),'attempt');a=state['attempts'].get(aid)
|
|
403
|
+
if not a:
|
|
404
|
+
if read_archive(store,aid) is not None: return {'op':op}
|
|
405
|
+
fail('reservation missing')
|
|
406
|
+
a['reservation']=0;a['active']=False;a['consumers']=[];save();return {'op':op}
|
|
407
|
+
if op=='inspect':
|
|
408
|
+
used,reserved,administrative=usage();offset=q.get('offset',0);limit=q.get('limit',200)
|
|
409
|
+
if type(offset)!=int or offset<0 or offset>16000000 or type(limit)!=int or limit<1 or limit>500: fail('invalid retention inventory page')
|
|
410
|
+
entries=[];total=0
|
|
411
|
+
for e in all_entries(state,store):
|
|
412
|
+
active=state['attempts'].get(e['attemptId'],{}).get('active',False) or any(a['active'] and key(ref_for(e)) in a['consumers'] for a in state['attempts'].values())
|
|
413
|
+
if total>=offset and len(entries)<limit: entries.append({'ref':ref_for(e),'bytes':e['bytes'],'tombstone':e['tombstone'],'active':active})
|
|
414
|
+
total+=1
|
|
415
|
+
reservations=[{'attemptId':aid,'active':a['active'],'reservationBytes':a['reservation']} for aid,a in sorted(state['attempts'].items())]
|
|
416
|
+
archived=sum(1 for aid,_ in archives(store) if aid not in state['attempts'])
|
|
417
|
+
result={'op':op,'entries':entries,'reservations':reservations,'archivedReservations':archived,'offset':offset,'limit':limit,'total':total,'remaining':max(0,total-offset-len(entries)),'usedBytes':used,'reservedBytes':reserved,'administrativeBytes':administrative,'capBytes':state['capBytes']}
|
|
418
|
+
if len(encoded(result))>STATE_BYTES: fail('retention inventory exceeds response bound')
|
|
419
|
+
return result
|
|
420
|
+
if op=='verify':
|
|
421
|
+
manifest,root=manifest_for(q['ref'],state,store)
|
|
422
|
+
return {'op':op,'manifest':manifest,'sha256':q['ref']['sha256']}
|
|
423
|
+
if op=='prune':
|
|
424
|
+
refs=q.get('refs')
|
|
425
|
+
if not isinstance(refs,list) or not refs or len(refs)>500: fail('prune requires 1..500 explicit references')
|
|
426
|
+
keys=[key(ref) for ref in refs]
|
|
427
|
+
if len(keys)!=len(set(keys)): fail('duplicate prune references')
|
|
428
|
+
for ref in refs:
|
|
429
|
+
k=key(ref);entry=find_entry(ref,state,store)
|
|
430
|
+
if not entry or entry['sha256']!=hexhash(ref['sha256']): fail('prune source identity missing')
|
|
431
|
+
if state['attempts'].get(entry['attemptId'],{}).get('active',False) or any(a['active'] and k in a['consumers'] for a in state['attempts'].values()): fail('active producer or consumer prevents prune')
|
|
432
|
+
fingerprint=digest(encoded({'state':state,'refs':sorted(refs,key=key),'entries':[find_entry(ref,state,store) for ref in sorted(refs,key=key)]}))
|
|
433
|
+
if q.get('fingerprint') is None: return {'op':op,'fingerprint':fingerprint,'pruned':0}
|
|
434
|
+
if q['fingerprint']!=fingerprint: fail('stale prune fingerprint')
|
|
435
|
+
# Immutable tombstones precede byte deletion; a crash cannot expose half-disposed payloads.
|
|
436
|
+
for ref in refs:
|
|
437
|
+
root=physical(os.path.join(store,'objects',ref['attemptId'],ref['stage']))
|
|
438
|
+
immutable(os.path.join(root,'tombstone.json'),{'v':1,'ref':ref_for(find_entry(ref,state,store))},4096)
|
|
439
|
+
for ref in refs:
|
|
440
|
+
root=os.path.join(store,'objects',ref['attemptId'],ref['stage'])
|
|
441
|
+
data=os.path.join(root,'data')
|
|
442
|
+
if os.path.exists(data): writable_remove(data)
|
|
443
|
+
immutable(os.path.join(root,'disposed.json'),{'v':1,'ref':ref_for(find_entry(ref,state,store))},4096)
|
|
444
|
+
save()
|
|
445
|
+
return {'op':op,'fingerprint':fingerprint,'pruned':len(keys)}
|
|
446
|
+
aid=ident(q.get('attemptId'),'attempt');attempt=state['attempts'].get(aid)
|
|
447
|
+
if not attempt or not attempt['active']: fail('active retention reservation required')
|
|
448
|
+
if op=='lookup':
|
|
449
|
+
q['stage']=ident(q.get('stage'));q['key']=hexhash(q.get('key'));q['expected']=lookup_identity(q.get('expected'))
|
|
450
|
+
outputs=q.get('outputs')
|
|
451
|
+
if not isinstance(outputs,dict) or not outputs or len(outputs)>32: fail('invalid reuse output declaration')
|
|
452
|
+
for port,path in outputs.items(): ident(port);relative(path)
|
|
453
|
+
if q['stage']=='evaluator': return {'op':op,'hit':False,'reason':'ineligible-source'}
|
|
454
|
+
selections=attempt.get('reuseSelections',{})
|
|
455
|
+
if not isinstance(selections,dict) or len(selections)>16: fail('invalid reuse selections (at most 16 active selections); finish or cancel attempts holding selections, inspect with ares retention inspect <dir>, restore invalid state, then prune inactive sources with ares retention prune <dir>')
|
|
456
|
+
prior=selections.get(q['stage']);chosen=None;miss='missing'
|
|
457
|
+
try:
|
|
458
|
+
if prior is not None:
|
|
459
|
+
if not isinstance(prior,dict) or set(prior)!={'key','ref'} or prior['key']!=q['key']: return {'op':op,'hit':False,'reason':'ineligible-source'}
|
|
460
|
+
manifest,reason=reuse_source(prior['ref'],q,state,store)
|
|
461
|
+
if reason: return {'op':op,'hit':False,'reason':reason}
|
|
462
|
+
chosen=(prior['ref'],manifest)
|
|
463
|
+
else:
|
|
464
|
+
for entry in reuse_entries(state,store):
|
|
465
|
+
if entry.get('reuseKey')!=q['key']: continue
|
|
466
|
+
ref=ref_for(entry);manifest,reason=reuse_source(ref,q,state,store)
|
|
467
|
+
if reason:
|
|
468
|
+
miss=reason
|
|
469
|
+
# A matching but malformed source never triggers unbounded payload retries.
|
|
470
|
+
if reason in ('corrupt','unsupported'): return {'op':op,'hit':False,'reason':reason}
|
|
471
|
+
continue
|
|
472
|
+
chosen=(ref,manifest);break
|
|
473
|
+
except LookupLimit: return {'op':op,'hit':False,'reason':'scan-cap'}
|
|
474
|
+
except FileNotFoundError: return {'op':op,'hit':False,'reason':'missing'}
|
|
475
|
+
except ValueError as error: return {'op':op,'hit':False,'reason':'unsupported' if str(error).startswith('unsupported') else 'corrupt'}
|
|
476
|
+
except (OSError,KeyError,TypeError): return {'op':op,'hit':False,'reason':'corrupt'}
|
|
477
|
+
if chosen is None: return {'op':op,'hit':False,'reason':miss}
|
|
478
|
+
ref,manifest=chosen;source_key=key(ref)
|
|
479
|
+
if prior is None or source_key not in attempt['consumers']:
|
|
480
|
+
if prior is None and len(selections)>=16: fail('reuse selection bound exceeded (16 active selections); finish or cancel attempts holding selections, inspect with ares retention inspect <dir>, then prune inactive sources with ares retention prune <dir> before retrying')
|
|
481
|
+
selections[q['stage']]={'key':q['key'],'ref':ref};attempt['reuseSelections']=selections
|
|
482
|
+
attempt['consumers']=sorted(set(attempt['consumers']+[source_key]));save()
|
|
483
|
+
return {'op':op,'hit':True,'ref':ref,'manifest':manifest,'sha256':ref['sha256'],'manifestBytes':len(read_bytes(os.path.join(store,'objects',ref['attemptId'],ref['stage'],'manifest.json'),MAX_META))}
|
|
484
|
+
workspace=physical(os.path.join(study_root,aid),True)
|
|
485
|
+
def code_hash(source):
|
|
486
|
+
root=within(source,workspace);physical(root)
|
|
487
|
+
files,dirs,_=inventory(root,max_bytes=MAX_BYTES,max_files=100000,max_directories=100000,code=True)
|
|
488
|
+
return digest(encoded({'files':files,'directories':dirs}))
|
|
489
|
+
if op=='snapshot': return {'op':op,'sha256':code_hash(q['source'])}
|
|
490
|
+
stage=ident(q.get('stage'))
|
|
491
|
+
if op=='seal':
|
|
492
|
+
source=within(q['source'],workspace);physical(source)
|
|
493
|
+
reuse_key=q.get('reuseKey')
|
|
494
|
+
if reuse_key is not None:
|
|
495
|
+
hexhash(reuse_key)
|
|
496
|
+
if stage=='evaluator': fail('evaluator outputs cannot be indexed for reuse')
|
|
497
|
+
observation=q['observed'];identity=q['identity'];outputs=q['outputs'];metadata_limit=q.get('metadataLimit',MAX_META)
|
|
498
|
+
if type(metadata_limit)!=int or metadata_limit<0 or metadata_limit>MAX_META: fail('invalid shared metadata limit')
|
|
499
|
+
if not isinstance(observation,dict) or set(observation)!={'containerId','endedAt','exitCode'} or not isinstance(identity,dict) or set(identity)!={'definitionHash','inputHashes','codeTree','image','argvHash','envHash','seed','producerVersion'}: fail('invalid producing manifest fields')
|
|
500
|
+
if observation.get('exitCode')!=0 or not re.fullmatch(r'[a-f0-9]{64}',observation.get('containerId','')) or not isinstance(observation.get('endedAt'),str): fail('observed successful termination receipt required')
|
|
501
|
+
if len(observation['endedAt'])>64: fail('invalid observed termination time')
|
|
502
|
+
try: datetime.datetime.fromisoformat(observation['endedAt'].replace('Z','+00:00'))
|
|
503
|
+
except Exception: fail('invalid observed termination time')
|
|
504
|
+
for field in ('definitionHash','argvHash','envHash'): hexhash(identity.get(field))
|
|
505
|
+
if not re.fullmatch(r'[a-f0-9]{40}|[a-f0-9]{64}',identity.get('codeTree','')) or not isinstance(identity.get('image'),str) or not re.search(r'@sha256:[a-f0-9]{64}$',identity['image']): fail('invalid producing execution identity')
|
|
506
|
+
if type(identity.get('seed'))!=int or not isinstance(identity.get('producerVersion'),str) or len(identity['producerVersion'])>128: fail('invalid producer version or seed')
|
|
507
|
+
if not isinstance(identity.get('inputHashes'),dict) or len(identity['inputHashes'])>32: fail('invalid input identities')
|
|
508
|
+
for port,h in identity['inputHashes'].items(): ident(port);hexhash(h)
|
|
509
|
+
if not isinstance(outputs,dict) or len(outputs)>32: fail('invalid declared outputs')
|
|
510
|
+
for port,path in outputs.items(): ident(port);relative(path)
|
|
511
|
+
paths=list(outputs.values())
|
|
512
|
+
if any(a==b or a.startswith(b+'/') or b.startswith(a+'/') for i,a in enumerate(paths) for b in paths[i+1:]): fail('overlapping declared outputs')
|
|
513
|
+
k=aid+'/'+stage
|
|
514
|
+
if k in state['entries']:
|
|
515
|
+
prior=state['entries'][k]
|
|
516
|
+
manifest,root=manifest_for(ref_for(prior),state,store)
|
|
517
|
+
if manifest['identity']!=identity or manifest['observed']!=observation or manifest['outputs']!=outputs or manifest.get('reuseKey')!=reuse_key: fail('stage already sealed with different provenance')
|
|
518
|
+
sidecars=sum(e['metadataBytes'] for e in state['entries'].values() if e['attemptId']==aid)
|
|
519
|
+
if sidecars>metadata_limit: fail('cumulative shared metadata limit exceeded')
|
|
520
|
+
return {'op':op,'manifest':manifest,'sha256':prior['sha256'],'manifestBytes':prior['metadataBytes'],'sidecarBytes':sidecars}
|
|
521
|
+
published_root=os.path.join(store,'objects',aid,stage)
|
|
522
|
+
if os.path.lexists(published_root):
|
|
523
|
+
physical(published_root)
|
|
524
|
+
raw=read_bytes(os.path.join(published_root,'manifest.json'),MAX_META);manifest=json.loads(raw)
|
|
525
|
+
if manifest.get('v')!=1 or manifest.get('studyId')!=study or manifest.get('attemptId')!=aid or manifest.get('stage')!=stage or manifest.get('identity')!=identity or manifest.get('observed')!=observation or manifest.get('outputs')!=outputs or manifest.get('reuseKey')!=reuse_key: fail('unindexed publication provenance mismatch')
|
|
526
|
+
files,dirs,total=inventory(os.path.join(published_root,'data'))
|
|
527
|
+
original,original_dirs,_=selected_inventory(source,paths)
|
|
528
|
+
if manifest.get('files')!=files or manifest.get('directories')!=dirs or original!=files or original_dirs!=dirs: fail('unindexed publication integrity mismatch')
|
|
529
|
+
siblings=[e for e in state['entries'].values() if e['attemptId']==aid and not e['tombstone']]
|
|
530
|
+
if sum(e['payloadBytes'] for e in siblings)+total>MAX_BYTES or sum(e['files'] for e in siblings)+len(files)>MAX_FILES or sum(e['metadataBytes'] for e in siblings)+len(raw)>metadata_limit: fail('cumulative attempt output or metadata limit exceeded')
|
|
531
|
+
if sum(e['bytes'] for e in siblings)+total+len(raw)>attempt['reservation']: fail('retention reservation exceeded')
|
|
532
|
+
state['entries'][k]={'attemptId':aid,'stage':stage,'sha256':digest(raw),'bytes':total+len(raw),'payloadBytes':total,'metadataBytes':len(raw),'files':len(files),'tombstone':False,**({'reuseKey':reuse_key} if reuse_key is not None else {})};save()
|
|
533
|
+
return {'op':op,'manifest':manifest,'sha256':digest(raw),'manifestBytes':len(raw),'sidecarBytes':sum(e['metadataBytes'] for e in siblings)+len(raw)}
|
|
534
|
+
tmp=os.path.join(store,'quarantine',aid+'-'+stage+'.pending')
|
|
535
|
+
if os.path.lexists(tmp): writable_remove(tmp)
|
|
536
|
+
os.mkdir(tmp,0o700);data=os.path.join(tmp,'data');os.mkdir(data,0o700)
|
|
537
|
+
try:
|
|
538
|
+
# Copy only declared outputs, while retaining their paths under the stage output root.
|
|
539
|
+
for port,path in outputs.items():
|
|
540
|
+
if not os.path.lexists(os.path.join(source,path)): fail('declared output port '+port+' missing at its declared path; the stage command must write that output')
|
|
541
|
+
selected=within(os.path.join(source,path),source)
|
|
542
|
+
dest=os.path.join(data,path);os.makedirs(os.path.dirname(dest),mode=0o700,exist_ok=True)
|
|
543
|
+
bounded_copy(selected,dest)
|
|
544
|
+
files,dirs,total=inventory(data)
|
|
545
|
+
# Rehash producer bytes without a second payload copy before publication.
|
|
546
|
+
original,original_dirs,_=selected_inventory(source,paths)
|
|
547
|
+
if original!=files or original_dirs!=dirs: fail('producer output changed during seal')
|
|
548
|
+
manifest={'v':1,'studyId':study,'attemptId':aid,'stage':stage,'identity':identity,'observed':observation,'outputs':outputs,'files':files,'directories':dirs,**({'reuseKey':reuse_key} if reuse_key is not None else {})}
|
|
549
|
+
raw=encoded(manifest)
|
|
550
|
+
siblings=[e for e in state['entries'].values() if e['attemptId']==aid and not e['tombstone']]
|
|
551
|
+
if sum(e['payloadBytes'] for e in siblings)+total>MAX_BYTES or sum(e['files'] for e in siblings)+len(files)>MAX_FILES or sum(e['metadataBytes'] for e in siblings)+len(raw)>metadata_limit: fail('cumulative attempt output or metadata limit exceeded')
|
|
552
|
+
if sum(e['bytes'] for e in siblings)+total+len(raw)>attempt['reservation']: fail('retention reservation exceeded')
|
|
553
|
+
atomic(os.path.join(tmp,'manifest.json'),manifest,MAX_META)
|
|
554
|
+
parent=mkdir(os.path.join(store,'objects',aid));final=os.path.join(parent,stage)
|
|
555
|
+
if os.path.lexists(final): fail('publication changed under retention lock; inspect executor integrity')
|
|
556
|
+
freeze_dirs(data);os.chmod(os.path.join(tmp,'manifest.json'),0o400)
|
|
557
|
+
os.rename(tmp,final);syncdir(parent)
|
|
558
|
+
state['entries'][k]={'attemptId':aid,'stage':stage,'sha256':digest(raw),'bytes':total+len(raw),'payloadBytes':total,'metadataBytes':len(raw),'files':len(files),'tombstone':False,**({'reuseKey':reuse_key} if reuse_key is not None else {})}
|
|
559
|
+
save()
|
|
560
|
+
return {'op':op,'manifest':manifest,'sha256':digest(raw),'manifestBytes':len(raw),'sidecarBytes':sum(e['metadataBytes'] for e in siblings)+len(raw)}
|
|
561
|
+
finally:
|
|
562
|
+
if os.path.exists(tmp): writable_remove(tmp)
|
|
563
|
+
if op=='materialize':
|
|
564
|
+
inputs=q['inputs'];target=within(q['target'],workspace);task_root=within(q['taskRoot'],workspace)
|
|
565
|
+
if not isinstance(inputs,dict) or len(inputs)>32: fail('invalid input ports')
|
|
566
|
+
has_task=any(isinstance(descriptor,dict) and 'task' in descriptor for descriptor in inputs.values())
|
|
567
|
+
def verify_task():
|
|
568
|
+
if not has_task and stage!='evaluator': return
|
|
569
|
+
expected=hexhash(q.get('expectedTaskTreeHash'))
|
|
570
|
+
physical(task_root)
|
|
571
|
+
task_files,_,_=inventory(task_root,max_bytes=64*1024*1024)
|
|
572
|
+
pairs=sorted([[item['path'],item['sha256']] for item in task_files],key=lambda item:item[0].encode('utf-16-be','surrogatepass'))
|
|
573
|
+
actual=digest(json.dumps(pairs,separators=(',',':'),ensure_ascii=False).encode())
|
|
574
|
+
if actual!=expected: fail('frozen task snapshot integrity mismatch')
|
|
575
|
+
def verify_code():
|
|
576
|
+
if q.get('codeRoot') is None and q.get('expectedCodeHash') is None: return
|
|
577
|
+
expected=hexhash(q.get('expectedCodeHash'))
|
|
578
|
+
if code_hash(q.get('codeRoot'))!=expected: fail('frozen code snapshot integrity mismatch')
|
|
579
|
+
verify_task();verify_code()
|
|
580
|
+
sources=[];dependencies=[]
|
|
581
|
+
for port,descriptor in inputs.items():
|
|
582
|
+
ident(port)
|
|
583
|
+
if set(descriptor)=={'task'}:
|
|
584
|
+
path=relative(descriptor['task'])
|
|
585
|
+
if path=='evaluator' or path.startswith('evaluator/'): fail('evaluator task path is private')
|
|
586
|
+
physical(task_root);source=within(os.path.join(task_root,path),task_root)
|
|
587
|
+
elif 'ref' in descriptor and set(descriptor).issubset({'ref','output'}):
|
|
588
|
+
manifest,root=manifest_for(descriptor['ref'],state,store);dependencies.append(key(descriptor['ref']))
|
|
589
|
+
if 'output' in descriptor:
|
|
590
|
+
name=ident(descriptor['output'])
|
|
591
|
+
if name not in manifest['outputs']: fail('undeclared upstream output')
|
|
592
|
+
source=os.path.join(root,'data',manifest['outputs'][name])
|
|
593
|
+
else: source=os.path.join(root,'data')
|
|
594
|
+
if os.path.realpath(source)!=source: fail('unsafe retained input source')
|
|
595
|
+
else: fail('undeclared input source')
|
|
596
|
+
sources.append((port,source,descriptor))
|
|
597
|
+
marker=target+'.retention.json'
|
|
598
|
+
if os.path.lexists(target):
|
|
599
|
+
receipt=json.loads(read_bytes(marker,MAX_META))
|
|
600
|
+
if receipt.get('sources')!=digest(encoded(inputs)): fail('existing consumer input identities changed')
|
|
601
|
+
files,dirs,_=inventory(target)
|
|
602
|
+
if sorted(os.listdir(target))!=sorted(inputs): fail('undeclared materialized input')
|
|
603
|
+
if files!=receipt['files'] or dirs!=receipt['directories']: fail('existing consumer snapshot integrity mismatch')
|
|
604
|
+
for port,source,descriptor in sources:
|
|
605
|
+
part,part_dirs,_=bounded_copy(source)
|
|
606
|
+
expected=digest(encoded({'files':part,'directories':part_dirs}))
|
|
607
|
+
actual_files,actual_dirs,_=bounded_copy(os.path.join(target,port))
|
|
608
|
+
if expected!=receipt['payloadHashes'][port] or receipt['inputHashes'][port]!=(descriptor['ref']['sha256'] if 'ref' in descriptor else expected) or digest(encoded({'files':actual_files,'directories':actual_dirs}))!=expected: fail('consumer source or payload changed since materialization')
|
|
609
|
+
verify_task();verify_code()
|
|
610
|
+
return {'op':op,'inputHashes':receipt['inputHashes'],'files':files}
|
|
611
|
+
# Record consumer references before any copy; a crash keeps the source protected.
|
|
612
|
+
attempt['consumers']=sorted(set(attempt['consumers']+dependencies));save()
|
|
613
|
+
parent=physical(os.path.dirname(target));tmp=target+'.pending'
|
|
614
|
+
if os.path.lexists(tmp): writable_remove(tmp)
|
|
615
|
+
os.mkdir(tmp,0o700)
|
|
616
|
+
try:
|
|
617
|
+
hashes={};payload_hashes={};total=0;count=0
|
|
618
|
+
for port,source,descriptor in sources:
|
|
619
|
+
files,dirs,size=bounded_copy(source,os.path.join(tmp,port));count+=len(files);total+=size
|
|
620
|
+
if count>MAX_FILES or total>MAX_BYTES: fail('materialized inputs exceed aggregate bounds')
|
|
621
|
+
payload_hashes[port]=digest(encoded({'files':files,'directories':dirs}));hashes[port]=descriptor['ref']['sha256'] if 'ref' in descriptor else payload_hashes[port]
|
|
622
|
+
if 'ref' in descriptor: manifest_for(descriptor['ref'],state,store)
|
|
623
|
+
files,dirs,_=inventory(tmp)
|
|
624
|
+
if sorted(os.listdir(tmp))!=sorted(inputs): fail('undeclared materialized input')
|
|
625
|
+
for port in inputs:
|
|
626
|
+
actual_files,actual_dirs,_=bounded_copy(os.path.join(tmp,port))
|
|
627
|
+
if digest(encoded({'files':actual_files,'directories':actual_dirs}))!=payload_hashes[port]: fail('consumer payload changed before publication')
|
|
628
|
+
verify_task();verify_code()
|
|
629
|
+
receipt={'sources':digest(encoded(inputs)),'inputHashes':hashes,'payloadHashes':payload_hashes,'files':files,'directories':dirs}
|
|
630
|
+
atomic(marker,receipt,MAX_META)
|
|
631
|
+
freeze_dirs(tmp);os.rename(tmp,target);syncdir(parent)
|
|
632
|
+
return {'op':op,'inputHashes':hashes,'files':files}
|
|
633
|
+
finally:
|
|
634
|
+
if os.path.exists(tmp): writable_remove(tmp)
|
|
635
|
+
fail('unsupported retention operation')
|
|
636
|
+
finally:
|
|
637
|
+
fcntl.flock(lock_fd,fcntl.LOCK_UN);os.close(lock_fd)
|
|
638
|
+
try:
|
|
639
|
+
request=sys.stdin.buffer.read(STATE_BYTES+1)
|
|
640
|
+
if len(request)>STATE_BYTES: fail('request bound exceeded')
|
|
641
|
+
result=perform(json.loads(request))
|
|
642
|
+
output=encoded(result)
|
|
643
|
+
if len(output)>STATE_BYTES: fail('receipt bound exceeded')
|
|
644
|
+
print(output.decode())
|
|
645
|
+
except Exception as error:
|
|
646
|
+
message=str(error) if isinstance(error,ValueError) else 'retained filesystem operation failed'
|
|
647
|
+
print(json.dumps({'error':message[:300]}))
|
|
648
|
+
sys.exit(1)
|
|
649
|
+
`;
|