#!/usr/bin/env python3 """Prewarm the collection host's native cache through its online activation API.""" from __future__ import annotations import argparse from collections import Counter from concurrent.futures import ThreadPoolExecutor import copy import json import os from pathlib import Path import sys import time import uuid CODE_ROOT = Path(__file__).resolve().parents[2] for directory in (CODE_ROOT, Path(__file__).resolve().parent): if str(directory) not in sys.path: sys.path.insert(0, str(directory)) from collect_one import load_config, _env DEFAULT_ROLES = ('sofa', 'armchair', 'coffee_table', 'side_table', 'media_console', 'television', 'lamp', 'dining_table', 'dining_chair', 'bed', 'wardrobe', 'desk', 'chair', 'bookcase', 'kitchen_counter', 'upper_cabinet', 'range_hood', 'kitchen_sink', 'cooktop', 'refrigerator', 'sink', 'toilet', 'shower', 'mirror', 'rug', 'plant') def _selected_pairs(data): from asset_retrieval_audit import _role if not isinstance(data, dict): return set() if isinstance(data.get('rounds'), list): needs = data.get('needs', []) if not isinstance(needs, list) or any(not isinstance(n, dict) for n in needs): raise ValueError('dynamic selection needs must be a list of objects') roles = {n['entity_id']: n.get('role') for n in needs} # The last recorded selection supersedes provisional earlier choices. for row in reversed(data['rounds']): if not isinstance(row, dict): raise ValueError('dynamic selection round must be an object') selected = row.get('selected_asset_ids') if isinstance(selected, dict) and selected: return {(aid, _role(roles[eid])) for eid, aid in selected.items() if isinstance(aid, str) and aid and roles.get(eid)} return set() pairs = set() entities = data.get('entities', data.get('selections', data.get('selected', []))) if isinstance(entities, dict): entities = list(entities.values()) if not isinstance(entities, list): return pairs for entity in entities: if not isinstance(entity, dict): continue role = _role(entity.get('role') or entity.get('semantic_key') or entity.get('category')) selected = entity.get('selected', [entity]) if isinstance(selected, dict): selected = [selected] if not isinstance(selected, list): continue for row in selected: aid = row.get('asset_id') if isinstance(row, dict) else row if role and isinstance(aid, str) and aid: pairs.add((aid, role)) return pairs def history_frequencies(directory): """One vote per run/asset/role; final selection takes precedence over rounds.""" directory = Path(directory) if not directory.is_dir(): raise ValueError('history directory does not exist: ' + str(directory)) counts = Counter() notes = [] runs = {} for name in ('selection.json', 'dynamic_selection.json'): for path in sorted(directory.rglob(name)): runs.setdefault(path.parent, []).append(path) for paths in runs.values(): for path in paths: try: pairs = _selected_pairs(json.loads(path.read_text(encoding='utf-8'))) except (OSError, ValueError, TypeError, KeyError) as exc: notes.append(dict(path=str(path), reason=str(exc))) continue if pairs: counts.update(pairs) break notes.append(dict(path=str(path), reason='no recognized selected asset/role pairs')) rows = [dict(asset_id=aid, role=role, frequency=count) for (aid, role), count in sorted(counts.items(), key=lambda item: (-item[1], item[0]))] return rows, notes def choose_candidates(config, frequencies, *, limit, top_k, roles, retrieve=None): """Resolve current native envelopes; historical source bytes are never trusted.""" if retrieve is None: from dynamic_retrieval import retrieve_candidates retrieve = retrieve_candidates needs = ([dict(entity_id='history_' + str(i), role=row['role'], asset_id=row['asset_id']) for i, row in enumerate(frequencies)] if frequencies else [dict(entity_id='role_' + str(i), role=role) for i, role in enumerate(roles)]) metadata = {need['entity_id']: (frequencies[i] if frequencies else {}) for i, need in enumerate(needs)} candidates = [] notes = [] seen = set() # Respect the retriever's public 256-need limit, and stop after enough hits. for offset in range(0, len(needs), 256): chunk = needs[offset:offset + 256] result = retrieve(Path(config['retrieval_index']), chunk, seed=0, batch_size=1 if frequencies else top_k, appearance_index=config.get('appearance_index')) if result.get('status') != 'ok' or result.get('errors'): raise ValueError('retrieval failed: ' + json.dumps(result.get('errors', []))) by_entity = {row['entity_id']: row for row in result.get('needs', [])} # Interleave Top-K across roles so a small limit still covers several roles. ranked = [] for need in chunk: if need['entity_id'] not in by_entity: raise ValueError('retrieval omitted need: ' + need['entity_id']) hits = by_entity[need['entity_id']].get('hits', []) if not hits: notes.append(dict(asset_id=need.get('asset_id'), role=need['role'], reason='no current index hit')) ranked.append((need, hits)) ordered = ((need, hit) for need, hits in ranked for hit in hits) if frequencies else ( (need, hits[rank]) for rank in range(top_k) for need, hits in ranked if rank < len(hits)) for need, hit in ordered: if need.get('asset_id') and hit['asset_id'] != need['asset_id']: raise ValueError('retrieval returned a different pinned asset') identity = (hit['asset_id'], need['role']) if identity in seen: continue seen.add(identity) row = copy.deepcopy(hit) row.update(role=need['role'], entity_id=need['entity_id'], prewarm_frequency=metadata[need['entity_id']].get('frequency', 0)) candidates.append(row) if len(candidates) >= limit: return candidates, notes return candidates, notes def build_runtime(config, case): """Use exactly the runtime/path/material adapters used by task prepare.""" from prepare_task_runtime import prepare_runtime from task_scene_pipeline import configure_material_runtime from artifact_runtime import configure_artifact_reuse runtime = prepare_runtime(CODE_ROOT / 'engine', case, Path(config['rootfs']), runtime_template=Path(config['runtime_template']), prepared_asset_pool=Path(config['prepared_asset_pool']), supplemental_prepared_pool=Path(config['supplemental_prepared_pool']), collision_frame_mappings=Path(config['collision_frame_mappings'])) configure_material_runtime(runtime, config['mdl_sdk_root'], config['mdl_sdk_python'], material_artifact_index=config['material_artifact_index']) configure_artifact_reuse(runtime, config['artifact_cache_root']) runtime.update(retrieval_index=str(Path(config['retrieval_index']).resolve()), appearance_index=str(Path(config['appearance_index']).resolve()), attribute_release=str(Path(config['attribute_release']).resolve()), supplemental_prepared_pool=str(Path(config['prepared_cache']).resolve())) return runtime def _worker_limit(requested): try: cpus = len(os.sched_getaffinity(0)) except AttributeError: cpus = os.cpu_count() or 1 # The unchanged native Blender producer itself uses four threads. return min(requested, max(1, cpus // 4)) def prewarm(runtime, candidates, output, *, workers, activate=None): """Each task uses the public API's isolated, deadline-bounded native process.""" if activate is None: from native_asset_activation import activate_candidates activate = activate_candidates started = time.monotonic() output = Path(output) effective_workers = _worker_limit(workers) def work(item): index, row = item try: result = activate(copy.deepcopy(runtime), [copy.deepcopy(row)], output / ('asset_' + str(index).zfill(5))) assets = result.get('assets', []) asset = copy.deepcopy(assets[0]) if assets else dict(asset_id=row['asset_id'], activation_status='failed', error='activation returned no asset receipt') asset['worker_status'] = result.get('status') asset['worker_errors'] = result.get('errors', []) return asset except Exception as exc: return dict(asset_id=row['asset_id'], activation_status='failed', error=type(exc).__name__ + ': ' + str(exc)) with ThreadPoolExecutor(max_workers=effective_workers) as executor: assets = list(executor.map(work, enumerate(candidates))) prepared = sum(row.get('activation_status') == 'prepared' for row in assets) hits = sum(row.get('activation_status') == 'reused' for row in assets) failed = len(assets) - prepared - hits errors = sum(bool(row.get('worker_errors')) or row.get('worker_status') in ('failed', 'timed_out') for row in assets) return dict(schema='rhg.prewarm_cache.v1', status=('failed' if failed == len(assets) and assets else 'partial') if failed or errors else 'completed', selected_count=len(candidates), prepared_count=prepared, hit_count=hits, artifact_hit_count=sum(row.get('artifact_cache', {}).get('status') == 'reused' for row in assets), failed_count=failed, worker_error_count=errors, workers=effective_workers, requested_workers=workers, elapsed_s=time.monotonic() - started, artifact_cache_root=runtime.get('artifact_cache_root'), assets=assets) def _positive(value): number = int(value) if number < 1: raise argparse.ArgumentTypeError('must be positive') return number def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--config', type=Path, required=True) parser.add_argument('--from-runs', type=Path) parser.add_argument('--workers', type=_positive, default=2) parser.add_argument('--limit', type=_positive, default=64) parser.add_argument('--top-k', type=_positive, default=4) parser.add_argument('--roles', default=','.join(DEFAULT_ROLES)) parser.add_argument('--dry-run', action='store_true') parser.add_argument('--report', type=Path, help='Optional JSON report, also printed to stdout') args = parser.parse_args(argv) if args.top_k > 256: parser.error('--top-k must be at most 256') roles = list(dict.fromkeys(role.strip() for role in args.roles.split(',') if role.strip())) if not roles: parser.error('--roles must contain at least one role') started = time.monotonic() saved_environment = dict(os.environ) try: config = load_config(args.config) case_id = 'prewarm_' + time.strftime('%Y%m%d_%H%M%S') + '_' + uuid.uuid4().hex[:8] case = CODE_ROOT / 'engine/runs' / case_id environment = _env(config, case_id=case_id, case=case, log=case, gpu=None, library=config['library'], cache=Path(config['artifact_cache_root'])) os.environ.clear() os.environ.update(environment) frequencies, notes = history_frequencies(args.from_runs) if args.from_runs else ([], []) candidates, selection_notes = choose_candidates(config, frequencies, limit=args.limit, top_k=args.top_k, roles=roles) if args.dry_run: report = dict(schema='rhg.prewarm_cache.v1', status='dry_run', selected_count=len(candidates), prepared_count=0, hit_count=None, failed_count=0, requested_workers=args.workers, workers=_worker_limit(args.workers), artifact_cache_root=config['artifact_cache_root'], assets=[{k: row[k] for k in ('asset_id', 'role', 'prewarm_frequency')} for row in candidates]) else: if not candidates: raise ValueError('no candidates to prewarm; check history/index/roles') for name in ('TMPDIR', 'XDG_CACHE_HOME', 'CUDA_CACHE_PATH', 'TORCH_HOME'): Path(environment[name]).mkdir(parents=True, exist_ok=True) runtime = build_runtime(config, case) report = prewarm(runtime, candidates, case / 'activation', workers=args.workers) report['case'] = str(case) report.update(selection_source='history' if frequencies else 'role_top_k', notes=notes + selection_notes, total_elapsed_s=time.monotonic() - started) report_path = args.report or (case / 'prewarm_report.json' if not args.dry_run else None) if report_path is not None: from prepare_task_runtime import _write report['report_path'] = str(report_path.resolve()) _write(report_path, report) print(json.dumps(report, ensure_ascii=False, indent=2)) return 0 if report['status'] in ('completed', 'dry_run') else 1 except (OSError, ValueError) as exc: print('prewarm: ' + str(exc), file=sys.stderr) return 2 finally: os.environ.clear() os.environ.update(saved_environment) if __name__ == '__main__': raise SystemExit(main())