Files

208 lines
11 KiB
Python

#!/usr/bin/env python3
"""Layout-independent content steps (owner 2026-11-24: compacted clients must keep updating).
A STORE step carries what a frozen content candidate adds to the store, by identity instead of by file layout:
STEP STORE <id> <parent_build_key> <child_build_key>
FRAME <ekey32> <blte bytes> <blte sha256> <blob sha256> <blob size> zstd
FRAME <ekey32> <blte bytes> <blte sha256> <blob sha256> <blob size> zstd-frame <base ekey32>
CONF <target> <sha256> <size> <blob sha256> <blob size>
ACTIVATE <target> <parent sha256> <child sha256> <blob sha256> <blob size>
Apply (this module's apply(), and OctoUpdater.exe the same way), on ANY local layout of the parent build:
1. .build.info build key == parent.
2. read the newest IDX generation of every bucket; FRAMEs whose 9-byte key prefix is already indexed are skipped.
3. decode each missing FRAME (zstd-frame: zstd --patch-from the base frame's BLTE body, read through the client's
own index), check its sha256, append header+BLTE to the highest data.NNN (a new one when 1 GiB would be crossed).
4. one new IDX generation per touched bucket (old rows kept bit-identical, new rows sorted in), old generation removed.
5. CONF files, then .build.info last; data/shmem removed (native CASC rebuilds it).
An interrupted run leaves the client on the parent build: extra frames are only unreferenced bytes.
Delta bases: the child's republished tables (root, tvfs-*, download, encoding) against the parent's same-role frame.
"""
import hashlib, json, os, struct, subprocess, sys, tempfile
from pathlib import Path
OPS = Path(__file__).resolve().parent.parent; sys.path.insert(0, str(OPS))
import casc_local_archive as A
from casc_asset_package import blte_encoding_key
from casc_compact import read_indexes, span
SEGMENT = 1 << 30
CONTENT = Path('/mnt/Games/@project/gateway/runtime/continuation-20261113/claude-lane/content')
sha = lambda b: hashlib.sha256(b).hexdigest()
def role_records(cand):
core = json.loads((cand / 'core.json').read_text()); meta = json.loads((cand / 'metadata.json').read_text())
records = {k: v for k, v in core['parts'].items() if v.get('encoding_key')}
if meta.get('encoding', {}).get('encoding_key'): records['encoding'] = meta['encoding']
return records
def roles(cand):
return {role: row['encoding_key'] for role, row in role_records(cand).items()}
def candidate_for(build_key):
for d in sorted(CONTENT.glob('*-frozen-candidate')):
m = d / 'metadata.json'
if m.exists() and json.loads(m.read_text()).get('key') == build_key: return d
raise SystemExit(f'no frozen candidate for build {build_key[:8]}')
def candidate_frames(cand):
"""(full ekey bytes, BLTE body) for every span the candidate's new archive(s) hold."""
plan = json.loads((cand / 'stage-plan.json').read_text()); api, _ = A.lookup3_api()
files = {e['target']: cand / e['artifact'] for e in plan['forward']['copy_verified_files']}
segs = {int(Path(t).name[5:]): p for t, p in files.items() if Path(t).name.startswith('data.')}
out = {}
for t, p in files.items():
if not t.endswith('.idx'): continue
b = int(Path(t).name[:2], 16)
for row in A.parse_index(p.read_bytes(), b, api)['rows']:
seg, off, size = span(row)
if seg not in segs: continue
with open(segs[seg], 'rb') as f: f.seek(off); blob = f.read(size)
key = blob[:16][::-1]; assert key[:9] == row[:9] and blob[30:34] == b'BLTE', (t, off)
out[key] = blob[30:]
return out, files, plan
def parent_frame(cand, row, frames, plan):
"""Resolve a delta dictionary only when the parent proves it contains those bytes."""
key = bytes.fromhex(row['encoding_key'])
data = frames.get(key)
if data is None:
# A role can be inherited without a copy in the parent's new archive.
# A loose publisher payload alone says nothing about player availability.
guards = plan.get('preconditions', {}).get('inherited_native_alias_exact_spans', [])
size = row.get('encoded_size')
digest = row.get('encoded_sha256')
if not size or not digest or not row.get('encoded_file'):
return None
if not any(p.get('encoding_key') == key.hex() and p.get('bytes') == size
and p.get('sha256') == digest for p in guards):
return None
path = (cand / row['encoded_file']).resolve()
if not path.is_relative_to(cand.resolve()):
raise ValueError(f'Parent role payload escapes its candidate: {key.hex()}')
if not path.is_file():
return None
data = path.read_bytes()
if ('encoded_size' in row and len(data) != row['encoded_size']
or 'encoded_sha256' in row and sha(data) != row['encoded_sha256']
or blte_encoding_key(data) != key):
raise ValueError(f'Parent role frame failed verification: {key.hex()}')
return data
def read_frame_from(cand, ekey):
"""A frame's BLTE body from a frozen candidate's own new archive (delta base on the publisher side)."""
frames, _, _ = candidate_frames(cand)
return frames.get(bytes.fromhex(ekey))
def zst(chan, data, base=None):
d = chan / 'blobs'; d.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=d) as t:
src = Path(t) / 'src'; src.write_bytes(data); out = Path(t) / 'out.zst'
cmd = ['zstd', '-q', '-f', '-19', '-T0', '--long=31', str(src), '-o', str(out)]
if base is not None: (Path(t) / 'base').write_bytes(base); cmd[1:1] = [f'--patch-from={Path(t) / "base"}']
subprocess.run(cmd, check=True); raw = out.read_bytes()
s = sha(raw); p = d / f'{s}.zst'
if not p.exists(): p.write_bytes(raw)
return s, len(raw)
def publish(chan, cand):
"""Return the STORE step dict for a frozen candidate."""
cand = cand.resolve(); frames, files, plan = candidate_frames(cand)
parent = candidate_for(plan['parent_build_key']); pr, cr = role_records(parent), roles(cand)
base_of = {key: pr[role] for role, key in cr.items()
if role in pr and key != pr[role]['encoding_key']}
if base_of:
pframes, _, parent_plan = candidate_frames(parent)
lines = []
for key, blte in sorted(frames.items()):
k = key.hex(); base = base_of.get(k)
b = parent_frame(parent, base, pframes, parent_plan) if base else None
if b is not None:
s, n = zst(chan, blte, b); lines.append(f"FRAME {k} {len(blte)} {sha(blte)} {s} {n} zstd-frame {base['encoding_key']}")
else:
s, n = zst(chan, blte); lines.append(f'FRAME {k} {len(blte)} {sha(blte)} {s} {n} zstd')
print(f' frame {k[:12]} {len(blte)} -> {n}' + (' (delta)' if b is not None else ''), flush=True)
for t, p in files.items():
if t.startswith('Data/config/'):
raw = p.read_bytes(); s, n = zst(chan, raw); lines.append(f'CONF {t} {sha(raw)} {len(raw)} {s} {n}')
fa = plan['forward']['final_activation']; raw = (cand / fa['file']).read_bytes(); assert sha(raw) == fa['child_sha256']
s, n = zst(chan, raw); lines.append(f"ACTIVATE {fa['target']} {fa['parent_sha256']} {fa['child_sha256']} {s} {n}")
child = plan['candidate_build_key']
return {'kind': 'STORE', 'id': child[:8], 'parent': plan['parent_build_key'], 'child': child, 'source': str(cand), 'lines': lines}
# ---------------------------------------------------------------- apply (reference for OctoUpdater.exe)
def build_key(client):
return next(l for l in (client / '.build.info').read_text().splitlines()[1:] if l.strip()).split('|')[2]
def unzst(blob, base=None):
with tempfile.TemporaryDirectory() as t:
i = Path(t) / 'in.zst'; i.write_bytes(blob); o = Path(t) / 'out'
cmd = ['zstd', '-q', '-d', '-f', '--long=31', str(i), '-o', str(o)]
if base is not None: (Path(t) / 'base').write_bytes(base); cmd[1:1] = [f'--patch-from={Path(t) / "base"}']
subprocess.run(cmd, check=True); return o.read_bytes()
def apply(client, step, blobs):
client = Path(client); data = client / 'Data/data'; api, _ = A.lookup3_api()
if build_key(client) != step['parent']: raise SystemExit(f"client build {build_key(client)[:8]} is not the parent {step['parent'][:8]}")
buckets = read_indexes(data, api)
rows = {} # first row per key prefix, as native lookup
for _, _, layout in buckets.values():
for r in layout['rows']: rows.setdefault(r[:9], r)
def frame(ekey):
seg, off, size = span(rows[bytes.fromhex(ekey)[:9]])
with open(data / f'data.{seg:03d}', 'rb') as f: f.seek(off); b = f.read(size)
return b if b[:4] == b'BLTE' else b[30:]
todo = []
for v in (l.split() for l in step['lines']):
if v[0] != 'FRAME' or bytes.fromhex(v[1])[:9] in rows: continue
blob = (blobs / f'{v[4]}.zst').read_bytes(); assert sha(blob) == v[4]
blte = unzst(blob, frame(v[7]) if v[6] == 'zstd-frame' else None)
if len(blte) != int(v[2]) or sha(blte) != v[3]: raise SystemExit(f'frame {v[1][:12]} decodes wrong')
todo.append((bytes.fromhex(v[1]), blte))
segs = sorted(int(p.name[5:]) for p in data.glob('data.[0-9][0-9][0-9]'))
seg = segs[-1]; pos = (data / f'data.{seg:03d}').stat().st_size; adds = {}
fh = open(data / f'data.{seg:03d}', 'ab')
try:
for key, blte in todo:
if pos + 30 + len(blte) > SEGMENT:
fh.close(); seg += 1; pos = 0; fh = open(data / f'data.{seg:03d}', 'xb')
fh.write(A._archive_span_with_key(blte, pos, api, key))
adds.setdefault(A.encoding_bucket(key), []).append(dict(encoding_key=key, segment=seg, offset=pos, span_size=len(blte) + 30))
pos += 30 + len(blte)
fh.flush(); os.fsync(fh.fileno())
finally: fh.close()
for b, new in sorted(adds.items()):
name, raw, _ = buckets[b]; out, _ = A.extend_index(raw, b, new, api)
nxt = data / f'{b:02x}{int(name[2:10], 16) + 1:08x}.idx'; nxt.write_bytes(out)
os.fsync(os.open(nxt, os.O_RDONLY)); (data / name).unlink()
for v in (l.split() for l in step['lines']):
if v[0] == 'CONF':
raw = unzst((blobs / f'{v[4]}.zst').read_bytes()); assert sha(raw) == v[2]
t = client / v[1]; t.parent.mkdir(parents=True, exist_ok=True); t.write_bytes(raw)
act = next(l.split() for l in step['lines'] if l.startswith('ACTIVATE '))
bi = client / act[1]
if sha(bi.read_bytes()) != act[2]: raise SystemExit('.build.info is not the parent file')
raw = unzst((blobs / f'{act[4]}.zst').read_bytes()); assert sha(raw) == act[3]
tmp = bi.with_suffix('.info.new'); tmp.write_bytes(raw); os.replace(tmp, bi)
for p in (data / 'shmem',):
if p.exists(): p.unlink()
return dict(frames=len(todo), skipped=sum(1 for l in step['lines'] if l.startswith('FRAME ')) - len(todo), archive=seg, buckets=len(adds))
if __name__ == '__main__':
import argparse
a = argparse.ArgumentParser(); a.add_argument('cmd', choices=['apply']); a.add_argument('client'); a.add_argument('--repo', required=True)
a.add_argument('--channel', default='octo'); a.add_argument('--id', required=True)
x = a.parse_args(); chan = Path(x.repo) / x.channel
st = json.loads((chan / 'state.json').read_text()); step = next(s for s in st['steps'] if s['kind'] == 'STORE' and s['id'] == x.id)
print(json.dumps(apply(x.client, step, chan / 'blobs')))