Recreate-AAA / bench_builder /development_inputs.py
CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
Raw History Blame Contribute Delete
24.6 kB
"""Editable development packages and immutable experiment input revisions.
Only explicitly selected videos or complete sessions and ordinary files cross this boundary.
Evaluator cases and repository source are never added implicitly.
"""
from __future__ import annotations
import functools
import hashlib
import json
import os
import shutil
import subprocess
import tempfile
import threading
import uuid
from pathlib import Path, PurePosixPath
from bench_builder.util.digest import sha256_file
_LOCK = threading.RLock()
def _write(path: Path, value) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + '.tmp')
temporary.write_text(json.dumps(value, indent=2), encoding='utf-8')
temporary.replace(path)
def _id(value: str) -> str:
import re
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,159}', value):
raise ValueError('Invalid development input identifier')
return value
def file_path(root: Path, name: str) -> Path:
relative = PurePosixPath(name)
if not name or '\\' in name or relative.is_absolute() or any(p in {'.', '..'} for p in relative.parts):
raise ValueError('Use a relative file path inside the development package')
path = root.joinpath(*relative.parts)
if not path.resolve().is_relative_to(root.resolve()):
raise ValueError('Development file escapes its package')
if any(p.is_symlink() for p in (path, *path.parents) if p != root.parent):
raise ValueError('Development files must not be symlinks')
return path
def _files(root: Path):
for path in sorted(root.rglob('*')):
if path.is_symlink():
raise ValueError('Development inputs must not contain symlinks')
if path.is_file():
yield path
def inventory(root: Path) -> dict[str, str]:
return {path.relative_to(root).as_posix(): sha256_file(path) for path in _files(root)}
def recordings(task):
from bench_builder.program_bench import discover_reference_recordings
return {item.session_id: item for item in discover_reference_recordings(task) if item.playable}
def draft_root(task, draft='default') -> Path:
return task.package_dir / 'development' / 'drafts' / _id(draft)
def ensure_default(task) -> Path:
root = draft_root(task)
with _LOCK:
if (root / 'selection.json').is_file():
return root
from bench_builder.program_bench import public_design_prompt_text, _prepare_workspace_assets
files = root / 'files'
files.mkdir(parents=True, exist_ok=True)
(files / 'instruction.md').write_text(public_design_prompt_text(task) or task.instruction, encoding='utf-8')
# Initial assets are ordinary editable files. No recording is selected
# implicitly; the author chooses the information condition explicitly.
(files / 'assets').mkdir(exist_ok=True)
_prepare_workspace_assets(task, files / 'assets')
_write(root / 'selection.json', {'recording_ids': []})
return root
def draft_files(task, draft='default') -> dict[str, Path]:
"""Resolve shared inputs and this draft's local edits without copying bytes."""
root = draft_root(task, draft)
selection = json.loads((root / 'selection.json').read_text())
shared = selection.get('shared_files', {})
if not isinstance(shared, dict):
raise ValueError('Invalid shared development files')
files = {path.relative_to(root / 'files').as_posix(): path for path in _files(root / 'files')}
for name, source in shared.items():
file_path(root / 'files', name)
if not isinstance(source, str):
raise ValueError('Invalid shared development file path')
parts = PurePosixPath(source).parts
if (len(parts) < 5 or parts[0] != 'development'
or parts[1] not in {'drafts', 'revisions'} or parts[3] != 'files'):
raise ValueError('Shared files must reference development inputs in this task')
_id(parts[2])
path = file_path(task.package_dir, source)
if name in files:
continue
if not path.is_file():
raise ValueError(f'Shared development file is unavailable: {name}')
files[name] = path
return dict(sorted(files.items()))
def resolve_draft_file(task, draft, name) -> Path:
file_path(draft_root(task, draft) / 'files', name)
path = draft_files(task, draft).get(name)
if path is None:
raise ValueError('Development file was not found')
return path
def read_state(task, draft='default') -> dict:
if draft == 'default':
ensure_default(task)
root = draft_root(task, draft)
selection = json.loads((root / 'selection.json').read_text())
files = draft_files(task, draft)
return {
'draftId': draft, 'recordingIds': selection['recording_ids'],
'name': selection.get('name', ''),
'buildOptions': selection.get('build_options', {}),
'recordingMode': selection.get('recording_mode', 'video'),
'instruction': files['instruction.md'].read_text(encoding='utf-8') if 'instruction.md' in files else '',
'files': [{'path': name, 'bytes': path.stat().st_size} for name, path in files.items()],
'recordings': [{'sessionId': sid, 'label': f'{item.track_id} · {sid}',
'videoUrl': f'/api/tasks/{task.task_id}/reference-studio/recordings/{sid}/video'}
for sid, item in recordings(task).items()],
}
def remove_recording_selection(task, session_id: str) -> None:
"""Unselect a deleted recording in editable drafts; preserve frozen revisions."""
with _LOCK:
for path in (task.package_dir / 'development' / 'drafts').glob('*/selection.json'):
selection = json.loads(path.read_text())
ids = selection.get('recording_ids', [])
if session_id in ids:
selection['recording_ids'] = [item for item in ids if item != session_id]
_write(path, selection)
def save(task, draft, instruction, recording_ids, recording_mode='video'):
if recording_mode not in {'video', 'session'}:
raise ValueError('Recording mode must be video or session')
with _LOCK:
root = draft_root(task, draft)
if not (root / 'selection.json').is_file():
raise ValueError('Development draft was not found')
available = recordings(task)
if any(sid not in available for sid in recording_ids):
raise ValueError('A selected recording is unavailable')
selection = json.loads((root / 'selection.json').read_text())
(root / 'files').mkdir(exist_ok=True)
(root / 'files' / 'instruction.md').write_text(instruction, encoding='utf-8')
selection.get('shared_files', {}).pop('instruction.md', None)
selection.update(recording_ids=list(dict.fromkeys(recording_ids)), recording_mode=recording_mode)
_write(root / 'selection.json', selection)
return read_state(task, draft)
def write_file(task, draft, name, content: bytes | None):
with _LOCK:
root = draft_root(task, draft)
if not (root / 'selection.json').exists():
raise ValueError('Development draft was not found')
path = file_path(root / 'files', name)
selection = json.loads((root / 'selection.json').read_text())
if content is None:
path.unlink(missing_ok=True)
else:
if any(other != name and (other.startswith(name + '/') or name.startswith(other + '/'))
for other in draft_files(task, draft)):
raise ValueError('Development file conflicts with an existing file or directory')
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
selection.get('shared_files', {}).pop(name, None)
_write(root / 'selection.json', selection)
return read_state(task, draft)
def named_drafts(task) -> list[dict]:
"""List saved build tasks without reading or hashing their shared media."""
result = []
for path in sorted((task.package_dir / 'development/drafts').glob('*/selection.json')):
selection = json.loads(path.read_text())
if selection.get('name'):
result.append({'draftId': path.parent.name, 'name': selection['name']})
return result
def duplicate(task, *, source='default', revision=None, name=None, build_options=None):
if name is not None and (not name.strip() or len(name) > 200 or any(ord(c) < 32 for c in name)):
raise ValueError('Build task name must contain 1 to 200 printable characters')
with _LOCK:
ensure_default(task)
draft = uuid.uuid4().hex
target = draft_root(task, draft)
if revision:
original = task.package_dir / 'development' / 'revisions' / _id(revision)
verify(original)
files = {path.relative_to(original / 'files').as_posix(): path for path in _files(original / 'files')}
selection = {'recording_ids': []}
else:
original = draft_root(task, source)
files = draft_files(task, source)
selection = json.loads((original / 'selection.json').read_text())
# Instructions and recording selection belong to the new experiment.
# Large reference files stay at their existing paths; edits create local overrides.
(target / 'files').mkdir(parents=True)
if 'instruction.md' in files:
(target / 'files/instruction.md').write_text(files['instruction.md'].read_text(encoding='utf-8'), encoding='utf-8')
selection['shared_files'] = {
name: path.relative_to(task.package_dir).as_posix()
for name, path in files.items() if name != 'instruction.md'
}
if name is not None:
selection['name'] = name.strip()
else:
selection.pop('name', None)
if build_options is not None:
selection['build_options'] = build_options
_write(target / 'selection.json', selection)
return read_state(task, draft)
def unreferenced_drafts(task, delete=()) -> list[dict]:
"""Report unnamed drafts that no other draft shares files from; delete only the ids given.
Nothing calls this automatically. ``default`` and named drafts are never listed.
``bytes`` is what deleting a draft frees: the files it holds itself, not the shared
files it points to. A listed draft can still be in use (the Build page keeps its
current draft unnamed), so read the report first and pass back the ids to delete.
A draft that only a listed draft references is listed once that one is gone.
"""
with _LOCK:
drafts = task.package_dir / 'development' / 'drafts'
selections = {path.parent.name: json.loads(path.read_text())
for path in sorted(drafts.glob('*/selection.json'))}
referenced = set()
for draft, selection in selections.items():
shared = selection.get('shared_files', {})
if not isinstance(shared, dict):
raise ValueError(f'Invalid shared development files in draft {draft}')
for source in shared.values():
parts = PurePosixPath(str(source)).parts
# Compared without case: on Windows both spellings are one directory.
if (parts[:2] == ('development', 'drafts') and len(parts) > 2
and parts[2].casefold() != draft.casefold()):
referenced.add(parts[2].casefold())
report = [
{'draftId': draft, 'bytes': sum(
path.lstat().st_size for path in (drafts / draft).rglob('*')
if path.is_file() and not path.is_symlink())}
for draft, selection in selections.items()
if draft.casefold() != 'default' and not selection.get('name')
and draft.casefold() not in referenced
]
delete = set(delete)
unlisted = delete - {row['draftId'] for row in report}
if unlisted:
raise ValueError(f'Not an unnamed, unreferenced draft: {", ".join(sorted(unlisted))}')
for row in report:
row['deleted'] = row['draftId'] in delete
if row['deleted']:
shutil.rmtree(drafts / row['draftId']) # A directory name listed above.
return report
def _frozen_files(revisions: Path) -> dict[str, list[tuple[Path, str]]]:
"""Index the files that existing revisions record, by sha256, without hashing them."""
held: dict[str, list[tuple[Path, str]]] = {}
for manifest in revisions.glob('*/inputs.json'):
if manifest.parent.name.startswith('.'):
continue # A staging directory, not a revision.
try:
for name, digest in json.loads(manifest.read_text())['files'].items():
held.setdefault(digest, []).append((manifest.parent / 'files', name))
except (OSError, ValueError, LookupError, AttributeError, TypeError):
continue # An unreadable revision only loses its chance to share bytes.
return held
def _keep(source, destination, *, held: dict[str, list[tuple[Path, str]]]) -> None:
"""Freeze one file, hard-linking bytes that a frozen file already holds.
Links are only made between frozen files. The source is never linked: it may be
a draft file, and ``write_file`` edits drafts in place.
"""
source, destination = Path(source), Path(destination)
digest = sha256_file(source)
for root, name in held.get(digest, ()):
try:
os.link(file_path(root, name), destination)
except (OSError, ValueError):
continue # Missing, or this file system cannot link it.
if sha256_file(destination) == digest:
return
destination.unlink() # That frozen file changed; do not spread it.
shutil.copy2(source, destination)
held.setdefault(digest, []).append((destination.parent, destination.name))
def _link_or_copy(source, destination) -> None:
try:
os.link(source, destination)
except OSError:
shutil.copy2(source, destination)
def freeze(task, draft='default') -> Path:
"""Snapshot a draft as a revision whose files share storage with earlier revisions.
A revision is still a complete ``files/`` tree. A file whose bytes another revision
of this task already holds is a hard link to them instead of another copy, and falls
back to a copy where hard links are unavailable.
"""
with _LOCK:
if draft == 'default':
ensure_default(task)
root = draft_root(task, draft)
selection = json.loads((root / 'selection.json').read_text())
selected = selection['recording_ids']
revisions = task.package_dir / 'development' / 'revisions'
revisions.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=revisions, prefix='.preparing-') as temporary:
staged = Path(temporary)
keep = functools.partial(_keep, held=_frozen_files(revisions))
files = draft_files(task, draft)
shared_revisions = {
task.package_dir / 'development/revisions' / path.relative_to(task.package_dir).parts[2]
for path in files.values()
if path.relative_to(task.package_dir).parts[:2] == ('development', 'revisions')
}
for shared in shared_revisions:
verify(shared)
(staged / 'files').mkdir()
for name, source in files.items():
destination = file_path(staged / 'files', name)
destination.parent.mkdir(parents=True, exist_ok=True)
keep(source, destination)
sources = []
available = recordings(task)
for sid in selected:
if sid not in available:
raise ValueError(f'Selected recording is unavailable: {sid}')
item = available[sid]
if selection.get('recording_mode') == 'session':
target = file_path(staged / 'files', f'recordings/{_id(sid)}')
if item.session_dir.is_symlink():
raise ValueError('Recording sessions must not be symlinks')
list(_files(item.session_dir)) # Reject links before copying any session files.
shutil.copytree(item.session_dir, target, copy_function=keep)
sources.append({'recording_id': sid, 'mode': 'session', 'path': f'recordings/{sid}'})
continue
from bench_builder.recording_media import browser_video
video = browser_video(item.effective_video_path)
target = file_path(staged / 'files', f'recordings/{_id(sid)}{video.suffix.lower()}')
if target.exists():
raise ValueError(f'Recording filename already exists: {target.name}')
target.parent.mkdir(parents=True, exist_ok=True)
keep(video, target)
sources.append({'recording_id': sid, 'video_sha256': sha256_file(target)})
from . import checkpoints
entrances = checkpoints.read(task)
associations = {sid: key for sid, key in entrances['recordings'].items() if sid in selected}
if entrances['checkpoints'] and (selected or not (staged / 'files/checkpoints.json').exists()):
_write(staged / 'files' / 'checkpoints.json', {
'checkpoints': entrances['checkpoints'],
'recordings': associations,
})
manifest = {'files': inventory(staged / 'files'), 'recordings': sources}
revision = hashlib.sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest()
manifest['revision'] = revision
_write(staged / 'inputs.json', manifest)
destination = revisions / revision
if not destination.exists():
shutil.copytree(staged, destination, copy_function=_link_or_copy)
verify(destination)
return destination
def verify(root: Path) -> dict:
metadata = json.loads((root / 'inputs.json').read_text())
if inventory(root / 'files') != metadata['files']:
raise ValueError('Frozen development inputs changed')
expected = hashlib.sha256(json.dumps({k: v for k, v in metadata.items() if k != 'revision'}, sort_keys=True).encode()).hexdigest()
if expected != metadata['revision']:
raise ValueError('Development input revision changed')
return metadata
def extract_screenshots(task, draft, recording_id, count=12):
"""Materialize screenshots and remove this video's selection explicitly."""
import imageio_ffmpeg
if not 1 <= count <= 120:
raise ValueError('Choose between 1 and 120 screenshots')
with _LOCK:
item = recordings(task).get(recording_id)
if item is None:
raise ValueError('Recording was not found')
root = draft_root(task, draft)
selection = json.loads((root / 'selection.json').read_text())
_, duration = imageio_ffmpeg.count_frames_and_secs(str(item.effective_video_path))
if duration <= 0:
raise ValueError('Recording duration is unavailable')
with tempfile.TemporaryDirectory(prefix='gbb-development-frames-') as temporary:
try:
subprocess.run(
[imageio_ffmpeg.get_ffmpeg_exe(), '-v', 'error', '-i', str(item.effective_video_path),
'-vf', f'fps={count / duration}', '-frames:v', str(count),
str(Path(temporary) / 'frame-%04d.png')],
check=True, timeout=180, capture_output=True,
)
except subprocess.SubprocessError as exc:
raise ValueError('Could not extract screenshots from this recording') from exc
target = file_path(root / 'files', f'screenshots/{_id(recording_id)}-{uuid.uuid4().hex[:8]}')
shutil.copytree(temporary, target)
selection['recording_ids'] = [sid for sid in selection['recording_ids'] if sid != recording_id]
_write(root / 'selection.json', selection)
return read_state(task, draft)
def import_task_assets(task, draft):
"""Copy the current saved asset selection without requiring publication approval."""
from bench_builder.program_bench import load_public_pack_review, _inside, _reject_links
with _LOCK:
root = draft_root(task, draft)
if not (root / 'selection.json').exists():
raise ValueError('Development draft was not found')
review = load_public_pack_review(task)
if review is None:
raise ValueError('Save an asset selection on the task first')
existing_files = draft_files(task, draft)
with tempfile.TemporaryDirectory(prefix='.assets-', dir=root) as temporary:
staged = []
for item in review.assets:
if not item.included:
continue
if item.blocked_reason:
raise ValueError(f'Asset is not eligible: {item.source_path}')
source = _inside(task.reference_dir, item.source_path)
_reject_links(source, label='selected development asset')
snapshot = Path(temporary) / str(len(staged))
shutil.copyfile(source, snapshot)
if sha256_file(snapshot) != item.sha256:
raise ValueError('Selected asset changed; refresh the task asset selection')
relative = item.destination_path.removeprefix('public/assets/').removeprefix('public/')
name = 'assets/' + relative
destination = file_path(root / 'files', name)
existing = existing_files.get(name)
if existing is not None and sha256_file(existing) != item.sha256:
raise ValueError(f'Asset would replace an edited development file: {relative}')
staged.append((destination, snapshot))
for destination, snapshot in staged:
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(snapshot, destination)
return read_state(task, draft)
def prepare_progress_contract(run_dir: Path) -> None:
"""Provide a fixed fallback without replacing any supplied or retained contract."""
candidate = run_dir / 'candidate'
paths = (
run_dir / 'public-inputs/video_agent/analysis/game_design.json',
run_dir / 'progress-contract.json',
candidate / 'game_design.json',
)
existing = next((path for path in paths if path.is_file()), None)
if existing is not None:
if not (candidate / 'game_design.json').exists():
shutil.copy2(existing, candidate / 'game_design.json')
return
if (run_dir / 'agent/progress/snapshots.jsonl').is_file():
return
ledger = candidate / 'builder_checks.json'
if ledger.is_file():
checks = json.loads(ledger.read_text()).get('requirement_checks')
if not isinstance(checks, list) or not checks:
raise ValueError('Existing checklist has no requirements; cannot replace it with a fallback')
rows = [{'id': row.get('requirement_id', row.get('id')),
'acceptance': row.get('acceptance') or row.get('description') or row.get('reason') or row.get('requirement_id') or row.get('id')}
for row in checks]
ids = [row['id'] for row in rows]
if any(not isinstance(key, str) or not key.strip() for key in ids) or len(ids) != len(set(ids)):
raise ValueError('Existing checklist must have unique nonempty requirement IDs')
contract = {'observable_requirements': rows, 'source': 'retained_legacy_checklist'}
_write(run_dir / 'progress-contract.json', contract)
_write(candidate / 'game_design.json', contract)
return
supplied = run_dir / 'public-inputs/game_design.json'
contract = json.loads(supplied.read_text(encoding='utf-8')) if supplied.is_file() else {
'observable_requirements': [{
'id': 'recreate-game',
'acceptance': 'Recreate the game according to the supplied development instructions and files.',
}],
'generated_fallback': True,
}
_write(run_dir / 'progress-contract.json', contract)
_write(candidate / 'game_design.json', contract)