Merge branch 'main' into fix/home-leak-tests

This commit is contained in:
Ludovic Marie
2026-10-25 01:09:27 +02:00
committed by GitHub
230 changed files with 6340 additions and 8129 deletions
-297
View File
@@ -1,297 +0,0 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'none'; base-uri 'none'; form-action 'none'">
<title>Horizon — Compare runs</title>
<style>
:root{color-scheme:light;--ink:#192920;--muted:#65726a;--line:#d8ded8;--paper:#f6f7f3;--base:#247854;--candidate:#bc642f}
*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}main{max-width:1100px;margin:auto;padding:40px 28px 70px}header{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:26px}.brand{display:flex;align-items:center;gap:11px;font-weight:700}.mark{width:30px;height:30px;background:var(--base);box-shadow:inset 0 -10px #195a3c,inset -10px 0 #2a8c62}.badge{border:1px solid var(--line);padding:4px 10px;border-radius:20px;color:var(--muted);font-size:12px}h1{font-size:clamp(30px,5vw,44px);letter-spacing:-1.3px;line-height:1.15;margin:0 0 10px}h2{font-size:20px;letter-spacing:-.3px;margin:0}p{margin:8px 0;color:var(--muted)}.intro{max-width:750px;margin-bottom:26px}.uploads{display:grid;grid-template-columns:1fr 1fr;gap:18px}.card{background:white;border:1px solid var(--line);border-radius:12px;padding:22px;min-width:0}.card-top{display:flex;gap:9px;align-items:center;margin-bottom:6px}.dot{width:9px;height:9px;border-radius:50%;background:var(--base)}.candidate .dot{background:var(--candidate)}input[type=file]{width:100%;font:inherit;font-size:13px;color:var(--muted);margin-top:15px}input::file-selector-button,button{font:inherit;font-size:13px;background:white;color:var(--ink);border:1px solid var(--line);border-radius:6px;padding:9px 13px;cursor:pointer;margin-right:10px}button:disabled{opacity:.45;cursor:default}input:focus-visible,button:focus-visible{outline:3px solid #80b998;outline-offset:3px}.status{font-size:13px;overflow-wrap:anywhere;margin-top:14px;min-height:20px}.error{color:#a23624}.details{font-size:12px;color:var(--muted);margin:12px 0 0;display:grid;grid-template-columns:100px 1fr;gap:4px 12px;overflow-wrap:anywhere}.details dt,.details dd{margin:0}.details dt{color:var(--ink)}.empty{border:1px dashed var(--line);border-radius:12px;padding:34px;text-align:center;margin-top:22px}.section{margin-top:24px}.section-top{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:14px}.notice{overflow-wrap:anywhere;background:#fff8e8;border:1px solid #e7d9af;border-radius:9px;padding:14px 18px;margin-bottom:18px;font-size:13px}.notice p{color:#685c3f;margin:3px 0}.notice ul{padding-left:18px;margin:8px 0}.metrics{overflow:auto;border:1px solid var(--line);border-radius:10px;background:white}table{width:100%;border-collapse:collapse;white-space:nowrap;text-align:right;font-variant-numeric:tabular-nums}th,td{padding:12px 18px;border-bottom:1px solid #edf0ea}th{font-size:12px;font-weight:600;color:var(--muted)}th:first-child,td:first-child{text-align:left}tr:last-child td{border-bottom:0}td:first-child{font-weight:500}td:last-child{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:13px}.chart{padding:20px;background:white;border:1px solid var(--line);border-radius:10px}.chart svg{display:block;width:100%;height:auto}.chart-tools{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px}.chart-tools label{font-size:13px;color:var(--muted)}.chart-info{min-height:22px;font-size:13px;color:var(--muted);font-variant-numeric:tabular-nums}.footnote{font-size:12px;margin-top:15px;max-width:850px}.hidden{display:none!important}footer{margin-top:30px;border-top:1px solid var(--line);padding-top:16px;color:var(--muted);font-size:12px}.legend{display:flex;gap:18px;font-size:12px}.legend span{display:flex;gap:6px;align-items:center}@media(max-width:650px){main{padding:24px 16px 40px}.uploads{grid-template-columns:1fr}.card{padding:18px}header{align-items:flex-start}.section-top{align-items:flex-start}th,td{padding:10px 12px}.badge{white-space:nowrap;font-size:11px}.chart{padding:12px}}
</style>
<main>
<header><div class="brand"><span class="mark" aria-hidden="true"></span>Horizon</div><span class="badge">Offline · files stay on your device</span></header>
<h1>Compare your runs.</h1>
<p class="intro">Choose two Horizon benchmark JSON files from your instance’s <strong>horizon-benchmarks</strong> folder. Add each matching CSV to see frame spikes. Compare frames with frames, or server ticks with server ticks.</p>
<div class="uploads">
<section class="card" aria-labelledby="baselineTitle"><div class="card-top"><span class="dot" aria-hidden="true"></span><h2 id="baselineTitle">Baseline</h2></div><p>Vanilla or your previous configuration.</p><input id="baselineFiles" type="file" multiple accept=".json,.csv" aria-label="Choose baseline JSON and optional CSV"><div id="baselineStatus" class="status" role="status">No report selected.</div><dl id="baselineDetails" class="details"></dl></section>
<section class="card candidate" aria-labelledby="candidateTitle"><div class="card-top"><span class="dot" aria-hidden="true"></span><h2 id="candidateTitle">Candidate</h2></div><p>The configuration you want to evaluate.</p><input id="candidateFiles" type="file" multiple accept=".json,.csv" aria-label="Choose candidate JSON and optional CSV"><div id="candidateStatus" class="status" role="status">No report selected.</div><dl id="candidateDetails" class="details"></dl></section>
</div>
<div id="empty" class="empty"><strong>Your measurements go here.</strong><p>Record with F8 in the game. Keep the world, route, graphics settings and warm-up consistent.</p></div>
<p id="comparisonError" class="error hidden" role="alert"></p>
<section id="results" class="section hidden">
<div class="section-top"><h2 id="resultsTitle">Frame comparison</h2><button id="export" type="button">Save comparison</button></div>
<div id="notices" class="notice"></div>
<div class="metrics"><table aria-label="Benchmark comparison"><thead><tr><th>Measurement</th><th>Baseline</th><th>Candidate</th><th>Change</th></tr></thead><tbody id="metricRows"></tbody></table></div>
<p class="footnote">Changes are candidate versus baseline. Higher FPS is better; lower frame/tick duration, memory and CPU use is usually better. Check workload differences before attributing any change to an optimization.</p>
<section id="chartSection" class="section hidden"><div class="chart"><div class="chart-tools"><h2 id="chartTitle">Frame pacing</h2><label><input id="logScale" type="checkbox" checked> Log scale</label></div><div class="legend"><span><i class="dot"></i>Baseline</span><span><i class="dot" style="background:var(--candidate)"></i>Candidate</span></div><svg id="timeline" viewBox="0 0 960 300" role="img" aria-label="Recorded duration timeline"></svg><div id="chartInfo" class="chart-info">Move over the chart to inspect a time bucket.</div><p id="chartNote" class="footnote"></p></div></section>
<p id="csvHint" class="footnote"></p>
</section>
<footer>No installation, account or network access is needed. Repeat at least three matched runs and test fresh terrain separately from a warm cache. Heap/nonheap exclude native allocations. Process RSS is not a complete GPU/unified-memory measurement.</footer>
</main>
<script>
'use strict';
const SETTINGS=['minecraft','kind','os','os_version','architecture','gpu','graphics_backend','graphics_driver','server_runtime_kind','client_graphics_capture_status','java_version','heap_max_bytes','framebuffer_width','framebuffer_height','render_distance','simulation_distance','vsync','fps_limit','graphics_preset','ambient_occlusion','improved_transparency','mipmap_levels','entity_distance_scaling','entity_shadows','particles','clouds','cloud_range','fov','world_difficulty','dh_capture_status','dh_rendering_enabled','dh_renderer_mode','dh_lod_radius_chunks','dh_horizontal_quality','dh_vertical_quality','dh_max_horizontal_resolution','dh_transparency','dh_lod_shading','dh_lod_only_mode','dh_camera_quality_dropoff','dh_ambient_occlusion'];
const state={baseline:null,candidate:null},generation={baseline:0,candidate:0};
let comparison=null,chartData=null;
const $=id=>document.getElementById(id);
const number=value=>typeof value==='number'&&Number.isFinite(value);
const text=(tag,value)=>{const element=document.createElement(tag);element.textContent=String(value);return element;};
const format=value=>number(value)?new Intl.NumberFormat(undefined,{maximumFractionDigits:2}).format(value):'—';
function validateReport(report){
if(!report||report.schema!==1||!['frames','ticks'].includes(report.kind))throw Error('Choose a Horizon frame or server-tick JSON report.');
if(!report.stats||!Number.isInteger(report.stats.count)||report.stats.count<1||report.stats.count>300000)throw Error('This report has no valid sample count. Record focused gameplay with F8 first.');
for(const key of ['meanRate','lowOnePercentRate','meanMs','p50Ms','p95Ms','p99Ms','maxMs']){
if(!number(report.stats[key])||report.stats[key]<0)throw Error('This report has missing or invalid timing measurements.');
}
if(!number(report.elapsed_seconds)||report.elapsed_seconds<=0)throw Error('This report has an invalid recording duration.');
return report;
}
function parseCsv(source,count){
const lines=source.trim().split(/\r?\n/);
if(lines.shift()!=='sample,duration_ns')throw Error('CSV header does not match a Horizon recording.');
if(lines.length!==count||lines.length>300000)throw Error('CSV sample count does not match this JSON report.');
return lines.map((line,index)=>{
const fields=line.split(','),sample=Number(fields[0]),duration=Number(fields[1]);
if(fields.length!==2||sample!==index||!Number.isSafeInteger(duration)||duration<=0)throw Error('CSV contains an invalid sample.');
return duration/1e6;
});
}
function softwareWarnings(a,b){
const warnings=[];
for(const key of ['java_vendor','java_vm_name','java_runtime_version']){
if(![a,b].every(r=>typeof r[key]==='string'&&r[key].length))warnings.push(key+' was not captured in both reports; Java implementation equivalence is unknown.');
else if(a[key]!==b[key])warnings.push('Software '+key+' differs. Treat it as an explicit experiment variable.');
}
const mods=[a,b].map(r=>Array.isArray(r.mods)&&r.mods.every(entry=>typeof entry==='string'&&entry.length)?new Set(r.mods):null);
if(mods.some(entries=>entries===null))warnings.push('Loaded mod versions were not captured in both reports; software equivalence is unknown.');
else{
const only=[...mods[0]].filter(entry=>!mods[1].has(entry)).sort(),other=[...mods[1]].filter(entry=>!mods[0].has(entry)).sort();
if(only.length||other.length){
warnings.push('Loaded mod versions differ. Treat added, removed or upgraded mods as explicit experiment variables.');
for(const [label,entries] of [['baseline',only],['candidate',other]])if(entries.length)warnings.push('Only '+label+': '+entries.slice(0,12).join(', ')+(entries.length>12?'; '+(entries.length-12)+' more':'')+'.');
}
}
return warnings;
}
const TICK_STATE_FIELDS=['configured_tick_rate','frozen','stepping','sprinting','runs_game_elements'];
function tickStateAvailable(r){
if(r.tick_state_capture_status!=='sampled_server_ticks'||!Number.isSafeInteger(r.tick_state_samples)||r.tick_state_samples<=0)return false;
for(const boundary of ['tick_state_first','tick_state_last']){
const s=r[boundary];
if(!s||!number(s.configured_tick_rate)||s.configured_tick_rate<1||TICK_STATE_FIELDS.slice(1).some(key=>typeof s[key]!=='boolean'))return false;
}
if(!Array.isArray(r.tick_state_changed)||r.tick_state_changed.some(key=>!TICK_STATE_FIELDS.includes(key)))return false;
return ['frozen','stepping','sprinting','suppressed','nonstandard_rate'].every(key=>{
const v=r['tick_state_'+key+'_samples'];return Number.isSafeInteger(v)&&v>=0&&v<=r.tick_state_samples;
});
}
function compareTickStates(a,b){
const differences=[],warnings=[],available=[tickStateAvailable(a),tickStateAvailable(b)];
for(const [index,label,r] of [[0,'Baseline',a],[1,'Candidate',b]]){
if(!available[index]){warnings.push(label+' tick-manager state was not captured or is invalid; simulation workload equivalence is unknown.');continue;}
if(r.tick_state_changed.length){
differences.push({setting:label+' tick-manager state changed during recording',baseline:label==='Baseline'?r.tick_state_changed:null,candidate:label==='Candidate'?r.tick_state_changed:null});
warnings.push(label+' sampled tick-manager changes: '+r.tick_state_changed.join(', ')+'.');
}
const abnormal=['frozen','stepping','sprinting','suppressed','nonstandard_rate'].filter(key=>r['tick_state_'+key+'_samples']>0);
if(abnormal.length)warnings.push(label+' includes tick-manager samples with '+abnormal.join(', ')+'; interpret execution times as this workload.');
}
if(available.every(Boolean))for(const boundary of ['tick_state_first','tick_state_last'])for(const key of TICK_STATE_FIELDS){
if(a[boundary][key]!==b[boundary][key])differences.push({setting:boundary+'.'+key,baseline:a[boundary][key],candidate:b[boundary][key]});
}
warnings.push('Tick-manager state is sampled after measured server invocations. Changes entirely between samples, paused intervals and completed world work are not verified.');
return{differences,warnings};
}
function serverContextWarnings(a,b){
const warnings=[];
for(const [label,r] of [['Baseline',a],['Candidate',b]]){
if(!['integrated','dedicated'].includes(r.server_runtime_kind))warnings.push(label+' server runtime kind was not captured; integrated/dedicated equivalence is unknown.');
if(r.server_runtime_kind==='integrated'&&!(r.client_graphics_capture_status==='captured_at_recording_start'&&['gpu','graphics_backend','graphics_driver'].every(key=>typeof r[key]==='string'&&r[key].trim().length)))warnings.push(label+' integrated-server client graphics were not captured; shared rendering workload is unknown.');
}
warnings.push('Integrated-server graphics context is a recording-start snapshot; later graphics changes and full client workload equivalence are not verified.');
return warnings;
}
function compareReports(a,b){
if(a.kind!==b.kind)throw Error('Compare frame runs with frame runs, or tick runs with tick runs.');
const differences=SETTINGS.filter(key=>JSON.stringify(a[key])!==JSON.stringify(b[key])).map(key=>({setting:key,baseline:a[key]??null,candidate:b[key]??null}));
if(a.kind==='ticks'&&a.peak_players!==b.peak_players)differences.push({setting:'peak_players',baseline:a.peak_players??null,candidate:b.peak_players??null});
const warnings=['World, camera route and terrain-cache warm-up still need to match. These are not verified by the captured settings.'];
warnings.push(...softwareWarnings(a,b));
if(a.kind==='ticks'){
warnings.push(...serverContextWarnings(a,b));
const tick=compareTickStates(a,b);differences.push(...tick.differences);warnings.push(...tick.warnings);
}
for(const key of ['compact_object_headers','garbage_collectors']){
if(!(key in a)||!(key in b))warnings.push(key+' was not captured in both reports; JVM configuration equivalence is unknown.');
else if(JSON.stringify(a[key])!==JSON.stringify(b[key]))warnings.push('JVM '+key+' differs. Treat it as an explicit experiment variable.');
}
if(a.kind==='frames'){
for(const key of ['adaptive_budget_enabled','adaptive_target_fps','precise_worker_pacing','debounce_queue_wait','wakeable_idle_wait','dispatch_retry_backoff','tick_membership_dedup','empty_culling_whitelist','culling_ray_scratch','terrain_position_arithmetic','terrain_quad_reuse','interruptible_terrain_read','dh_thread_count','dh_runtime_ratio']){
if(key in a&&key in b&&JSON.stringify(a[key])!==JSON.stringify(b[key]))warnings.push('Experiment '+key+' differs.');
}
for(const [label,r] of [['Baseline',a],['Candidate',b]]){
if(!['available','not_installed'].includes(r.dh_capture_status))warnings.push(label+' distant-terrain configuration was not captured; quality equivalence is unknown.');
if(Array.isArray(r.visual_settings_changed)&&r.visual_settings_changed.length){
differences.push({setting:label+' visual settings changed during recording',baseline:label==='Baseline'?r.visual_settings_changed:null,candidate:label==='Candidate'?r.visual_settings_changed:null});
warnings.push(label+' visual settings changed between capture boundaries: '+r.visual_settings_changed.join(', ')+'.');
}
}
}
if(Math.abs(a.elapsed_seconds-b.elapsed_seconds)>Math.max(2,Math.min(a.elapsed_seconds,b.elapsed_seconds)*.1))warnings.push('Recording durations differ. Match durations when comparing memory peaks and collection totals.');
for(const [label,r] of [['Baseline',a],['Candidate',b]]){
if(r.elapsed_seconds<60)warnings.push(label+' recording is shorter than 60 seconds. Use longer repeated runs.');
if(r.dropped_samples)warnings.push(label+' exceeded the recording buffer; '+r.dropped_samples+' samples were dropped.');
if(r.kind==='frames'&&r.excluded_frames)warnings.push(label+' excluded '+r.excluded_frames+' menu, paused or unfocused frame starts. Process CPU still spans the whole recording.');
}
const rows=[];
const add=(label,key,unit,scale=1,stats=false)=>{
const av=stats?a.stats[key]:a[key],bv=stats?b.stats[key]:b[key];
if(number(av)&&number(bv))rows.push({label,key,unit,baseline:av/scale,candidate:bv/scale,change_percent:av?100*(bv/av-1):null});
};
if(a.kind==='frames'){
add('Average FPS','meanRate','FPS',1,true);add('Slowest 1% average','lowOnePercentRate','FPS',1,true);
}else{
add('Average tick duration','meanMs','ms',1,true);add('Observed tick rate','observed_ticks_per_second','TPS');
warnings.push('Tick durations exclude scheduler sleep. Observed TPS counts measured invocations, including frozen ticks, and includes recording time spent paused; tick execution capacity is not TPS.');
}
add('95th percentile duration','p95Ms','ms',1,true);add('99th percentile duration','p99Ms','ms',1,true);add('Longest duration','maxMs','ms',1,true);
add('Sampled peak process RSS','process_rss_peak_sampled_bytes','MiB',1048576);add('Last sampled process RSS','process_rss_last_sampled_bytes','MiB',1048576);
add('Sampled peak JVM heap','heap_used_peak_sampled_bytes','MiB',1048576);add('JVM heap at end','heap_used_end_bytes','MiB',1048576);
add('Sampled peak nonheap','nonheap_used_peak_sampled_bytes','MiB',1048576);add('Average process CPU','process_cpu_mean_cores','cores');
if(number(a.gc_time_ms)&&number(b.gc_time_ms)){
const av=a.gc_time_ms/a.elapsed_seconds,bv=b.gc_time_ms/b.elapsed_seconds;
rows.push({label:'GC collection time / second',key:'gc_collection_ms_per_second',unit:'ms/s',baseline:av,candidate:bv,change_percent:av?100*(bv/av-1):null});
}
warnings.push('Memory peaks are sampled and can miss short spikes. RSS includes resident JVM and native pages, but is not a complete GPU/unified-memory measurement. Heap/nonheap measure JVM pools only. CPU includes the whole process and integrated server.');
warnings.push('GC collection time comes from collector MXBean counters. It may include concurrent cycles and overlapping collector phases; it is not a measured stop-the-world pause total. Use JFR pause events for that comparison.');
for(const [label,r] of [['Baseline',a],['Candidate',b]])if(number(r.process_rss_last_sample_age_ms)&&r.process_rss_last_sample_age_ms>2500)warnings.push(label+' resident-memory sample is '+format(r.process_rss_last_sample_age_ms/1000)+' seconds old. The background reader may be slow or unavailable.');
return{kind:a.kind,differences,warnings,metrics:rows};
}
function renderDetails(side){
const entry=state[side],target=$(side+'Details');target.replaceChildren();
if(!entry)return;
const r=entry.report,fields=[['Profile',r.profile||r.label||'Unlabeled'],['Recording',format(r.elapsed_seconds)+' s · '+format(r.stats.count)+' samples'],['Platform',[r.os,r.architecture].filter(Boolean).join(' ')||'Not captured']];
if(r.kind==='frames')fields.push(['Graphics',[r.gpu,r.graphics_backend].filter(Boolean).join(' · ')||'Not captured'],['Window',number(r.framebuffer_width)?r.framebuffer_width+' × '+r.framebuffer_height:'Not captured'],['Experiments','Adaptive: '+(r.adaptive_budget_enabled?'on':'off')+' · precise pacing: '+(r.precise_worker_pacing?'on':'off')+' · queue wait: '+(r.debounce_queue_wait?'on':'off')]);
fields.push(['JVM', 'Compact headers: '+(r.compact_object_headers===true?'on':r.compact_object_headers===false?'off':'not captured')+' · GC: '+(Array.isArray(r.garbage_collectors)?r.garbage_collectors.join(', '):'not captured')]);
fields.push(['Java',[r.java_vendor,r.java_vm_name,r.java_runtime_version||r.java_version].filter(Boolean).join(' · ')||'Not captured']);
if(r.kind==='ticks'){
fields.push(['Server runtime',['integrated','dedicated'].includes(r.server_runtime_kind)?r.server_runtime_kind:'Not captured']);
if(r.server_runtime_kind==='integrated')fields.push(['Shared client graphics',r.client_graphics_capture_status==='captured_at_recording_start'?[r.gpu,r.graphics_backend,r.graphics_driver].filter(Boolean).join(' · ')+' (at recording start)':'Not captured']);
if(tickStateAvailable(r)){
const first=r.tick_state_first,last=r.tick_state_last;
fields.push(['Configured ticks',format(first.configured_tick_rate)+' / s at first sample · '+format(last.configured_tick_rate)+' / s at last sample']);
fields.push(['Tick-manager samples',r.tick_state_samples+' · frozen '+r.tick_state_frozen_samples+' · stepping '+r.tick_state_stepping_samples+' · sprinting '+r.tick_state_sprinting_samples+' · suppressed '+r.tick_state_suppressed_samples]);
fields.push(['Tick-manager changes',r.tick_state_changed.length?r.tick_state_changed.join(', '):'None observed']);
}else fields.push(['Tick-manager state','Not captured or invalid']);
}
if(r.kind==='frames'){
fields.push(['Distant terrain',r.dh_capture_status==='not_installed'?'Not installed':r.dh_capture_status==='available'?(r.dh_rendering_enabled?'Enabled':'Disabled')+' · '+r.dh_lod_radius_chunks+' chunk radius · '+r.dh_horizontal_quality+'/'+r.dh_vertical_quality+' quality · '+r.dh_max_horizontal_resolution+' resolution':'Not captured']);
if(number(r.dh_thread_count))fields.push(['Terrain workers',r.dh_thread_count+' · runtime ratio at start '+format(r.dh_runtime_ratio)+(number(r.visual_settings_end?.dh_runtime_ratio)?' / end '+format(r.visual_settings_end.dh_runtime_ratio):'')]);
if(number(r.fov))fields.push(['Field of view',format(r.fov)]);
if(r.world_difficulty)fields.push(['World difficulty',r.world_difficulty]);
fields.push(['Frame limit',r.fps_limit_unlimited===true||(r.minecraft==='26.3'&&number(r.fps_limit)&&r.fps_limit>=260)?'Uncapped':number(r.fps_limit)?r.fps_limit+' FPS':'not captured']);
if(r.adaptive_budget_enabled&&number(r.adaptive_target_fps))fields.push(['Adaptive frame goal',r.adaptive_target_fps+' FPS (not a cap)']);
}
fields.push(['Rejected dispatch retry', r.dispatch_retry_backoff===true?'on':r.dispatch_retry_backoff===false?'off':'not captured']);
fields.push(['Wakeable queue idle', r.wakeable_idle_wait===true?'on':r.wakeable_idle_wait===false?'off':'not captured']);
if(r.kind==='frames')fields.push(['Tick membership deduplication',r.tick_membership_dedup===true?'on':r.tick_membership_dedup===false?'off':'not captured']);
if(r.kind==='frames')fields.push(['Terrain quad reuse',r.terrain_quad_reuse===true?'on':r.terrain_quad_reuse===false?'off':'not captured']);
if(r.kind==='frames')fields.push(['Terrain position arithmetic',r.terrain_position_arithmetic===true?'on':r.terrain_position_arithmetic===false?'off':'not captured']);
if(r.kind==='frames')fields.push(['Culling ray scratch',r.culling_ray_scratch===true?'on':r.culling_ray_scratch===false?'off':'not captured']);
if(r.kind==='frames')fields.push(['Empty culling whitelist',r.empty_culling_whitelist===true?'on':r.empty_culling_whitelist===false?'off':'not captured']);
if(r.kind==='frames')fields.push(['Interruptible terrain read',r.interruptible_terrain_read===true?'on':r.interruptible_terrain_read===false?'off':'not captured']);
for(const [label,value]of fields)target.append(text('dt',label),text('dd',value));
if(Array.isArray(r.mods)&&r.mods.every(entry=>typeof entry==='string'&&entry.length)){
const versions=[...new Set(r.mods)].sort(),list=text('details','');
list.append(text('summary',versions.length+' loaded mods'),text('div',versions.join('\n')));
list.lastChild.style.whiteSpace='pre-wrap';
list.lastChild.style.maxHeight='16rem';list.lastChild.style.overflow='auto';
const value=text('dd','');value.append(list);target.append(text('dt','Software'),value);
}else target.append(text('dt','Software'),text('dd','Loaded mod versions not captured'));
}
async function loadFiles(side,files){
const token=++generation[side];state[side]=null;render();
const status=$(side+'Status');status.classList.remove('error');status.textContent='Reading files…';
try{
const list=Array.from(files),jsonFiles=list.filter(f=>f.name.toLowerCase().endsWith('.json')),csvFiles=list.filter(f=>f.name.toLowerCase().endsWith('.csv'));
if(list.length<1||list.length>2||jsonFiles.length!==1||csvFiles.length>1)throw Error('Choose one JSON report and, optionally, its matching CSV.');
if(jsonFiles[0].size>2*1024*1024||csvFiles.some(f=>f.size>16*1024*1024))throw Error('File is too large for a Horizon recording.');
const report=validateReport(JSON.parse(await jsonFiles[0].text()));
let samples=null,csvWarning=null;
if(csvFiles.length){
try{
if(csvFiles[0].name!==report.samples_file)throw Error('CSV filename does not match this report’s samples file.');
samples=parseCsv(await csvFiles[0].text(),report.stats.count);
const mean=samples.reduce((sum,value)=>sum+value,0)/samples.length;
if(Math.abs(mean-report.stats.meanMs)>Math.max(1e-6,report.stats.meanMs*1e-6)){
samples=null;throw Error('CSV durations do not match the timing summary in this JSON.');
}
}catch(error){csvWarning=error.message;}
}
if(token!==generation[side])return;
state[side]={report,samples,csvWarning,filename:jsonFiles[0].name};
status.textContent=jsonFiles[0].name+(samples?' · CSV loaded':'');
}catch(error){
if(token!==generation[side])return;
status.textContent=error instanceof SyntaxError?'This file is not valid JSON.':error.message;status.classList.add('error');
}
render();
}
function render(){
comparison=null;renderDetails('baseline');renderDetails('candidate');
$('results').classList.add('hidden');$('comparisonError').classList.add('hidden');$('empty').classList.toggle('hidden',!!state.baseline&&!!state.candidate);
if(!state.baseline||!state.candidate)return;
try{comparison=compareReports(state.baseline.report,state.candidate.report);}catch(error){$('comparisonError').textContent=error.message;$('comparisonError').classList.remove('hidden');return;}
$('results').classList.remove('hidden');$('resultsTitle').textContent=comparison.kind==='frames'?'Frame comparison':'Server tick comparison';
const notice=$('notices');notice.replaceChildren(text('strong',comparison.differences.length?'Captured settings differ — check the workload.':'Captured settings match. Check the route and warm-up too.'));
if(comparison.differences.length){const list=document.createElement('ul');for(const d of comparison.differences)list.append(text('li',d.setting+': '+JSON.stringify(d.baseline)+' → '+JSON.stringify(d.candidate)));notice.append(list);}
for(const warning of comparison.warnings)notice.append(text('p',warning));
const rows=$('metricRows');rows.replaceChildren();
for(const metric of comparison.metrics){const row=document.createElement('tr');row.append(text('td',metric.label),text('td',format(metric.baseline)+' '+metric.unit),text('td',format(metric.candidate)+' '+metric.unit),text('td',metric.change_percent===null?'—':(metric.change_percent>=0?'+':'')+format(metric.change_percent)+'%'));rows.append(row);}
const hints=[];for(const side of ['baseline','candidate'])if(state[side].csvWarning)hints.push((side==='baseline'?'Baseline: ':'Candidate: ')+state[side].csvWarning);
if(!state.baseline.samples||!state.candidate.samples)hints.push('Add each matching CSV alongside its JSON to draw both duration timelines.');
$('csvHint').textContent=hints.join(' ');drawChart();
}
function bucketSamples(samples,ticks){
const total=ticks?samples.length:samples.reduce((a,b)=>a+b,0)/1000,bucketSeconds=Math.max(total/1000,ticks?1:.001),buckets=[];
let time=0;
for(const duration of samples){time+=ticks?1:duration/1000;const index=Math.floor(time/bucketSeconds),last=buckets[buckets.length-1];if(last&&last.index===index)last.duration=Math.max(last.duration,duration);else buckets.push({index,time,duration});}
return{total,buckets};
}
function svgElement(tag,attributes){const element=document.createElementNS('http://www.w3.org/2000/svg',tag);for(const [key,value]of Object.entries(attributes))element.setAttribute(key,String(value));return element;}
function drawChart(){
const svg=$('timeline');svg.replaceChildren();chartData=null;
$('chartInfo').textContent='Move over the chart to inspect a bucket.';
const available=!!comparison&&!!state.baseline?.samples&&!!state.candidate?.samples;$('chartSection').classList.toggle('hidden',!available);if(!available)return;
const ticks=comparison.kind==='ticks';
$('chartTitle').textContent=ticks?'Tick durations by sample':'Frame pacing';
$('chartNote').textContent='Each point preserves the longest duration in its bucket. '+(ticks?'Ticks are placed by sample number. Scheduler sleep and pauses are not represented as durations.':'Frames use recorded active time; menus and unfocused intervals are omitted. This is not GPU execution time.');
const a=bucketSamples(state.baseline.samples,ticks),b=bucketSamples(state.candidate.samples,ticks),maxTime=Math.max(a.total,b.total,.001),maxMs=Math.max(...a.buckets.map(p=>p.duration),...b.buckets.map(p=>p.duration),1);
const width=Math.max(320,Math.round(svg.getBoundingClientRect().width));svg.setAttribute('viewBox','0 0 '+width+' 300');
const left=64,right=width-18,top=20,bottom=250,log=$('logScale').checked,transform=x=>log?Math.log1p(x):x;
const x=t=>left+t/maxTime*(right-left),y=ms=>bottom-transform(ms)/transform(maxMs)*(bottom-top);
for(const ms of [0,8.33,16.67,33.33,50,100,250,500,1000,2000,5000,10000,30000,60000]){
if(ms>maxMs)continue;
const line=svgElement('line',{x1:left,x2:right,y1:y(ms),y2:y(ms),stroke:'#e5eae3'});svg.append(line);
const label=svgElement('text',{x:left-8,y:y(ms)+4,'text-anchor':'end',fill:'#65726a','font-size':11});label.textContent=format(ms)+' ms';svg.append(label);
}
const divisions=width<500?3:5;
for(let i=0;i<=divisions;i++){const t=maxTime*i/divisions,label=svgElement('text',{x:x(t),y:bottom+24,'text-anchor':i===0?'start':i===divisions?'end':'middle',fill:'#65726a','font-size':11});label.textContent=ticks?'Tick '+format(Math.round(t)):format(t)+' s';svg.append(label);}
for(const [data,color]of [[a,'#247854'],[b,'#bc642f']])svg.append(svgElement('path',{d:data.buckets.map((point,index)=>(index?'L':'M')+x(point.time).toFixed(2)+' '+y(point.duration).toFixed(2)).join(' '),fill:'none',stroke:color,'stroke-width':1.7,'vector-effect':'non-scaling-stroke'}));
const cursor=svgElement('line',{x1:0,x2:0,y1:top,y2:bottom,stroke:'#192920','stroke-dasharray':'3 3',visibility:'hidden'});svg.append(cursor);chartData={a,b,maxTime,left,right,cursor,ticks,width};
}
$('timeline').addEventListener('pointermove',event=>{
if(!chartData)return;const rect=$('timeline').getBoundingClientRect(),px=(event.clientX-rect.left)/rect.width*chartData.width,t=Math.max(0,Math.min(chartData.maxTime,(px-chartData.left)/(chartData.right-chartData.left)*chartData.maxTime));
chartData.cursor.setAttribute('x1',px);chartData.cursor.setAttribute('x2',px);chartData.cursor.setAttribute('visibility',px>=chartData.left&&px<=chartData.right?'visible':'hidden');
const nearest=data=>{if(t>data.total)return'no samples';let point=data.buckets[0];for(const p of data.buckets){if(Math.abs(p.time-t)<Math.abs(point.time-t))point=p;}return format(point.duration)+' ms';};
$('chartInfo').textContent=(chartData.ticks?'Tick '+format(Math.round(t)):format(t)+' s')+' · baseline '+nearest(chartData.a)+' · candidate '+nearest(chartData.b);
});
$('timeline').addEventListener('pointerleave',()=>{if(chartData)chartData.cursor.setAttribute('visibility','hidden');});
$('logScale').addEventListener('change',drawChart);
window.addEventListener('resize',drawChart);
for(const side of ['baseline','candidate'])$(side+'Files').addEventListener('change',event=>loadFiles(side,event.target.files));
$('export').addEventListener('click',()=>{
if(!comparison)return;const summary={horizon_comparison:1,source_files:{baseline:state.baseline.filename,candidate:state.candidate.filename},...comparison},blob=new Blob([JSON.stringify(summary,null,2)+'\n'],{type:'application/json'}),url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download='horizon-comparison.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
});
</script>
</html>
+9
View File
@@ -0,0 +1,9 @@
# Java comparison dependencies
These locks support `tools/perf_bench.py` (vanilla Fabric and performance-mod comparisons)
and `tools/server_bench.py` (Fabric + Lithium). `tools/runtime.py` downloads and verifies
the pinned Fabric libraries. Game files still come from the user's own Minecraft install.
`mods.lock.json` pins Sodium, Lithium, FerriteCore, ImmediatelyFast and Fabric API with
publisher URLs and hashes. `fabric.lock.json` pins the loader and its libraries.
These are developer benchmark inputs.
+75
View File
@@ -0,0 +1,75 @@
{
"id": "fabric-loader-0.19.5-26.3",
"inheritsFrom": "26.3",
"releaseTime": "2026-10-03T15:06:21+0000",
"time": "2026-10-03T15:06:21+0000",
"type": "release",
"mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient",
"arguments": {
"game": [],
"jvm": [
"-DFabricMcEmu= net.minecraft.client.main.Main "
]
},
"libraries": [
{
"name": "org.ow2.asm:asm:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "9cb72080438acf27f2607002e1444a7b",
"sha1": "ada2141c0cc52ee8f5c48cd5fa4ce0e794f22236",
"sha256": "ed825d10ab1399c8c0cb669e688cf0c8c82629b4c8399b58352b68e92ca10fcb",
"sha512": "8db6efa37d4d569bf2b95d90931b8064f87ed928d20bbf8d8e7fa6182e9a11d32e6a2cc034a3d173a38ee70ce2ea9f20f52f9d8730d9401d2bc6060674c18928",
"size": 126151
},
{
"name": "org.ow2.asm:asm-analysis:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "6dd9011ec87f65e4b2e14e938c4118e4",
"sha1": "8d49f14d51f632cb1d87c88d1ceaf50db0d8af1b",
"sha256": "dede75a21306b65974ecd8f87114ff6970f09fb794157a4ca09ab25c888c2bfc",
"sha512": "0542a90be38f81e39ef43a9253630a2d59f82c17c24492f005c67619561308afbbd23bf8504d3e83b1d4cebe5746126da76037473ddac3071b028c2ae279296b",
"size": 35140
},
{
"name": "org.ow2.asm:asm-commons:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "8eee0b1bdd046baf472eb83dd5e6bb44",
"sha1": "4229e4c55fd8e01c23f9fe9884075cc628aacc50",
"sha256": "6d0abefb7cbf972ea16edb37ec14835372505063a45f976ab7ea889ed9497895",
"sha512": "8540a8f9a63b22bae54fc501f2da405c2c1c45fa13921a1193629cfbfbb716473f8a19984559af7b0b1ea3814d439ec445ea1cfeb159bf922bb7e60a40acf823",
"size": 74840
},
{
"name": "org.ow2.asm:asm-tree:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "62541e1dc62331408ef31317555bf4fa",
"sha1": "e244332a17564c1d1572449399a842de35881be2",
"sha256": "3dfb0d5b6a106cd40b5b250e39935fbf2f927f4477546a5369a3ac609cf0506b",
"sha512": "2ffe5bbfac53bbacc1e4e474628b4247fb1c5f592017f393a327b3f2d2a72a338263f2f6549a42cea57a42f676b967153a10a22aae46affed83608f74daf3768",
"size": 51958
},
{
"name": "org.ow2.asm:asm-util:9.10.1",
"url": "https://maven.fabricmc.net/",
"md5": "d0892ecb209867805e7d2418e5dc6c42",
"sha1": "7bb9d450e8d4cbf9f9e04096c44bbfe7fba80b15",
"sha256": "1bb99d091fba2597dc6d51193e9bbcf0d8447e7ed96bd8f0198b18152f09655c",
"sha512": "7330ded981ddeb01b302cba12d56b419207b6b02ebfaf814cbbc3d2d2d1055e055294ce108ac9e4de9e1d0f3c4e0064f133e87e8085922241c1a2e5fa1fedd2c",
"size": 95628
},
{
"name": "net.fabricmc:sponge-mixin:0.17.4+mixin.0.8.7",
"url": "https://maven.fabricmc.net/",
"md5": "9e33b145b2a46fbc70daf532e3705066",
"sha1": "5f66cc9f59b8efaa942155a3d5a30599bf6640dd",
"sha256": "1f0ae44db7295f8626f33b1dc0ad7f043d8954a8d6847247875fcc5dfcecc934",
"sha512": "837b479c7e831463e074b56314259952f2f82c2ec8ddd71930514ca04f97bb488f43fdb2d4608e7f3fad334604a546053256844ea653542bae8d25bbdab66e21",
"size": 1539080
},
{
"name": "net.fabricmc:fabric-loader:0.19.5",
"url": "https://maven.fabricmc.net/",
"sha256": "93044e4dd46de5d8136701292f05e868da096d2c9fddb4793e4fdbcc63efc695"
}
]
}
+134
View File
@@ -0,0 +1,134 @@
{
"format": 1,
"minecraft": "26.3",
"java_major": 25,
"fabric_loader": "0.19.5",
"projects": {
"sodium": {
"slug": "sodium",
"project_id": "AANobbMI",
"version_id": "bAZQdGpg",
"version": "mc26.3-0.9.2-fabric",
"game_versions": [
"26.3"
],
"loaders": [
"fabric"
],
"license": "LicenseRef-Polyform-Shield-1.0.0",
"source": "https://github.com/CaffeineMC/sodium",
"url": "https://cdn.modrinth.com/data/AANobbMI/versions/bAZQdGpg/sodium-fabric-0.9.2%2Bmc26.3.jar",
"filename": "sodium-fabric-0.9.2+mc26.3.jar",
"size": 1908068,
"hashes": {
"sha1": "9acfe851e36f4fb27d7c5baa224e8bd4e0334283",
"sha512": "f3f260f204b8ce5e8777c2c73f537956755ec61f3817b0b78b5e5568e8aa40f14891f146475075109747665c7c88a45ca0ca9a8df3c68d79c58ecdaa8d8c4b93"
},
"dependencies": [],
"client_side": "required",
"server_side": "unsupported"
},
"lithium": {
"slug": "lithium",
"project_id": "gvQqBUqZ",
"version_id": "xS0Q8LSi",
"version": "mc26.3-0.26.2-fabric",
"game_versions": [
"26.3"
],
"loaders": [
"fabric",
"quilt"
],
"license": "LGPL-3.0-only",
"source": "https://github.com/caffeinemc/lithium-fabric",
"url": "https://cdn.modrinth.com/data/gvQqBUqZ/versions/xS0Q8LSi/lithium-fabric-0.26.2%2Bmc26.3.jar",
"filename": "lithium-fabric-0.26.2+mc26.3.jar",
"size": 914543,
"hashes": {
"sha512": "4d7fee66132eedc71feab9390b92c95d7058edbdad0fecfac1d836a2950b97a7ca463afbede61c7ef361ce65e1f927ab9e89dde5bf2e0e0ce486afb5c5dbee40",
"sha1": "dd5a4ec2c68d7601d8bce9076f789c55a5f8bef3"
},
"dependencies": [],
"client_side": "optional",
"server_side": "optional"
},
"ferrite-core": {
"slug": "ferrite-core",
"project_id": "uXXizFIs",
"version_id": "d5ddUdiB",
"version": "9.0.0-fabric",
"game_versions": [
"26.1",
"26.1.1",
"26.1.2",
"26.2",
"26.3"
],
"loaders": [
"fabric"
],
"license": "MIT",
"source": "https://github.com/malte0811/FerriteCore",
"url": "https://cdn.modrinth.com/data/uXXizFIs/versions/d5ddUdiB/ferritecore-9.0.0-fabric.jar",
"filename": "ferritecore-9.0.0-fabric.jar",
"size": 72677,
"hashes": {
"sha1": "eac76ff0f3753422c61b2c44487d0d195d88d4bc",
"sha512": "d81fa97e11784c19d42f89c2f433831d007603dd7193cee45fa177e4a6a9c52b384b198586e04a0f7f63cd996fed713322578bde9a8db57e1188854ae5cbe584"
},
"dependencies": [],
"client_side": "optional",
"server_side": "optional"
},
"fabric-api": {
"slug": "fabric-api",
"project_id": "P7dR8mSH",
"version_id": "bNnaTiuM",
"version": "0.161.0+26.3",
"game_versions": [
"26.3"
],
"loaders": [
"fabric"
],
"license": "Apache-2.0",
"source": "https://github.com/FabricMC/fabric",
"url": "https://cdn.modrinth.com/data/P7dR8mSH/versions/bNnaTiuM/fabric-api-0.161.0%2B26.3.jar",
"filename": "fabric-api-0.161.0+26.3.jar",
"size": 2620967,
"hashes": {
"sha1": "53f9ee02c3702734d90520aa8c9719bf0e1c8d4f",
"sha512": "ed6b2586d6fde11fde8472f5a527c51e99b67026e46f94d4bfd85e7e28ce5ee299173ee16ad576ceb51f39f98d30a811086a6deb1a86a524859cc16e12da109d"
},
"dependencies": [],
"client_side": "optional",
"server_side": "optional"
},
"immediatelyfast": {
"slug": "immediatelyfast",
"project_id": "5ZwdcRci",
"version_id": "3MP9UR23",
"version": "1.17.1+26.3-fabric",
"game_versions": [
"26.3"
],
"loaders": [
"fabric",
"quilt"
],
"license": "LGPL-3.0-or-later",
"source": "https://github.com/RaphiMC/ImmediatelyFast",
"url": "https://cdn.modrinth.com/data/5ZwdcRci/versions/3MP9UR23/ImmediatelyFast-Fabric-1.17.1%2B26.3.jar",
"filename": "ImmediatelyFast-Fabric-1.17.1+26.3.jar",
"size": 99586,
"hashes": {
"sha512": "8e139589fd995bce3d485a34d92a07243964212f7ed2e4fc2f6de5b9a74d0f59b03252e7ce40c64e006cf3e21bed5de27b830d33ef048b286e041f6178ad8428",
"sha1": "f565bbeb201f2305e81761429d3f1f47e1c3a321"
},
"dependencies": [],
"client_side": "required",
"server_side": "unsupported"
}
}
}
-268
View File
@@ -1,268 +0,0 @@
#!/usr/bin/env python3
"""Compile only original unobfuscated-26.3 mod sources; never bundle game classes."""
import argparse
import json
import os
import platform
from pathlib import Path
import shutil
import subprocess
import zipfile
try:
from . import lab, runtime
except ImportError:
import lab
import runtime
ROOT = lab.ROOT
SOURCE = ROOT / "mods/horizon/src"
BUILD = ROOT / ".local/mod-build"
def test_metrics():
destination = BUILD / "metric-tests"
destination.mkdir(parents=True, exist_ok=True)
sources = [SOURCE / "main/java/dev/horizonlab/metrics" / name
for name in ["SampleStats.java", "Recording.java", "ProcessMemoryMonitor.java", "TickState.java", "ServerContext.java"]]
sources.append(SOURCE / "test/java/dev/horizonlab/metrics/MetricsTest.java")
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.metrics.MetricsTest"], check=True)
subprocess.run(["java", "-XX:+UseCompactObjectHeaders", "-cp", str(destination),
"dev.horizonlab.metrics.MetricsTest"], check=True)
subprocess.run(["java", "-Xms32M", "-Xmx256M", "-XX:+UseZGC", "-XX:+UseCompactObjectHeaders", "-cp", str(destination),
"dev.horizonlab.metrics.MetricsTest"], check=True)
budget_sources = [SOURCE / "main/java/dev/horizonlab/budget/TerrainBudget.java",
SOURCE / "test/java/dev/horizonlab/budget/TerrainBudgetTest.java"]
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, budget_sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.TerrainBudgetTest"], check=True)
worker_sources = [SOURCE / "main/java/dev/horizonlab/budget/WorkerPacer.java",
SOURCE / "test/java/dev/horizonlab/budget/WorkerPacerTest.java"]
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, worker_sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.WorkerPacerTest"], check=True)
debounce_sources = [SOURCE / "main/java/dev/horizonlab/budget/DebounceWait.java",
SOURCE / "test/java/dev/horizonlab/budget/DebounceWaitTest.java"]
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, debounce_sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.DebounceWaitTest"], check=True)
idle_sources = [SOURCE / "main/java/dev/horizonlab/budget/WakeableIdleWait.java",
SOURCE / "test/java/dev/horizonlab/budget/WakeableIdleWaitTest.java"]
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, idle_sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.WakeableIdleWaitTest"], check=True)
dispatch_sources = [SOURCE / "main/java/dev/horizonlab/budget/DispatchRetry.java",
SOURCE / "test/java/dev/horizonlab/budget/DispatchRetryTest.java"]
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, dispatch_sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.DispatchRetryTest"], check=True)
def build():
lock = json.loads((ROOT / "packs/mods.lock.json").read_text())
_, jars, _ = runtime.prepare_client(assets=False)
with zipfile.ZipFile(jars[0]) as game_archive:
game_version = json.loads(game_archive.read("version.json"))
if game_version["world_version"] != lock["options_data_version"]:
raise ValueError("Pack options data version does not match the verified game JAR")
dh = lock["projects"]["distanthorizons"]
jars.append(runtime.fetch(dh["url"], ROOT / ".local/pack-cache" / dh["filename"],
dh["hashes"]["sha512"], "sha512"))
culling = lock["projects"]["entityculling"]
jars.append(runtime.fetch(culling["url"], ROOT / ".local/pack-cache" / culling["filename"],
culling["hashes"]["sha512"], "sha512"))
api = lock["projects"]["fabric-api"]
api_jar = runtime.fetch(api["url"], ROOT / ".local/pack-cache" / api["filename"],
api["hashes"]["sha512"], "sha512")
nested = BUILD / "fabric-api"
nested.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(api_jar) as archive:
for name in archive.namelist():
if name.startswith("META-INF/jars/") and name.endswith(".jar"):
destination = nested / Path(name).name
destination.write_bytes(archive.read(name))
jars.append(destination)
classes = BUILD / "classes"
if classes.exists():
shutil.rmtree(classes)
classes.mkdir(parents=True)
sources = sorted((SOURCE / "main/java").rglob("*.java"))
command = ["--release", "25", "-proc:none", "-encoding", "UTF-8", "-d", str(classes),
"-classpath", os.pathsep.join(map(str, jars)), *map(str, sources)]
argfile = BUILD / "javac.args"
argfile.write_text("\n".join(json.dumps(arg) for arg in command) + "\n")
subprocess.run(["javac", "@" + str(argfile)], cwd=ROOT, check=True)
adapter_tests = BUILD / "adapter-tests"
adapter_tests.mkdir(parents=True, exist_ok=True)
test_classpath = os.pathsep.join(map(str, [classes, *jars]))
subprocess.run(["javac", "--release", "25", "-proc:none", "-classpath", test_classpath,
"-d", str(adapter_tests),
str(SOURCE / "test/java/dev/horizonlab/client/DistantTerrainBudgetTest.java"),
str(SOURCE / "test/java/dev/horizonlab/client/DistantTerrainSettingsTest.java"),
str(SOURCE / "test/java/dev/horizonlab/geometry/RelativeTerrainPositionTest.java"),
str(SOURCE / "test/java/dev/horizonlab/metrics/ResidentMemoryTest.java")], check=True)
subprocess.run(["java", "-cp", os.pathsep.join([str(adapter_tests), test_classpath]),
"dev.horizonlab.client.DistantTerrainBudgetTest"], check=True)
subprocess.run(["java", "-cp", os.pathsep.join([str(adapter_tests), test_classpath]),
"dev.horizonlab.client.DistantTerrainSettingsTest"], check=True)
subprocess.run(["java", "--enable-native-access=ALL-UNNAMED", "-cp", os.pathsep.join([str(adapter_tests), test_classpath]),
"dev.horizonlab.metrics.ResidentMemoryTest"], check=True)
subprocess.run(["java", "-cp", os.pathsep.join([str(adapter_tests), test_classpath]),
"dev.horizonlab.geometry.RelativeTerrainPositionTest"], check=True)
output = ROOT / "dist" / f"horizon-{lock['pack_version']}.jar"
output.parent.mkdir(exist_ok=True)
entries = {path.relative_to(classes).as_posix(): path.read_bytes() for path in classes.rglob("*.class")}
if any(not name.startswith("dev/horizonlab/") for name in entries):
raise ValueError("Only original Horizon classes may be packaged")
resources = SOURCE / "main/resources"
entries.update({path.relative_to(resources).as_posix(): path.read_bytes() for path in resources.rglob("*") if path.is_file()})
entries["LICENSE"] = (ROOT / "LICENSE").read_bytes()
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for name in sorted(entries):
info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
archive.writestr(info, entries[name])
print(f"Built {output} ({output.stat().st_size} bytes, sha256 {lab.digest(output, 'sha256')})")
return output
def build_dispatch_fixture():
return build_integration_fixture("dispatch", "dev.horizonlab.dispatch.DispatchIntegration")
def build_tick_dedup_fixture():
return build_integration_fixture("tick-dedup", "dev.horizonlab.dispatch.TickDedupIntegration")
def build_culling_empty_fixture():
return build_integration_fixture("culling-empty", "dev.horizonlab.dispatch.CullingEmptyIntegration", ["entityculling"])
def build_integration_fixture(name, entrypoint, extra_projects=(), fixture_mixins=(), fixture_dependencies=None):
"""Create a private integration-test mod; never include it in release packs."""
arguments = [json.loads(line) for line in (BUILD / "javac.args").read_text().splitlines()]
classpath = arguments[arguments.index("-classpath") + 1] + os.pathsep + str(BUILD / "classes")
lock = json.loads((ROOT / "packs/mods.lock.json").read_text())
for name_project in extra_projects:
project = lock["projects"][name_project]
jar = runtime.fetch(project["url"], ROOT / ".local/pack-cache" / project["filename"],
project["hashes"]["sha512"], "sha512")
classpath += os.pathsep + str(jar)
classes = BUILD / f"{name}-fixture"
if classes.exists():
shutil.rmtree(classes)
classes.mkdir(parents=True)
fixture_sources = [SOURCE / "test/java" / (entrypoint.replace(".", "/") + ".java")]
fixture_sources.extend(SOURCE / "test/java/dev/horizonlab/dispatch/fixture" / (mixin + ".java") for mixin in fixture_mixins)
subprocess.run(["javac", "--release", "25", "-proc:none", "-classpath", classpath,
"-d", str(classes), *map(str, fixture_sources)], check=True)
output = BUILD / f"{name}-fixture.jar"
metadata = {"schemaVersion": 1, "id": "horizon_" + name.replace("-", "_") + "_fixture",
"version": "1.0.0", "environment": "client", "entrypoints": {"client": [entrypoint]},
"depends": {"horizonlab": "*", **({"distanthorizons": "3.3.4"}
if fixture_dependencies is None else fixture_dependencies)}}
if fixture_mixins:
metadata["mixins"] = [name + "-fixture.mixins.json"]
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
if fixture_mixins:
archive.writestr(metadata["mixins"][0], json.dumps({"required": True, "package": "dev.horizonlab.dispatch.fixture",
"compatibilityLevel": "JAVA_25", "client": list(fixture_mixins), "injectors": {"defaultRequire": 1}}))
for path in sorted(classes.rglob("*.class")):
archive.write(path, path.relative_to(classes).as_posix())
archive.writestr("fabric.mod.json", json.dumps(metadata))
print(f"Private {name} integration fixture: {output}")
return output
def benchmark_workers():
arguments = [json.loads(line) for line in (BUILD / "javac.args").read_text().splitlines()]
classpath = os.pathsep.join([str(BUILD / "classes"), arguments[arguments.index("-classpath") + 1]])
tests = BUILD / "worker-benchmark"
tests.mkdir(parents=True, exist_ok=True)
subprocess.run(["javac", "--release", "25", "-proc:none", "-cp", classpath,
"-d", str(tests), str(SOURCE / "test/java/dev/horizonlab/budget/WorkerPacingBenchmark.java")], check=True)
output = ROOT / "dist/worker-pacing-benchmark.txt"
with output.open("w", encoding="utf-8") as report:
report.write(f"Java {subprocess.check_output(['java', '--version'], text=True).splitlines()[0]}\n")
report.write(f"Platform {platform.system()} {platform.release()} {platform.machine()}; logical CPUs {os.cpu_count()}\n")
report.flush()
for repeat in range(3):
for ratio in ["0.5", "0.05"]:
for mode in ["upstream", "precise"]:
subprocess.run(["java", "-cp", os.pathsep.join([str(tests), classpath]),
"dev.horizonlab.budget.WorkerPacingBenchmark", ratio, "10000", "50000", mode],
stdout=report, check=True)
print(output.read_text(), end="")
def benchmark_debounce():
arguments = [json.loads(line) for line in (BUILD / "javac.args").read_text().splitlines()]
classpath = os.pathsep.join([str(BUILD / "classes"), arguments[arguments.index("-classpath") + 1]])
tests = BUILD / "debounce-benchmark"
tests.mkdir(parents=True, exist_ok=True)
subprocess.run(["javac", "--release", "25", "-proc:none", "-cp", classpath,
"-d", str(tests), str(SOURCE / "test/java/dev/horizonlab/budget/DebounceQueueBenchmark.java")], check=True)
output = ROOT / "dist/debounce-queue-benchmark.txt"
with output.open("w", encoding="utf-8") as report:
report.write(f"Java {subprocess.check_output(['java', '--version'], text=True).splitlines()[0]}\n")
report.write(f"Platform {platform.system()} {platform.release()} {platform.machine()}; logical CPUs {os.cpu_count()}\n")
report.flush()
subprocess.run(["java", "-cp", os.pathsep.join([str(tests), classpath]),
"dev.horizonlab.budget.DebounceQueueBenchmark"], stdout=report, check=True)
print(output.read_text(), end="")
def benchmark_headers():
arguments = [json.loads(line) for line in (BUILD / "javac.args").read_text().splitlines()]
classpath = arguments[arguments.index("-classpath") + 1]
tests = BUILD / "header-benchmark"
tests.mkdir(parents=True, exist_ok=True)
subprocess.run(["javac", "--release", "25", "-proc:none", "-cp", classpath,
"-d", str(tests), str(SOURCE / "test/java/dev/horizonlab/metrics/ObjectHeaderBenchmark.java")], check=True)
output = ROOT / "dist/object-header-benchmark.txt"
with output.open("w", encoding="utf-8") as report:
report.write(f"Java {subprocess.check_output(['java', '--version'], text=True).splitlines()[0]}\n")
report.write(f"Platform {platform.system()} {platform.release()} {platform.machine()}; logical CPUs {os.cpu_count()}\n")
report.flush()
for repeat in range(3):
for enabled in [False, True]:
report.write(f"fork={repeat} requested_compact_headers={enabled}\n")
report.flush()
subprocess.run(["java", "-Xms128M", "-Xmx512M",
"-XX:" + ("+" if enabled else "-") + "UseCompactObjectHeaders",
"-cp", os.pathsep.join([str(tests), classpath]),
"dev.horizonlab.metrics.ObjectHeaderBenchmark", str(enabled).lower()],
stdout=report, check=True)
print(output.read_text(), end="")
def benchmark_idle():
arguments = [json.loads(line) for line in (BUILD / "javac.args").read_text().splitlines()]
classpath = os.pathsep.join([str(BUILD / "classes"), arguments[arguments.index("-classpath") + 1]])
tests = BUILD / "idle-benchmark"
tests.mkdir(parents=True, exist_ok=True)
subprocess.run(["javac", "--release", "25", "-proc:none", "-cp", classpath,
"-d", str(tests), str(SOURCE / "test/java/dev/horizonlab/budget/IdleQueueBenchmark.java")], check=True)
output = ROOT / "dist/idle-queue-benchmark.txt"
with output.open("w", encoding="utf-8") as report:
report.write(f"Java {subprocess.check_output(['java', '--version'], text=True).splitlines()[0]}\n")
report.write(f"Platform {platform.system()} {platform.release()} {platform.machine()}; logical CPUs {os.cpu_count()}\n")
report.flush()
subprocess.run(["java", "-cp", os.pathsep.join([str(tests), classpath]),
"dev.horizonlab.budget.IdleQueueBenchmark"], stdout=report, check=True)
print(output.read_text(), end="")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--test-only", action="store_true")
parser.add_argument("--benchmark-workers", action="store_true", help="Measure tiny-job executor pacing; not Minecraft FPS")
parser.add_argument("--benchmark-headers", action="store_true", help="Measure object allocation with compact headers off/on; not game RAM")
args = parser.parse_args()
if args.test_only and (args.benchmark_workers or args.benchmark_headers):
parser.error("Benchmarks require the compiled mod; omit --test-only")
test_metrics()
if not args.test_only:
build()
if args.benchmark_workers:
benchmark_workers()
if args.benchmark_headers:
benchmark_headers()
-188
View File
@@ -1,188 +0,0 @@
#!/usr/bin/env python3
"""Build portable pinned Modrinth packs; game code/assets remain launcher downloads."""
import argparse
import json
from pathlib import Path
import shutil
import zipfile
try:
from . import lab, runtime
except ImportError:
import lab
import runtime
ROOT = lab.ROOT
CORE = ["fabric-api", "sodium", "lithium", "ferrite-core", "immediatelyfast", "entityculling"]
PROFILES = {
"baseline": {"title": "Vanilla baseline", "mods": ["fabric-api"], "render": 12, "lod": 0, "heap": 6144},
"core-performance": {"title": "Full-detail performance comparison", "mods": CORE, "render": 12, "lod": 0, "heap": 6144},
"m2-balanced": {"title": "M2 Pro balanced", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144},
"adaptive": {"title": "Adaptive terrain experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True},
"worker-pacing": {"title": "Precise worker pacing experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "pacing": True},
"adaptive-pacing": {"title": "Adaptive precise pacing experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True, "pacing": True},
"queue-wait": {"title": "Debounce queue wait experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "queue_wait": True},
"adaptive-queue": {"title": "Adaptive pacing and queue wait experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True, "pacing": True, "queue_wait": True},
"dispatch-retry": {"title": "Rejected dispatch retry experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "dispatch_retry": True},
"tick-dedup": {"title": "Terrain tick membership experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "tick_dedup": True},
"culling-empty": {"title": "Empty culling whitelist experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "culling_empty": True},
"quad-reuse": {"title": "Terrain quad reuse experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "quad_reuse": True},
"terrain-position": {"title": "Relative terrain position experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "terrain_position": True},
"culling-rays": {"title": "Culling ray scratch experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "culling_rays": True},
"foreground-first": {"title": "Foreground-first combined experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True, "pacing": True, "queue_wait": True, "dispatch_retry": True, "tick_dedup": True, "target_fps": 120},
"foreground-vulkan": {"title": "Foreground-first Vulkan experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True, "pacing": True, "queue_wait": True, "dispatch_retry": True, "tick_dedup": True, "target_fps": 120, "backend": "vulkan"},
"low-memory": {"title": "Low memory", "mods": CORE, "render": 8, "lod": 0, "heap": 3072},
"far-distance": {"title": "Far distance", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 256, "heap": 8192},
"vulkan": {"title": "Vulkan experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "backend": "vulkan"},
}
def read_lock():
return json.loads((ROOT / "packs/mods.lock.json").read_text())
def validate_selection(lock, selection):
projects = lock["projects"]
selected_ids = {projects[name]["project_id"] for name in selection}
selected_versions = {projects[name]["version_id"] for name in selection}
for name in selection:
entry = projects[name]
if lock["minecraft"] not in entry["game_versions"]:
raise ValueError(f"Wrong game version: {name}")
if "fabric" not in entry["loaders"]:
raise ValueError(f"Wrong loader: {name}")
if Path(entry["filename"]).name != entry["filename"] or "\\" in entry["filename"]:
raise ValueError(f"Unsafe filename: {name}")
if not entry["url"].startswith("https://cdn.modrinth.com/"):
raise ValueError(f"Unexpected download host: {name}")
for dependency in entry["dependencies"]:
if dependency["dependency_type"] != "required":
continue
if dependency.get("version_id"):
if dependency["version_id"] not in selected_versions:
raise ValueError(f"Missing pinned dependency for {name}: {dependency}")
elif dependency.get("project_id") not in selected_ids:
raise ValueError(f"Missing dependency for {name}: {dependency}")
def mod_path(entry):
return "mods/" + entry["filename"]
def options(profile):
# Simulation distance stays at the vanilla default in every profile.
values = {"version": read_lock()["options_data_version"], "graphicsPreset": json.dumps("custom"),
"renderDistance": profile["render"], "simulationDistance": 12, "enableVsync": "false",
"maxFps": 260, "guiScale": 2, "onboardAccessibility": "false",
"preferredGraphicsBackend": json.dumps(profile.get("backend", "opengl"))}
return "".join(f"{key}:{value}\n" for key, value in values.items())
def overrides(profile_name, mod_bytes):
profile = PROFILES[profile_name]
files = {f"mods/horizon-{read_lock()['pack_version']}.jar": mod_bytes,
"config/horizon-profile.txt": (profile_name + "\n").encode(),
"options.txt": options(profile).encode()}
experiment = any(profile.get(key, False) for key in ["adaptive", "pacing", "queue_wait", "dispatch_retry", "tick_dedup", "culling_empty", "culling_rays", "terrain_position", "quad_reuse"])
config = ROOT / "packs/config" / f"{'m2-balanced' if experiment else profile_name}.toml"
files["config/horizon-adaptive.properties"] = (
f"enabled={str(profile.get('adaptive', False)).lower()}\ntargetFps={profile.get('target_fps', 60)}\n").encode()
files["config/horizon-worker-pacing.properties"] = (
f"enabled={str(profile.get('pacing', False)).lower()}\n").encode()
files["config/horizon-queue-wait.properties"] = (
f"enabled={str(profile.get('queue_wait', False)).lower()}\n").encode()
files["config/horizon-dispatch-retry.properties"] = (
f"enabled={str(profile.get('dispatch_retry', False)).lower()}\n").encode()
files["config/horizon-tick-dedup.properties"] = (
f"enabled={str(profile.get('tick_dedup', False)).lower()}\n").encode()
files["config/horizon-culling-empty.properties"] = (
f"enabled={str(profile.get('culling_empty', False)).lower()}\n").encode()
files["config/horizon-culling-rays.properties"] = (
f"enabled={str(profile.get('culling_rays', False)).lower()}\n").encode()
files["config/horizon-quad-reuse.properties"] = (
f"enabled={str(profile.get('quad_reuse', False)).lower()}\n").encode()
files["config/horizon-terrain-position.properties"] = (
f"enabled={str(profile.get('terrain_position', False)).lower()}\n").encode()
files["config/horizon-terrain-read-wait.properties"] = (
f"enabled={str(bool(profile['lod'])).lower()}\n").encode()
if profile["lod"]:
if not config.exists():
raise FileNotFoundError(f"Missing verified DH profile config: {config}")
files["config/DistantHorizons.toml"] = config.read_bytes()
return files
def write_zip(path, entries):
path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for name in sorted(entries):
info = zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
mode = 0o100755 if name.endswith(".command") else 0o100644
info.external_attr = mode << 16
archive.writestr(info, entries[name])
def build(profile_name, mod_jar):
lock = read_lock()
profile = PROFILES[profile_name]
validate_selection(lock, profile["mods"])
files = []
for name in profile["mods"]:
entry = lock["projects"][name]
files.append({"path": mod_path(entry), "hashes": entry["hashes"], "downloads": [entry["url"]],
"fileSize": entry["size"], "env": {"client": "required", "server": "unsupported"}})
index = {"formatVersion": 1, "game": "minecraft", "versionId": lock["pack_version"],
"name": "Horizon — " + profile["title"],
"summary": "Vanilla mechanics, pinned performance mods, measured frame and tick timings.",
"files": files, "dependencies": {"minecraft": lock["minecraft"], "fabric-loader": lock["fabric_loader"]}}
entries = {"modrinth.index.json": json.dumps(index, indent=2).encode()}
entries.update({"overrides/" + name: data for name, data in overrides(profile_name, mod_jar.read_bytes()).items()})
output = ROOT / "dist" / f"horizon-{profile_name}-{lock['pack_version']}.mrpack"
write_zip(output, entries)
print(f"Built {output.name}: {len(files)} pinned downloads")
return output
def prepare_instance(profile_name, destination, mod_jar):
lock = read_lock()
profile = PROFILES[profile_name]
validate_selection(lock, profile["mods"])
destination.mkdir(parents=True, exist_ok=True)
for name in profile["mods"]:
entry = lock["projects"][name]
source = runtime.fetch(entry["url"], ROOT / ".local/pack-cache" / entry["filename"],
entry["hashes"]["sha512"], "sha512")
target = destination / mod_path(entry)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
runtime.install_original_mod(mod_jar, destination / "mods", f"horizon-{lock['pack_version']}.jar")
for name, data in overrides(profile_name, mod_jar.read_bytes()).items():
if name.startswith("mods/"):
continue
target = destination / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
print(f"Prepared {profile_name} instance: {destination}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--profile", choices=PROFILES)
parser.add_argument("--instance", type=Path, help="Local demo smoke-test directory (no normal account launch)")
parser.add_argument("--mod", type=Path, default=ROOT / "dist" / f"horizon-{read_lock()['pack_version']}.jar")
args = parser.parse_args()
if not args.mod.exists():
parser.error("Build the original mod first: python3 tools/build_mod.py")
if args.instance:
if not args.profile:
parser.error("--instance requires --profile")
prepare_instance(args.profile, args.instance.resolve(), args.mod)
else:
for profile in [args.profile] if args.profile else PROFILES:
build(profile, args.mod)
if __name__ == "__main__":
main()
-42
View File
@@ -1,42 +0,0 @@
#!/usr/bin/env python3
"""Create the downloadable client starter and hashes from original project artifacts. (The Java/Fabric server
starter is gone: horizon-server replaces it, docs/hosting.md.)"""
import hashlib
from pathlib import Path
try:
from . import build_pack
except ImportError:
import build_pack
ROOT = build_pack.ROOT
def main():
lock = build_pack.read_lock()
version = lock["pack_version"]
mod = ROOT / "dist" / f"horizon-{version}.jar"
if not mod.exists():
raise FileNotFoundError("Run tools/build_mod.py first")
packs = [build_pack.build(profile, mod) for profile in build_pack.PROFILES]
client = {pack.name: pack.read_bytes() for pack in packs}
client["START-HERE.txt"] = (ROOT / "packs/START-HERE.txt").read_text().replace("@PACK_VERSION@", version).encode()
client["Mac-Start.command"] = (ROOT / "packs/Mac-Start.command").read_text().replace("@PACK_VERSION@", version).encode()
client["LICENSE"] = (ROOT / "LICENSE").read_bytes()
viewer = (ROOT / "tools/Compare-Benchmarks.html").read_bytes()
client["Compare-Benchmarks.html"] = viewer
(ROOT / "dist/Compare-Benchmarks.html").write_bytes(viewer)
build_pack.write_zip(ROOT / "dist" / f"horizon-mac-starter-{version}.zip", client)
artifacts = sorted(path for path in (ROOT / "dist").glob("*") if version in path.name)
artifacts.append(ROOT / "dist/Compare-Benchmarks.html")
checksums = []
for path in artifacts:
if path.suffix in [".jar", ".mrpack", ".zip", ".html"]:
checksums.append(hashlib.sha256(path.read_bytes()).hexdigest() + " " + path.name)
(ROOT / "dist/SHA256SUMS.txt").write_text("\n".join(checksums) + "\n")
print("Built the client starter and SHA256SUMS.txt")
if __name__ == "__main__":
main()
+8
View File
@@ -219,6 +219,14 @@ def world_blocks():
cmd('/clone 0 205 0 4 207 4 6 205 6 masked'),
cmd('/execute if blocks 0 205 0 4 207 4 6 205 6 all'),
cmd('/setblock 3 206 3 minecraft:air'),
# A hopper placed into power turns `enabled=false` and keeps its block entity.
cmd('/setblock 5 205 5 minecraft:redstone_block'),
cmd('/setblock 5 206 5 minecraft:hopper'),
cmd('/execute if block 5 206 5 minecraft:hopper[enabled=false]'),
cmd('/item replace block 5 206 5 container.0 with minecraft:diamond 3'),
cmd('/data get block 5 206 5 Items[0].count'),
cmd('/fill 5 205 4 5 205 4 minecraft:hopper'),
cmd('/data get block 5 205 4 Items'),
cmd('/fill 0 200 0 15 228 15 air'),
cmd('/execute if block 0 300 0 air'),
cmd('/setblock 0 400 0 stone'),
-193
View File
@@ -1,193 +0,0 @@
#!/usr/bin/env python3
"""Compare two real Horizon JSON reports and flag mismatched workloads."""
import argparse
import json
import math
from pathlib import Path
MATCH_FIELDS = ("minecraft", "kind", "os", "os_version", "architecture", "gpu", "graphics_backend", "graphics_driver",
"server_runtime_kind", "client_graphics_capture_status", "java_version", "heap_max_bytes", "framebuffer_width", "framebuffer_height", "render_distance",
"simulation_distance", "vsync", "fps_limit", "graphics_preset", "ambient_occlusion",
"improved_transparency", "mipmap_levels", "entity_distance_scaling", "entity_shadows", "particles",
"clouds", "cloud_range", "fov", "world_difficulty", "dh_capture_status", "dh_rendering_enabled", "dh_renderer_mode",
"dh_lod_radius_chunks", "dh_horizontal_quality", "dh_vertical_quality", "dh_max_horizontal_resolution",
"dh_transparency", "dh_lod_shading", "dh_lod_only_mode", "dh_camera_quality_dropoff",
"dh_ambient_occlusion")
TICK_STATE_FIELDS = ("configured_tick_rate", "frozen", "stepping", "sprinting", "runs_game_elements")
def tick_state_available(report):
def number(value):
if not isinstance(value, (int, float)) or isinstance(value, bool):
return False
try:
return math.isfinite(value)
except OverflowError:
return False
if report.get("tick_state_capture_status") != "sampled_server_ticks":
return False
count = report.get("tick_state_samples")
if not number(count) or count <= 0 or count > 9_007_199_254_740_991 or count != int(count):
return False
for boundary in ["tick_state_first", "tick_state_last"]:
state = report.get(boundary)
if not isinstance(state, dict) or not number(state.get("configured_tick_rate")) or state["configured_tick_rate"] < 1:
return False
if any(not isinstance(state.get(field), bool) for field in TICK_STATE_FIELDS[1:]):
return False
changed = report.get("tick_state_changed")
if not isinstance(changed, list) or any(field not in TICK_STATE_FIELDS for field in changed):
return False
return all(number(report.get("tick_state_" + field + "_samples"))
and 0 <= report["tick_state_" + field + "_samples"] <= count
and report["tick_state_" + field + "_samples"] == int(report["tick_state_" + field + "_samples"])
for field in ["frozen", "stepping", "sprinting", "suppressed", "nonstandard_rate"])
def compare_tick_states(baseline, candidate):
mismatches, warnings = [], []
available = [tick_state_available(report) for report in [baseline, candidate]]
for name, report, captured in zip(["baseline", "candidate"], [baseline, candidate], available):
if not captured:
warnings.append(f"{name} tick-manager state was not captured or is invalid; simulation workload equivalence is unknown.")
continue
if report["tick_state_changed"]:
mismatches.append(f"{name} tick-manager state changed during recording")
warnings.append(f"{name} sampled tick-manager changes: " + ", ".join(report["tick_state_changed"]) + ".")
abnormal = [field for field in ["frozen", "stepping", "sprinting", "suppressed", "nonstandard_rate"]
if report["tick_state_" + field + "_samples"] > 0]
if abnormal:
warnings.append(f"{name} includes tick-manager samples with " + ", ".join(abnormal) + "; interpret execution times as this workload.")
if all(available):
for boundary in ["tick_state_first", "tick_state_last"]:
for field in TICK_STATE_FIELDS:
if baseline[boundary][field] != candidate[boundary][field]:
mismatches.append(f"{boundary}.{field}: {baseline[boundary][field]!r} vs {candidate[boundary][field]!r}")
warnings.append("Tick-manager state is sampled after measured server invocations. Changes entirely between samples, paused intervals and completed world work are not verified.")
return mismatches, warnings
def software_warnings(baseline, candidate):
warnings = []
for field in ["java_vendor", "java_vm_name", "java_runtime_version"]:
if not all(isinstance(report.get(field), str) and report[field] for report in [baseline, candidate]):
warnings.append(f"{field} was not captured in both reports; Java implementation equivalence is unknown.")
elif baseline[field] != candidate[field]:
warnings.append(f"Software {field} differs: {baseline[field]!r} vs {candidate[field]!r}. Treat it as an explicit experiment variable.")
mods = []
for report in [baseline, candidate]:
entries = report.get("mods")
mods.append(set(entries) if isinstance(entries, list) and all(isinstance(entry, str) and entry for entry in entries) else None)
if any(entries is None for entries in mods):
warnings.append("Loaded mod versions were not captured in both reports; software equivalence is unknown.")
elif mods[0] != mods[1]:
warnings.append("Loaded mod versions differ. Treat added, removed or upgraded mods as explicit experiment variables.")
for label, entries in [("baseline", mods[0] - mods[1]), ("candidate", mods[1] - mods[0])]:
ordered = sorted(entries)
if ordered:
suffix = f"; {len(ordered) - 12} more" if len(ordered) > 12 else ""
warnings.append(f"Only {label}: " + ", ".join(ordered[:12]) + suffix + ".")
return warnings
def server_context_warnings(baseline, candidate):
warnings = []
for name, report in [("baseline", baseline), ("candidate", candidate)]:
kind = report.get("server_runtime_kind")
if kind not in ["integrated", "dedicated"]:
warnings.append(f"{name} server runtime kind was not captured; integrated/dedicated equivalence is unknown.")
if kind == "integrated":
captured = report.get("client_graphics_capture_status") == "captured_at_recording_start" and all(
isinstance(report.get(key), str) and report[key].strip() for key in ["gpu", "graphics_backend", "graphics_driver"])
if not captured:
warnings.append(f"{name} integrated-server client graphics were not captured; shared rendering workload is unknown.")
warnings.append("Integrated-server graphics context is a recording-start snapshot; later graphics changes and full client workload equivalence are not verified.")
return warnings
def compare(baseline, candidate):
for report in [baseline, candidate]:
if report.get("schema") != 1 or report.get("kind") not in ["frames", "ticks"]:
raise ValueError("Expected a schema-1 Horizon frame/tick report")
if report.get("stats", {}).get("count", 0) < 1:
raise ValueError("Report contains no samples")
if baseline["kind"] != candidate["kind"]:
raise ValueError("Compare frames with frames, or ticks with ticks")
mismatches = [f"{key}: {baseline.get(key)!r} vs {candidate.get(key)!r}" for key in MATCH_FIELDS
if baseline.get(key) != candidate.get(key)]
warnings = ["World, route, warm-up and LOD cache must also match; these are not verified by this tool."]
warnings.extend(software_warnings(baseline, candidate))
if baseline["kind"] == "ticks":
warnings.extend(server_context_warnings(baseline, candidate))
tick_mismatches, tick_warnings = compare_tick_states(baseline, candidate)
mismatches.extend(tick_mismatches)
warnings.extend(tick_warnings)
warnings.append("Tick durations exclude scheduler sleep. Observed TPS counts measured invocations, including frozen ticks, and includes recording time spent paused; tick execution capacity is not TPS.")
if baseline["kind"] == "frames":
for field in ["adaptive_budget_enabled", "adaptive_target_fps", "precise_worker_pacing", "debounce_queue_wait",
"wakeable_idle_wait", "dispatch_retry_backoff", "tick_membership_dedup", "empty_culling_whitelist", "culling_ray_scratch", "terrain_position_arithmetic", "terrain_quad_reuse", "interruptible_terrain_read", "dh_thread_count", "dh_runtime_ratio"]:
if field in baseline and field in candidate and baseline[field] != candidate[field]:
warnings.append(f"Experiment {field} differs: {baseline[field]!r} vs {candidate[field]!r}.")
for name, report in [("baseline", baseline), ("candidate", candidate)]:
if report.get("dh_capture_status") not in ["available", "not_installed"]:
warnings.append(f"{name} distant-terrain configuration was not captured; quality equivalence is unknown.")
if report.get("visual_settings_changed"):
mismatches.append(f"{name} visual settings changed during recording")
warnings.append(f"{name} visual settings changed between capture boundaries: {report['visual_settings_changed']!r}.")
for field in ["compact_object_headers", "garbage_collectors"]:
if field not in baseline or field not in candidate:
warnings.append(f"{field} was not captured in both reports; JVM configuration equivalence is unknown.")
elif baseline[field] != candidate[field]:
warnings.append(f"JVM {field} differs: {baseline[field]!r} vs {candidate[field]!r}. Treat this as an explicit experiment variable.")
if abs(baseline.get("elapsed_seconds", 0) - candidate.get("elapsed_seconds", 0)) > max(
2, min(baseline.get("elapsed_seconds", 0), candidate.get("elapsed_seconds", 0)) * 0.1):
warnings.append("Recording durations differ; match durations when comparing memory peaks and collection totals.")
for name, report in [("baseline", baseline), ("candidate", candidate)]:
if report.get("dropped_samples", 0):
warnings.append(f"{name} exceeded the recording buffer: {report['dropped_samples']} dropped samples.")
if report["kind"] == "frames" and report.get("excluded_frames", 0):
warnings.append(f"{name} excluded {report['excluded_frames']} menu, paused or unfocused frame starts. Process CPU still spans the whole recording.")
if report.get("elapsed_seconds", 0) < 60:
warnings.append(f"{name} is shorter than 60 seconds; use longer repeated runs for decisions.")
if baseline["kind"] == "ticks" and baseline.get("peak_players") != candidate.get("peak_players"):
mismatches.append("Peak player count differs")
rows = []
keys = ["meanRate", "lowOnePercentRate", "p95Ms", "p99Ms", "maxMs"] if baseline["kind"] == "frames" else ["meanMs", "p95Ms", "p99Ms", "maxMs"]
for key in keys:
before, after = baseline["stats"][key], candidate["stats"][key]
rows.append({"metric": key, "baseline": before, "candidate": after,
"change_percent": 100 * (after / before - 1) if before else None})
for key in ["heap_used_end_bytes", "heap_used_peak_sampled_bytes", "nonheap_used_peak_sampled_bytes",
"process_rss_last_sampled_bytes", "process_rss_peak_sampled_bytes", "process_cpu_mean_cores", "gc_time_ms", "observed_ticks_per_second"]:
if key in baseline and key in candidate:
before, after = baseline[key], candidate[key]
rows.append({"metric": key, "baseline": before, "candidate": after,
"change_percent": 100 * (after / before - 1) if before else None})
return {"kind": baseline["kind"], "mismatches": mismatches, "warnings": warnings, "metrics": rows}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("baseline", type=Path)
parser.add_argument("candidate", type=Path)
parser.add_argument("--json", action="store_true")
parser.add_argument("--strict", action="store_true", help="Exit nonzero on unmatched captured settings")
args = parser.parse_args()
result = compare(json.loads(args.baseline.read_text()), json.loads(args.candidate.read_text()))
if args.json:
print(json.dumps(result, indent=2))
else:
for row in result["metrics"]:
change = "n/a" if row["change_percent"] is None else f"{row['change_percent']:+.1f}%"
print(f"{row['metric']:25} {row['baseline']:12.3f} -> {row['candidate']:12.3f} ({change})")
for mismatch in result["mismatches"]:
print("UNMATCHED: " + mismatch)
for warning in result["warnings"]:
print("NOTE: " + warning)
return int(args.strict and bool(result["mismatches"]))
if __name__ == "__main__":
raise SystemExit(main())
+4 -1
View File
@@ -680,7 +680,10 @@ def clear_large_outputs(name, trace):
top = path.relative_to(local).parts[0]
except (ValueError, IndexError):
continue
if top not in OWN_DIRECTORIES:
# Only the harness's own directory: another harness running beside it may be writing
# large files in a directory this one merely read (decorated_region compiles its oracle
# into chunk-generation-parity while chunk_generation writes its dumps there).
if top not in OWN_DIRECTORIES and top.startswith(name.replace("_", "-")):
directories.add(local / top)
for directory in directories:
for file in (directory.rglob("*") if directory.is_dir() else []):
+4 -4
View File
@@ -24,7 +24,7 @@ Games:
mod (mods/horizon/src/bench), built here; nothing of the game
is redistributed
vanilla-mods the same + Sodium, Lithium, FerriteCore and ImmediatelyFast
(pinned in packs/mods.lock.json)
(pinned in tools/benchmark-deps/mods.lock.json)
neoforge Minecraft 1.21.1 on NeoForge (dev-only, tools/neoforge_oracle.py
installs it under .local/neoforge-oracle) + a driver mod
(mods/horizon/src/neoforge-bench) + the jars of --mod-jars and
@@ -524,9 +524,9 @@ def build_bench_mod(jars):
def perf_mod_jars():
"""Sodium, Lithium, FerriteCore and ImmediatelyFast for 26.3 (downloaded from
Modrinth, checked against packs/mods.lock.json, never committed), plus
Modrinth, checked against tools/benchmark-deps/mods.lock.json, never committed), plus
Fabric API when one of them needs it."""
lock = json.loads((ROOT / "packs/mods.lock.json").read_text())
lock = json.loads((ROOT / "tools/benchmark-deps/mods.lock.json").read_text())
jars, needs_api = [], False
for name in PERF_MODS:
project = lock["projects"][name]
@@ -866,7 +866,7 @@ def app(args):
jars = [j.name for f in filter(None, (args.mod_jars, args.deps)) for j in sorted(Path(f).glob("*.jar"))]
return {"name": "minecraft", "version": "1.21.1",
"mods": [{"name": "neoforge", "version": neoforge_oracle.NEOFORGE}] + [{"name": j} for j in jars]}
lock = json.loads((ROOT / "packs/mods.lock.json").read_text())
lock = json.loads((ROOT / "tools/benchmark-deps/mods.lock.json").read_text())
mods = [{"name": "fabric-loader", "version": lock["fabric_loader"]}]
if args.game == "vanilla-mods":
mods += [{"name": n, "version": lock["projects"][n]["version"]} for n in PERF_MODS]
+16 -8
View File
@@ -74,12 +74,17 @@ LAUNCHER_PATHS = [
]
LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"]
FOOTER = {
"game": "Install or update it from the Horizon launcher: it installs new versions by itself. "
"New here? Get the launcher at https://playhorizon.dev. You need your own copy of Minecraft: Java Edition.",
"launcher": "Your launcher updates itself. New here? Download the archive for your system below, extract it, "
"and run `horizon-launcher`. Website: https://playhorizon.dev",
}
# A game release is GitHub's latest (servers and install.sh follow it), so it is the first release people land on:
# its notes open with the way to the launcher (#1647). Raw HTML on one line, which GitHub shows and every launcher's
# notes view and one-line summary skip (pulldown-cmark's HTML events), so launchers never tell players to get
# themselves. The site's Releases page leaves it out too.
PLAYERS = ('<h3>Want to play? Download the <a href="https://playhorizon.dev">Horizon launcher</a>, not the files '
'below</h3><p>It installs this version and keeps it up to date. It is also on GitHub: <a href="'
f'https://github.com/{REPO}/releases?q=launcher&amp;expanded=true">the launcher releases</a>. You need your '
"own copy of Minecraft: Java Edition. The files below are what the launcher installs, and the dedicated "
"server for people who host one.</p>")
LAUNCHER_FOOTER = ("Your launcher updates itself. New here? Download the archive for your system below, extract it, "
"and run `horizon-launcher`. Website: https://playhorizon.dev")
DISCLAIMER = "Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft."
# An open issue with this label holds every game release (docs/release-flow.md). Only people who can triage the
# repository can add it, and the issue's text is never read: its author could edit it afterwards.
@@ -374,7 +379,9 @@ def notes(kind, version, prs, issues, previous=None):
else:
title = f"Horizon launcher {version.removeprefix(OLD_LAUNCHER_PREFIX).removeprefix(LAUNCHER_PREFIX)}"
intro = line_intro(kind, version, previous)
parts = [intro] if intro else []
parts = [PLAYERS] if kind == "game" else []
if intro:
parts.append(intro)
if not shown:
parts.append("Rebuilt from the latest main.")
if new:
@@ -386,7 +393,8 @@ def notes(kind, version, prs, issues, previous=None):
contributors = sorted({pr["author"] for pr in shown if pr["author"] and pr["author"] != REPO.split("/")[0]})
if contributors:
parts.append("Thanks to " + ", ".join(f"@{name}" for name in contributors) + ".")
parts.append(FOOTER[kind])
if kind == "launcher":
parts.append(LAUNCHER_FOOTER)
parts.append(DISCLAIMER)
return title, "\n\n".join(parts) + "\n"
+4 -98
View File
@@ -1,19 +1,9 @@
#!/usr/bin/env python3
"""Prepare an isolated game runtime from your own launcher install; local smoke tests use demo mode."""
"""Shared Java dependency and platform helpers for Rust comparison benchmarks."""
from concurrent.futures import ThreadPoolExecutor
import argparse
import json
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
import time
import urllib.error
import zipfile
try:
from . import lab
@@ -21,40 +11,11 @@ except ImportError:
import lab
ROOT = lab.ROOT
CACHE = ROOT / ".local" / "runtime"
library_allowed = lab.library_allowed
native_library_matches = lab.native_library_matches
def install_original_mod(source, mod_dir, filename=None):
"""Replace our own previous versions, retaining backups outside Fabric's mod scan."""
mod_dir.mkdir(parents=True, exist_ok=True)
filename = filename or source.name
# Retire both current and pre-rebrand filenames to avoid duplicate mod IDs.
candidates = sorted({*mod_dir.glob("horizon-*.jar"), *mod_dir.glob("horizon-lab-*.jar")})
for old in candidates:
if old.name == filename:
continue
with zipfile.ZipFile(old) as archive:
if json.loads(archive.read("fabric.mod.json"))["id"] != "horizonlab":
raise ValueError(f"Refusing to replace another mod: {old}")
backup = mod_dir.parent / ".horizon-mod-backups"
backup.mkdir(exist_ok=True)
destination = backup / f"{old.stem}-{lab.digest(old, 'sha256')[:12]}.jar"
shutil.move(str(old), str(destination))
if source.resolve() != (mod_dir / filename).resolve():
shutil.copyfile(source, mod_dir / filename)
CACHE = ROOT / ".local" / "runtime"
def jvm_options(heap, compact_headers=False, collector="default"):
options = ["-Xms512M", f"-Xmx{heap}"]
if compact_headers:
options.append("-XX:+UseCompactObjectHeaders")
if collector != "default":
options.append({"g1": "-XX:+UseG1GC", "zgc": "-XX:+UseZGC"}[collector])
return options
def fetch(url, path, checksum, algorithm="sha1"):
for attempt in range(3):
try:
@@ -66,7 +27,7 @@ def fetch(url, path, checksum, algorithm="sha1"):
def fabric_libraries():
profile = json.loads((ROOT / "packs/fabric.lock.json").read_text())
profile = json.loads((ROOT / "tools/benchmark-deps/fabric.lock.json").read_text())
jars = []
for library in profile["libraries"]:
group, artifact, version = library["name"].split(":")
@@ -76,6 +37,7 @@ def fabric_libraries():
return jars
def conditional_client_jvm_options(manifest, system=None, architecture=None):
"""Use official OS/architecture flags alongside our managed JVM/classpath options."""
options = []
@@ -88,59 +50,3 @@ def conditional_client_jvm_options(manifest, system=None, architecture=None):
raise ValueError("Unsupported conditional client JVM argument")
options.extend(values)
return options
def prepare_client(assets=True):
"""Classpath and natives from the user's own launcher install; nothing of the game is downloaded."""
lock, directory = lab.config()
manifest, client = lab.import_client(lock, directory)
jars = [client]
natives = CACHE / "natives"
natives.mkdir(parents=True, exist_ok=True)
for artifact in lab.client_library_artifacts(manifest):
jar = lab.import_library(artifact, directory / "libraries/client")
jars.append(jar)
with zipfile.ZipFile(jar) as archive:
for name in archive.namelist():
if name.endswith((".so", ".dll", ".dylib", ".jnilib")):
(natives / Path(name).name).write_bytes(archive.read(name))
jars.extend(fabric_libraries())
if assets:
store, index = lab.launcher_assets(manifest)
unique = {v["hash"] for v in json.loads(index.read_text())["objects"].values()}
print(f"Verifying {len(unique)} game assets in {store}...", flush=True)
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(lambda checksum: lab.launcher_object(store, checksum), sorted(unique)))
return manifest, jars, natives
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["prepare", "demo"])
parser.add_argument("--instance", type=Path, default=CACHE / "demo")
parser.add_argument("--heap", default="4G")
parser.add_argument("--compact-headers", action="store_true", help="Enable Java 25 compact object headers for this demo process")
parser.add_argument("--gc", choices=["default", "g1", "zgc"], default="default", help="Select a collector for this process; default leaves JVM policy in use")
args = parser.parse_args()
if not re.fullmatch(r"[1-9][0-9]*[MGmg]", args.heap):
parser.error("--heap must look like 4G")
manifest, jars, natives = prepare_client()
if args.command == "prepare":
return
instance = args.instance.resolve()
instance.mkdir(parents=True, exist_ok=True)
command = ["java", *jvm_options(args.heap, args.compact_headers, args.gc),
*conditional_client_jvm_options(manifest),
"--enable-native-access=ALL-UNNAMED",
f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}",
"-Dfabric.log.disableAnsi=true", "-cp", os.pathsep.join(map(str, jars)),
"net.fabricmc.loader.impl.launch.knot.KnotClient",
"--username", "HorizonDemo", "--version", manifest["id"], "--gameDir", str(instance),
"--assetsDir", str(lab.minecraft_dir() / "assets"), "--assetIndex", manifest["assetIndex"]["id"],
"--accessToken", "0", "--uuid", "00000000000000000000000000000000", "--demo",
"--width", "1280", "--height", "800"]
subprocess.run(command, cwd=instance, check=True)
if __name__ == "__main__":
main()
+4 -4
View File
@@ -32,8 +32,8 @@ Two more Java servers, both dev-only downloads into .local/server-bench/jars (ne
SHA-256 it publishes, with Paper's own defaults except `connection-throttle` (off: the bots all join from
one address). Paperclip patches the pinned server jar (your copy, put in
its cache so nothing is fetched from Mojang).
- `fabric`: the pinned vanilla server on the pinned Fabric loader (packs/fabric.lock.json) with Lithium from
packs/mods.lock.json (and Fabric API only if Lithium asks for it), checked against the lock's SHA-512.
- `fabric`: the pinned vanilla server on the pinned Fabric loader (tools/benchmark-deps/fabric.lock.json) with Lithium from
tools/benchmark-deps/mods.lock.json (and Fabric API only if Lithium asks for it), checked against the lock's SHA-512.
Both run with the same heap as vanilla (`--heap`).
"""
@@ -190,8 +190,8 @@ def paper_jar():
def fabric_mods():
"""Lithium from packs/mods.lock.json, plus Fabric API if Lithium depends on it (checked, cached)."""
lock = json.loads((ROOT / 'packs/mods.lock.json').read_text())
"""Lithium from tools/benchmark-deps/mods.lock.json, plus Fabric API if Lithium depends on it (checked, cached)."""
lock = json.loads((ROOT / 'tools/benchmark-deps/mods.lock.json').read_text())
def fetch(name):
project = lock['projects'][name]
return runtime.fetch(project['url'], JARS / project['filename'], project['hashes']['sha512'], 'sha512')
+516
View File
@@ -0,0 +1,516 @@
#!/usr/bin/env python3
"""Server resource packs end to end: a real Horizon client joins a real dedicated server (vanilla 26.3's, or
Horizon's with --horizon-server BIN) that offers a test pack from a local HTTP server, through tools/net_capture.py,
which records the statuses the client sends back.
The pack is built here: dirt recoloured blue, and three lang strings (dirt's name, the pause menu's "Back to Game",
the server list's "Join Server"). Each scenario sets the server list entry's Server Resource Packs setting in
servers.dat, joins, answers the prompt the way a player would (horizon-ctl clicks its buttons), and checks the
statuses against what vanilla's client sends (ServerPackManager):
- required, Prompt, Disconnect: no status, the disconnected screen says "This server requires a custom resource
pack", the setting stays Prompt;
- required, Prompt, Proceed: ACCEPTED, DOWNLOADED, SUCCESSFULLY_LOADED; the setting becomes Enabled, the file is in
downloads/ under its SHA-1 with a log.json entry, the HTTP request carries vanilla's X-Minecraft-* headers, the
blue dirt is on screen (screenshot) and the pause menu says the pack's "Back to Game"; after leaving, the server
list says "Join Server" again (the pack is gone);
- required, Enabled: no prompt, the same three statuses, and no second download (the cache);
- required with a wrong SHA-1: ACCEPTED, FAILED_DOWNLOAD, and the player still joins;
- optional, Prompt, No: DECLINED, joins, the setting becomes Disabled; then joining again sends DECLINED without
asking; then Prompt and Yes: the pack (no hash given) is downloaded and loaded;
- optional on a dead URL: ACCEPTED, FAILED_DOWNLOAD, joins.
python3 tools/server_pack_e2e.py # vanilla's server
python3 tools/server_pack_e2e.py --horizon-server target/release/horizon-client
Every game and server here runs in fresh temporary folders (HORIZON_HOME, HORIZON_LAUNCHER_HOME, XDG_*), with no
audio and no self-update. Needs .local (the vanilla jars and prepared resources) and a built horizon-client and
horizon-ctl (--bin DIR, default target/fast).
"""
import argparse
import hashlib
import http.server
import json
import os
from pathlib import Path
import shutil
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
import zipfile
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parent))
import lab # noqa: E402
import net_capture # noqa: E402
import test_rust_parity as base # noqa: E402
from test_dedicated_server_parity import Server, free_port # noqa: E402
# ServerboundResourcePackPacket.Action, by ordinal.
ACTIONS = ['successfully_loaded', 'declined', 'failed_download', 'accepted', 'downloaded', 'invalid_url',
'failed_reload', 'discarded']
LOADED = ['accepted', 'downloaded', 'successfully_loaded']
FAILED = ['accepted', 'failed_download']
REQUIRED_REASON = 'This server requires a custom resource pack'
PLAYER = 'Steve'
PROPERTIES = {
'online-mode': 'false', 'white-list': 'false', 'level-seed': '12345', 'level-type': 'minecraft\\:flat',
'generate-structures': 'false', 'view-distance': '3', 'simulation-distance': '3', 'spawn-protection': '0',
'pause-when-empty-seconds': '-1', 'gamemode': 'creative',
}
class Failed(Exception):
pass
def check(condition, what):
if not condition:
raise Failed(what)
print(f' ok: {what}')
# The pack.
def png(width, height, pixel):
rows = b''.join(b'\0' + b''.join(bytes(pixel(x, y)) for x in range(width)) for y in range(height))
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
header = struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header) + chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b'')
def build_pack(path):
"""The test pack, byte for byte the same every time (fixed dates), and its SHA-1."""
def blue(x, y):
return (40, 90, 230, 255) if (x // 4 + y // 4) % 2 else (20, 50, 170, 255)
files = {
'pack.mcmeta': json.dumps({'pack': {'description': 'Horizon server pack test',
'min_format': 97, 'max_format': 97}}).encode(),
'assets/minecraft/textures/block/dirt.png': png(16, 16, blue),
'assets/minecraft/lang/en_us.json': json.dumps({
'block.minecraft.dirt': 'Blue Test Dirt',
'menu.returnToGame': 'Back to Game (server pack)',
'selectServer.select': 'Join Server (server pack)',
}).encode(),
}
with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as z:
for name, data in files.items():
z.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data)
return hashlib.sha1(path.read_bytes()).hexdigest()
def decode_png(data):
"""RGB(A) pixels of an 8-bit PNG: (width, height, rows of (r, g, b))."""
pos, idat, width = 8, b'', 0
while pos < len(data):
length, kind = struct.unpack('>I4s', data[pos:pos + 8])
body = data[pos + 8:pos + 8 + length]
if kind == b'IHDR':
width, height, depth, colour = struct.unpack('>IIBB', body[:10])
assert depth == 8 and colour in (2, 6), (depth, colour)
channels = 4 if colour == 6 else 3
elif kind == b'IDAT':
idat += body
pos += 12 + length
raw, stride, rows, previous = zlib.decompress(idat), width * channels, [], bytearray(width * channels)
for y in range(height):
kind, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])
for i in range(stride):
left = line[i - channels] if i >= channels else 0
up, corner = previous[i], previous[i - channels] if i >= channels else 0
if kind == 1:
line[i] = (line[i] + left) & 255
elif kind == 2:
line[i] = (line[i] + up) & 255
elif kind == 3:
line[i] = (line[i] + (left + up) // 2) & 255
elif kind == 4:
p = left + up - corner
pa, pb, pc = abs(p - left), abs(p - up), abs(p - corner)
line[i] = (line[i] + (left if pa <= pb and pa <= pc else up if pb <= pc else corner)) & 255
rows.append([tuple(line[x * channels:x * channels + 3]) for x in range(width)])
previous = line
return width, height, rows
def blue_share(path):
"""How much of the picture's lower middle (the ground under a player looking down) is blue."""
width, height, rows = decode_png(path.read_bytes())
samples = [rows[y][x] for y in range(height // 2 + height // 8, height - height // 8, 4)
for x in range(width // 4, 3 * width // 4, 4)]
return sum(b > r + 60 and b > g + 30 for r, g, b in samples) / len(samples)
# The HTTP server the pack comes from.
class Files(http.server.ThreadingHTTPServer):
def __init__(self, files):
self.files, self.requests = files, []
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(handler):
headers = {k: v for k, v in handler.headers.items() if k.lower().startswith(('x-minecraft', 'user-agent'))}
self.requests.append((handler.path, headers))
data = self.files.get(handler.path)
if data is None:
handler.send_error(404)
return
handler.send_response(200)
handler.send_header('Content-Type', 'application/zip')
handler.send_header('Content-Length', str(len(data)))
handler.end_headers()
handler.wfile.write(data)
def log_message(handler, *args):
pass
super().__init__(('127.0.0.1', 0), Handler)
threading.Thread(target=self.serve_forever, daemon=True).start()
def url(self, path):
return f'http://127.0.0.1:{self.server_address[1]}{path}'
# servers.dat (NbtIo.write: uncompressed, a named root compound).
def nbt_string(s):
data = s.encode()
return struct.pack('>H', len(data)) + data
def write_servers(path, ip, setting):
"""One entry for ip; setting True (Enabled), False (Disabled) or None (Prompt: no acceptTextures)."""
entry = b'\x08' + nbt_string('name') + nbt_string('Pack test') + b'\x08' + nbt_string('ip') + nbt_string(ip)
if setting is not None:
entry += b'\x01' + nbt_string('acceptTextures') + bytes([int(setting)])
root = b'\x09' + nbt_string('servers') + b'\x0a' + struct.pack('>i', 1) + entry + b'\x00'
path.write_bytes(b'\x0a' + nbt_string('') + root + b'\x00')
def read_setting(path):
data = path.read_bytes()
key = b'\x01' + nbt_string('acceptTextures')
at = data.find(key)
return None if at < 0 else bool(data[at + len(key)])
# The game.
class Game:
def __init__(self, bins, resources, work):
self.home = work / 'home'
for d in ('home', 'launcher', 'data', 'config'):
(work / d).mkdir(parents=True)
self.env = dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_LAUNCHER_HOME=str(work / 'launcher'),
XDG_DATA_HOME=str(work / 'data'), XDG_CONFIG_HOME=str(work / 'config'),
HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
self.base = [str(bins / 'horizon-ctl'), '--socket', str(work / 'c.sock')]
self.log = work / 'c.log'
reply = self('launch', '--game', bins / 'horizon-client', '--offscreen', '--resources', resources)
self.pid = reply.get('pid')
def __call__(self, *words, ok=True, timeout=300):
result = subprocess.run(self.base + [str(w) for w in words], cwd=self.home, env=self.env,
capture_output=True, text=True, timeout=timeout)
lines = result.stdout.strip().splitlines()
reply = json.loads(lines[-1]) if lines else {'error': result.stderr.strip()}
print(f' {" ".join(map(str, words))[:80]} -> {json.dumps(reply)[:200]}')
if ok and (result.returncode or 'error' in reply):
raise Failed(f'{" ".join(map(str, words))}: {reply}')
return reply
def labels(self):
return [w.get('label') for w in self('ui').get('widgets', [])]
def wait_widget(self, widget, timeout=60):
return self('wait-for', 'widget', widget, '--timeout', timeout, ok=False)
def quit(self):
try:
self('quit', ok=False, timeout=60)
except subprocess.TimeoutExpired:
pass
if self.pid:
for _ in range(40):
try:
os.kill(self.pid, 0)
except OSError:
return
time.sleep(0.5)
os.kill(self.pid, 9)
def statuses(capture, conn):
"""The resource pack statuses the client sent on one connection: (id, action), in order."""
out = []
for e in net_capture.load(capture):
if e.get('conn') == conn and e.get('dir') == 'c2s' and e.get('name') == 'resource_pack':
data = bytes.fromhex(e['data'])
out.append((data[:16].hex(), ACTIONS[data[16]]))
return out
def connections(capture):
return max([e['conn'] for e in net_capture.load(capture) if 'conn' in e], default=0)
class Run:
def __init__(self, args, out):
self.args, self.out = args, out
lock, jars, libraries = base.verify_artifacts()
deps = os.pathsep.join(map(str, [jars['server'], *libraries]))
self.vanilla = ['java', '-Xmx2g', '-cp', deps, 'net.minecraft.server.Main', 'nogui']
self.resources = lab.LOCAL / 'horizon-client' / lab.VERSION
self.files = {}
self.http = Files(self.files)
self.sha1 = build_pack(out / 'test-pack.zip')
self.files['/test-pack.zip'] = (out / 'test-pack.zip').read_bytes()
self.files['/optional-pack.zip'] = self.files['/test-pack.zip']
dead = free_port() # nothing listens there
self.packs = {
'required': {'resource-pack': self.http.url('/test-pack.zip'), 'resource-pack-sha1': self.sha1,
'require-resource-pack': 'true', 'resource-pack-id': '5b2c7a4e-1f3d-4c8b-9a6e-2d4f8b1c3e5a',
'resource-pack-prompt': '["Blue dirt for ",{"text":"this test","color":"aqua"}]'},
'bad-sha1': {'resource-pack': self.http.url('/test-pack.zip'), 'resource-pack-sha1': '0' * 40,
'require-resource-pack': 'true'},
'optional': {'resource-pack': self.http.url('/optional-pack.zip'), 'require-resource-pack': 'false'},
'dead-url': {'resource-pack': f'http://127.0.0.1:{dead}/gone.zip', 'require-resource-pack': 'false'},
}
self.results = []
def start_server(self, kind, work):
directory = work / f'server-{kind}'
directory.mkdir()
port = free_port()
props = dict(PROPERTIES, **self.packs[kind], **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
encoding='iso-8859-1')
(directory / 'eula.txt').write_text('eula=true\n')
if self.args.horizon_server:
command = [self.args.horizon_server, '--resources', self.resources, '--dedicated', '--nogui']
else:
command = self.vanilla
server = Server(command, directory, f'server-{kind}')
server.wait_for(r'Done \(', timeout=300)
return server, port
def join(self, game, address, scenario):
"""Connects; returns the capture's connection number."""
game('connect', address, PLAYER)
deadline = time.time() + 30
while connections(self.capture) <= self.conn and time.time() < deadline:
time.sleep(0.2)
self.conn = connections(self.capture)
print(f' [{scenario}] connection {self.conn}')
return self.conn
def scenario(self, name, fn):
print(f'- {name}')
try:
fn()
self.results.append((name, 'pass', ''))
except Exception as e: # noqa: BLE001: report every scenario
print(f' FAILED: {e}')
self.results.append((name, 'FAIL', str(e)[:300]))
if self.game('state', ok=False).get('screen') not in (None, 'title'):
self.leave(self.game)
def wait_statuses(self, conn, want, timeout=60):
deadline = time.time() + timeout
while time.time() < deadline:
got = [a for _, a in statuses(self.capture, conn)]
if len(got) >= len(want) and got[:len(want)] == want or got[:1] and got != want[:len(got)]:
break
time.sleep(0.3)
time.sleep(1.5) # nothing more comes after the last one
got = [a for _, a in statuses(self.capture, conn)]
check(got == want, f'statuses {got} == {want}')
def leave(self, game):
game('disconnect', ok=False)
time.sleep(1)
def run(self):
work = Path(tempfile.mkdtemp(prefix='hz-server-packs-'))
print(f'scratch: {work}')
# The servers too get scratch homes (the game sets its own below).
for var, sub in (('HORIZON_HOME', 'home'), ('HORIZON_LAUNCHER_HOME', 'launcher'), ('XDG_DATA_HOME', 'data'),
('XDG_CONFIG_HOME', 'config')):
(work / 'servers' / sub).mkdir(parents=True)
os.environ[var] = str(work / 'servers' / sub)
os.environ.update(HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
game = self.game = Game(Path(self.args.bin), self.resources, work / 'game')
servers_dat = game.home / 'servers.dat'
downloads = game.home / 'downloads'
try:
for kind, scenarios in self.plan(game, servers_dat, downloads):
server, port = self.start_server(kind, work)
# One capture per server: its connections are numbered from 1.
self.capture, self.conn = self.out / f'capture-{kind}.jsonl', 0
self.capture.touch()
listen = free_port()
stop = net_capture.start_background(listen, f'127.0.0.1:{port}', self.capture)
self.address = f'127.0.0.1:{listen}'
try:
self.server = server
for name, fn in scenarios:
self.scenario(f'{kind}: {name}', fn)
finally:
stop.set()
server.stop()
shutil.copy(server.log_path, self.out / server.log_path.name)
finally:
game.quit()
if game.log.exists():
shutil.copy(game.log, self.out / 'client.log')
if downloads.exists():
shutil.copytree(downloads, self.out / 'downloads')
return work
def plan(self, game, servers_dat, downloads):
sha1 = self.sha1
def required_disconnect():
write_servers(servers_dat, self.address, None)
conn = self.join(game, self.address, 'decline')
check(game.wait_widget('disconnect').get('ok'), 'the required prompt opened')
labels = game.labels()
check('Proceed' in labels and 'Disconnect' in labels, f'Proceed and Disconnect buttons: {labels}')
game('screenshot', self.out / 'prompt-required.png')
game('click', 'disconnect')
self.wait_statuses(conn, [])
screen = json.dumps(game('screen'))
check(REQUIRED_REASON in screen, 'the disconnected screen says "This server requires a custom resource pack"')
check(read_setting(servers_dat) is None, 'the setting stays Prompt')
check(not any(p == '/test-pack.zip' for p, _ in self.http.requests), 'nothing was downloaded')
def required_proceed():
conn = self.join(game, self.address, 'proceed')
check(game.wait_widget('proceed').get('ok'), 'the required prompt opened')
game('click', 'proceed')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, LOADED)
check(read_setting(servers_dat) is True, 'the setting became Enabled (acceptTextures 1)')
pack_id = self.packs['required']['resource-pack-id']
check((downloads / pack_id / sha1).exists(), f'downloads/{pack_id}/{sha1} is cached')
log = json.loads((downloads / 'log.json').read_text().splitlines()[-1])
check(log.get('id') == pack_id and log.get('hash') == sha1
and log.get('file', {}).get('name') == f'{pack_id}/{sha1}', f'log.json entry {log}')
path, headers = [r for r in self.http.requests if r[0] == '/test-pack.zip'][-1]
want = {'X-Minecraft-Username': PLAYER, 'X-Minecraft-Version': lab.VERSION,
'X-Minecraft-Version-ID': lab.VERSION, 'X-Minecraft-Pack-Format': '97.1',
'User-Agent': f'Minecraft Java/{lab.VERSION}'}
check(all(headers.get(k) == v for k, v in want.items()) and len(headers.get('X-Minecraft-UUID', '')) == 32,
f'download headers {headers}')
self.server.console(f'execute at {PLAYER} run fill ~-6 ~-1 ~-6 ~6 ~-1 ~6 minecraft:dirt')
game('look', 0, 90)
game('wait', 40)
shot = self.out / 'applied-blue-dirt.png'
game('screenshot', shot)
share = blue_share(shot)
check(share > 0.5, f'the ground is the pack\'s blue dirt ({share:.0%} of the samples)')
game('key', 'esc', 'tap')
game('wait', 5)
labels = game.labels()
check('Back to Game (server pack)' in labels, f'the pause menu uses the pack\'s lang: {labels}')
game('key', 'esc', 'tap')
self.leave(game)
labels = game.labels()
check('Join Server' in labels and 'Join Server (server pack)' not in labels,
f'after leaving, the pack is gone: {labels}')
def required_enabled():
before = len(self.http.requests)
conn = self.join(game, self.address, 'enabled')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, LOADED)
check(len(self.http.requests) == before, 'no second download: the cached file is used')
game('key', 'esc', 'tap')
game('wait', 5)
check('Back to Game (server pack)' in game.labels(), 'the pack is applied without a prompt')
game('key', 'esc', 'tap')
self.leave(game)
def bad_sha1():
write_servers(servers_dat, self.address, True)
conn = self.join(game, self.address, 'bad-sha1')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, FAILED)
entries = [json.loads(line) for line in (downloads / 'log.json').read_text().splitlines()]
failed = [e for e in entries if e.get('hash') == '0' * 40]
check(failed and failed[-1].get('error') == 'download_failed' and 'file' not in failed[-1],
f'log.json records the failure: {failed[-1:]}')
self.leave(game)
def optional_no():
write_servers(servers_dat, self.address, None)
conn = self.join(game, self.address, 'optional-no')
check(game.wait_widget('no').get('ok'), 'the optional prompt opened')
labels = game.labels()
check('Yes' in labels and 'No' in labels, f'Yes and No buttons: {labels}')
game('screenshot', self.out / 'prompt-optional.png')
game('click', 'no')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, ['declined'])
check(read_setting(servers_dat) is False, 'the setting became Disabled (acceptTextures 0)')
self.leave(game)
def optional_disabled():
conn = self.join(game, self.address, 'optional-disabled')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, ['declined'])
self.leave(game)
def optional_yes():
write_servers(servers_dat, self.address, None)
conn = self.join(game, self.address, 'optional-yes')
check(game.wait_widget('yes').get('ok'), 'the optional prompt opened')
game('click', 'yes')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, LOADED)
check(any(r[0] == '/optional-pack.zip' for r in self.http.requests), 'downloaded without a hash')
self.leave(game)
def dead_url():
write_servers(servers_dat, self.address, True)
conn = self.join(game, self.address, 'dead-url')
game('wait-for', 'loaded', '--timeout', 180)
self.wait_statuses(conn, FAILED)
self.leave(game)
return [
('required', [('Disconnect at the prompt', required_disconnect), ('Proceed', required_proceed),
('Enabled, cached', required_enabled)]),
('bad-sha1', [('wrong SHA-1', bad_sha1)]),
('optional', [('No at the prompt', optional_no), ('Disabled', optional_disabled),
('Yes at the prompt, no hash', optional_yes)]),
('dead-url', [('dead URL', dead_url)]),
]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--bin', default=str(lab.cargo_target() / 'fast'), help='horizon-client and horizon-ctl')
parser.add_argument('--horizon-server', help='a horizon-client binary to run as the dedicated server')
parser.add_argument('--out', default=str(lab.LOCAL / 'server-pack-e2e'))
args = parser.parse_args()
out = Path(args.out) / ('horizon' if args.horizon_server else 'vanilla')
shutil.rmtree(out, ignore_errors=True)
out.mkdir(parents=True)
run = Run(args, out)
work = run.run()
print(f'\nserver: {"horizon" if args.horizon_server else "vanilla 26.3"}; evidence in {out}')
for name, result, detail in run.results:
print(f' {result:4} {name}' + (f': {detail}' if detail else ''))
shutil.rmtree(work, ignore_errors=True)
if any(r != 'pass' for _, r, _ in run.results):
sys.exit(1)
if __name__ == '__main__':
main()
-179
View File
@@ -1,179 +0,0 @@
#!/usr/bin/env python3
"""Start real clients and verify a nonuniform GPU framebuffer readback."""
import argparse
import hashlib
import json
import os
import platform
import re
import shutil
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
from .test_culling_rays import FixtureTimeout, run_fixture
from .test_dispatch import failure_summary
except ImportError:
import build_mod
import build_pack
from test_culling_rays import FixtureTimeout, run_fixture
from test_dispatch import failure_summary
def graphics_failure_summary(run, report_count):
"""Selected stages/types/codes/methods only; messages and paths stay private."""
result = failure_summary(run, report_count)
pattern = r'(?<![\w.$])((?:java|org\.lwjgl|com\.mojang|net\.minecraft|net\.fabricmc|org\.spongepowered|dev\.horizonlab)\.[A-Za-z_$][\w.$]{0,160}(?:Exception|Error))(?=[:\s]|$)'
observed = set(result['java_exception_types']) | set(re.findall(pattern, run.stdout, re.ASCII))
expected_auth = {name for name in observed if name.startswith(('com.mojang.authlib.', 'com.mojang.realmsclient.'))}
result['java_exception_types'] = sorted(observed - expected_auth)[:8]
result['expected_demo_authentication_errors_observed'] = bool(expected_auth)
for key, marker in [('backend_attempts', 'HORIZON_GRAPHICS_BACKEND_ATTEMPT '),
('created_devices', 'HORIZON_GRAPHICS_DEVICE_CREATED ')]:
result[key] = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line][:16]
result['client_initializer_reached'] = 'HORIZON_CLIENT_GRAPHICS_INITIALIZER_READY' in run.stdout
result['readback_requested'] = 'HORIZON_CLIENT_GRAPHICS_READBACK_REQUESTED' in run.stdout
result['readback_callback_received'] = 'HORIZON_CLIENT_GRAPHICS_READBACK_RECEIVED' in run.stdout
inspection_marker = 'HORIZON_CLIENT_GRAPHICS_READBACK_INSPECTED '
inspections = []
fields = ('framebuffer_width', 'framebuffer_height', 'sampled_pixels', 'distinct_sampled_rgb')
for line in run.stdout.splitlines():
if inspection_marker not in line:
continue
try:
item = json.loads(line.split(inspection_marker, 1)[1])
except json.JSONDecodeError:
continue
if isinstance(item, dict) and all(type(item.get(field)) is int
and 0 <= item[field] <= 2_147_483_647 for field in fields):
inspections.append({field: item[field] for field in fields})
if len(inspections) == 4:
break
result['readback_inspections'] = inspections
waiting_marker = 'HORIZON_CLIENT_GRAPHICS_WAIT_STATE '
boolean_fields = ('world_loaded', 'player_present', 'overlay_present',
'screen_present', 'window_active', 'paused')
result['last_waiting_state'] = None
for line in run.stdout.splitlines():
if waiting_marker not in line:
continue
try:
state = json.loads(line.split(waiting_marker, 1)[1])
except json.JSONDecodeError:
continue
if (isinstance(state, dict) and all(type(state.get(field)) is bool for field in boolean_fields)
and type(state.get('ready_client_ticks')) is int and 0 <= state['ready_client_ticks'] <= 2_147_483_647):
result['last_waiting_state'] = {field: state[field] for field in (*boolean_fields, 'ready_client_ticks')}
# These exact messages belong to our private fixture. Never emit arbitrary
# exception messages or infer that a separately logged Vulkan code caused it.
categories = {'Uniform title readback': 'uniform_readback',
'Incomplete title framebuffer': 'small_framebuffer',
'Private client graphics readback failed': 'callback_exception'}
result['probe_failure_categories'] = [category for message, category in categories.items()
if 'java.lang.AssertionError: ' + message in run.stdout]
result['vulkan_error_codes'] = sorted(set(re.findall(r'\bVK_ERROR_[A-Z_0-9]{1,100}\b', run.stdout)))[:16]
result['fatal_jvm_error'] = 'A fatal error has been detected by the Java Runtime Environment' in run.stdout
# Only Java stack-frame lines from graphics namespaces. Strip module prefixes,
# filenames, line numbers and messages; these identify locations, not causes.
stack_pattern = (r'^\s*at (?:[A-Za-z0-9_.@$-]{1,80}/{1,2})?'
r'((?:com\.mojang\.(?:renderpearl|blaze3d)\.|'
r'net\.minecraft\.client\.(?:renderer\.|Screenshot\.))'
r'[A-Za-z0-9_.$<>]{1,180})\(')
methods = re.findall(stack_pattern, run.stdout, re.MULTILINE | re.ASCII)
result['observed_graphics_stack_methods'] = list(dict.fromkeys(methods))[:8]
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--native-display', action='store_true')
parser.add_argument('--profile', action='append', choices=sorted(build_pack.PROFILES))
parser.add_argument('--backend', choices=['opengl', 'vulkan'], help='Override backend in these private instances only')
parser.add_argument('--world', action='store_true', help='Create/open a disposable built-in demo world instead of stopping at the title')
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_integration_fixture('client-graphics',
'dev.horizonlab.metrics.ClientGraphicsIntegration',
fixture_mixins=['GraphicsBackendTraceMixin'], fixture_dependencies={})
version = build_pack.read_lock()['pack_version']
mod = root / 'dist' / f'horizon-{version}.jar'
original_hash = hashlib.sha256(mod.read_bytes()).hexdigest()
results = []
for profile in args.profile or ['core-performance', 'm2-balanced']:
instance = root / '.local/runtime' / ('client-graphics-' + profile
+ ('-override-' + args.backend if args.backend else '') + ('-world' if args.world else ''))
build_pack.prepare_instance(profile, instance, mod)
if args.world:
(instance / 'config/client-graphics-world.flag').touch()
if args.backend:
options = instance / 'options.txt'
text, count = re.subn(r'^preferredGraphicsBackend:.*$',
'preferredGraphicsBackend:' + json.dumps(args.backend), options.read_text(), flags=re.MULTILINE)
if count != 1:
raise AssertionError('Private backend preference is missing or ambiguous')
options.write_text(text)
shutil.copy2(fixture, instance / 'mods/client-graphics-fixture.jar')
command = [sys.executable, str(root / 'tools/runtime.py'), 'demo',
'--instance', str(instance), '--heap', '3G']
if platform.system() == 'Linux' and not args.native_display:
command = ['xvfb-run', '-a', *command]
try:
run = run_fixture(command, instance, os.environ.copy())
except FixtureTimeout as error:
diagnostics = graphics_failure_summary(error.run, 0)
diagnostics.update(fixture='client-graphics', profile=profile,
completed=False, timed_out=True, timeout_seconds=240)
print('HORIZON_FIXTURE_FAILURE ' + json.dumps(diagnostics), flush=True)
raise RuntimeError('Graphics probe did not finish; diagnostics remain private') from None
marker = 'HORIZON_CLIENT_GRAPHICS_RESULT '
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
trace_marker = 'HORIZON_GRAPHICS_BACKEND_ATTEMPT '
attempts = [json.loads(line.split(trace_marker, 1)[1]) for line in run.stdout.splitlines() if trace_marker in line]
if run.returncode or len(reports) != 1:
diagnostics = graphics_failure_summary(run, len(reports))
diagnostics['profile'] = profile
diagnostics['preferred_backend'] = args.backend or build_pack.PROFILES[profile].get('backend', 'opengl')
print('HORIZON_FIXTURE_FAILURE ' + json.dumps(diagnostics), flush=True)
raise RuntimeError('Graphics probe failed; diagnostics remain private')
report = reports[0]
if report['observed_mode'] != ('world' if args.world else 'title') or report['ready_client_ticks'] < 40:
raise AssertionError('Client never reached the requested graphics scene')
if report['overlay_present'] is not False:
raise AssertionError('Client graphics scene still has a loading overlay')
if args.world:
if report['world_loaded'] is not True or report['window_active'] is not True:
raise AssertionError('Client never reached focused demo-world gameplay')
if not list((instance / 'saves/Demo_World').rglob('*.dat')):
raise AssertionError('Disposable world did not leave saved data')
if report['sampled_pixels'] < 256 or report['distinct_sampled_rgb'] < 8:
raise AssertionError('GPU readback was uniform')
if hashlib.sha256((instance / 'mods' / mod.name).read_bytes()).hexdigest() != original_hash:
raise AssertionError('Runtime original mod differs from the intended build')
screenshot = instance / 'client-graphics-private.png'
if not screenshot.is_file() or hashlib.sha256(screenshot.read_bytes()).hexdigest() != report['private_png_sha256']:
raise AssertionError('Private screenshot evidence is missing or changed')
report.update(profile=profile, preferred_backend=args.backend or build_pack.PROFILES[profile].get('backend', 'opengl'),
launcher_exit_code=run.returncode, backend_attempts=attempts)
results.append(report)
print(json.dumps(report), flush=True)
output = root / 'dist/client-graphics-smoke.json'
output.write_text(json.dumps({'schema': 1, 'platform': platform.platform(),
'architecture': platform.machine(), 'minecraft': lab.VERSION,
'original_mod_sha256': original_hash, 'results': results,
'limits': ['Short scene startup and nonuniform framebuffer readback only.',
'World mode uses the ordinary limited demo; world files remain private.',
'No exhaustive gameplay, visual-correctness, FPS or M2 Pro performance claim.',
'Vulkan preference can fall back; inspect the observed backend.',
'PNG images, assets and full logs remain in the private runtime directory.']}, indent=2) + '\n')
print('Client graphics startup/readback checks passed.', flush=True)
if __name__ == '__main__':
main()
-69
View File
@@ -1,69 +0,0 @@
#!/usr/bin/env python3
"""Check live culling whitelist registration and the optional empty-iterator shortcut."""
import argparse
import json
import os
import platform
import shutil
import subprocess
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
except ImportError:
import build_mod
import build_pack
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--native-display", action="store_true")
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_culling_empty_fixture()
mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar"
results = []
for enabled in [False, True]:
instance = root / ".local/runtime" / ("culling-empty-fixture-patched" if enabled else "culling-empty-fixture-upstream")
build_pack.prepare_instance("m2-balanced", instance, mod)
shutil.copy2(fixture, instance / "mods/culling-empty-fixture.jar")
(instance / "config/horizon-culling-empty.properties").write_text(f"enabled={str(enabled).lower()}\n")
command = [sys.executable, str(root / "tools/runtime.py"), "demo", "--instance", str(instance), "--heap", "3G", "--compact-headers"]
if platform.system() == "Linux" and not args.native_display:
command = ["xvfb-run", "-a", *command]
environment = os.environ.copy()
environment["_JAVA_OPTIONS"] = "-Dhorizon.fixture.exit=true"
run = subprocess.run(command, cwd=root, env=environment, text=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, timeout=240)
(instance / "fixture.log").write_text(run.stdout)
marker = "HORIZON_CULLING_EMPTY_RESULT "
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(reports) != 1:
raise RuntimeError(f"Culling empty fixture failed; inspect {instance / 'fixture.log'}")
report = reports[0]
if report["enabled"] != enabled or not report["live_registration_checked"] or not report["block_callback_order_checked"] or not report["type_guard_checked"] or report["result"]:
raise AssertionError("Applied hook or semantic outcome did not match")
results.append(report)
print(json.dumps(report), flush=True)
if [r["empty_iterator_calls"] for r in results] != [1, 0]:
raise AssertionError("Empty shortcut did not apply to actual methods")
output = root / "dist/culling-empty-integration.json"
output.write_text(json.dumps({"schema": 1, "platform": platform.platform(), "architecture": platform.machine(),
"minecraft": lab.VERSION, "entity_culling": "1.11.2", "results": results,
"notes": ["Actual publisher whitelist methods inside Fabric; live registration and block-entity callbacks checked.",
"Nonempty iteration, callback order, short circuit, null/wrong-type inputs and clearing retain upstream behavior.",
"Empty-state iterator counts use a private instrumented set; allocation loop uses normal empty HashSets.",
"Entity callbacks with a valid game entity are not exercised by this menu-only fixture.",
"JIT escape analysis can remove allocations in an isolated loop; real culling-thread profiles are needed.",
"Not a game FPS, whole-game RAM, visual equivalence or Mac GPU benchmark."]}, indent=2) + "\n")
print(f"Applied empty whitelist checks passed: {output}")
if __name__ == "__main__":
main()
-105
View File
@@ -1,105 +0,0 @@
#!/usr/bin/env python3
"""Compare actual visibility geometry and per-instance numeric scratch ownership."""
import argparse
import hashlib
import json
import os
import platform
import shutil
import signal
import subprocess
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
except ImportError:
import build_mod
import build_pack
class FixtureTimeout(RuntimeError):
"""Keep timeout output private while allowing selected caller diagnostics."""
def __init__(self, run, private_log):
super().__init__(f"Private fixture timed out; inspect {private_log}")
self.run = run
def run_fixture(command, instance, environment):
# Keep all children of this private fixture in a controllable process group.
process = subprocess.Popen(command, cwd=build_pack.ROOT, env=environment, text=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
start_new_session=platform.system() != "Windows")
def stop_tree(force=False):
if platform.system() == "Windows":
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], capture_output=True, check=False)
else:
try: os.killpg(process.pid, signal.SIGKILL if force else signal.SIGTERM)
except ProcessLookupError: pass
try:
output, _ = process.communicate(timeout=240)
except subprocess.TimeoutExpired:
stop_tree()
try: output, _ = process.communicate(timeout=10)
except subprocess.TimeoutExpired:
stop_tree(True); output, _ = process.communicate(timeout=10)
(instance / "fixture.log").write_text(output)
raise FixtureTimeout(subprocess.CompletedProcess(command, process.returncode, output),
instance / 'fixture.log') from None
(instance / "fixture.log").write_text(output)
return subprocess.CompletedProcess(command, process.returncode, output)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--native-display", action="store_true")
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_integration_fixture("culling-rays", "dev.horizonlab.dispatch.CullingRayIntegration", ["entityculling"], ["CullingRayAccess"])
mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar"
original_sha256 = hashlib.sha256(mod.read_bytes()).hexdigest()
results = []
for enabled in [False, True]:
instance = root / ".local/runtime" / ("culling-rays-fixture-patched" if enabled else "culling-rays-fixture-upstream")
build_pack.prepare_instance("m2-balanced", instance, mod)
if hashlib.sha256((instance / "mods" / mod.name).read_bytes()).hexdigest() != original_sha256:
raise AssertionError("Fixture runtime mod does not match the intended build")
shutil.copy2(fixture, instance / "mods/culling-rays-fixture.jar")
(instance / "config/horizon-culling-rays.properties").write_text(f"enabled={str(enabled).lower()}\n")
command = [sys.executable, str(root / "tools/runtime.py"), "demo", "--instance", str(instance), "--heap", "3G", "--compact-headers"]
if platform.system() == "Linux" and not args.native_display:
command = ["xvfb-run", "-a", *command]
environment = os.environ.copy()
environment["_JAVA_OPTIONS"] = "-Dhorizon.fixture.exit=true"
run = run_fixture(command, instance, environment)
marker = "HORIZON_CULLING_RAYS_RESULT "
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(reports) != 1:
raise RuntimeError(f"Culling scratch fixture failed; inspect {instance / 'fixture.log'}")
report = reports[0]
if report["enabled"] != enabled or report["public_boxes"] != 12800 or report["edge_rays"] != 2197 or not report["input_unchanged"] or not report["scratch_ownership_checked"]:
raise AssertionError("Applied culling scratch fixture did not complete its geometry checks")
results.append(report)
print(json.dumps(report), flush=True)
for key in ["visibility_digest", "query_digest", "intersection_digest", "provider_reads", "checksum"]:
if results[0][key] != results[1][key]:
raise AssertionError(f"Scratch redirect changed upstream geometry: {key}")
output = root / "dist/culling-rays-integration.json"
output.write_text(json.dumps({"schema": 1, "platform": platform.platform(), "architecture": platform.machine(),
"minecraft": lab.VERSION, "entity_culling": "1.11.2", "original_mod_sha256": original_sha256, "results": results,
"notes": ["Actual upstream culling methods inside Fabric; private fixture invokers do not enter production packs.",
"Two interleaved instances and several occluder patterns; matching boolean and query digests.",
"Signed zero, tiny/large values, infinities and NaN are exercised directly in ray intersection.",
"Unchanged input vectors, independent instance scratch and upstream arithmetic values are checked.",
"Allocation and CPU are single warmed caller-loop observations; JIT folding can vary.",
"Not a game FPS, visual-equivalence proof, whole-game RAM or Mac GPU benchmark."]}, indent=2) + "\n")
print(f"Applied culling scratch checks passed: {output}")
if __name__ == "__main__":
main()
-87
View File
@@ -1,87 +0,0 @@
#!/usr/bin/env python3
"""Exercise applied DH dispatch hooks in isolated Fabric clients; no world or account needed."""
import argparse
import json
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
from .test_culling_rays import run_fixture
except ImportError:
import build_mod
import build_pack
from test_culling_rays import run_fixture
def failure_summary(run, report_count):
"""Publish only exit/count and bounded Java type names, never log messages."""
types = []
pattern = r"(?:Caused by:|Exception in thread \"[^\"]*\")\s+([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+)(?=[:\s]|$)"
for kind in re.findall(pattern, run.stdout, flags=re.ASCII):
if len(kind) <= 200 and kind not in types:
types.append(kind)
if len(types) == 8:
break
return {"exit_code": run.returncode, "result_count": report_count, "java_exception_types": types}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--native-display", action="store_true", help="Use the existing display instead of Linux Xvfb")
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_dispatch_fixture()
version = build_pack.read_lock()["pack_version"]
mod = root / "dist" / f"horizon-{version}.jar"
results = []
for enabled in [False, True]:
instance = root / ".local/runtime" / ("dispatch-fixture-patched" if enabled else "dispatch-fixture-upstream")
build_pack.prepare_instance("dispatch-retry", instance, mod)
shutil.copy2(fixture, instance / "mods/dispatch-fixture.jar")
(instance / "config/horizon-dispatch-retry.properties").write_text(f"enabled={str(enabled).lower()}\n")
command = [sys.executable, str(root / "tools/runtime.py"), "demo", "--instance", str(instance),
"--heap", "3G", "--compact-headers"]
if platform.system() == "Linux" and not args.native_display:
command = ["xvfb-run", "-a", *command]
environment = os.environ.copy()
environment["_JAVA_OPTIONS"] = "-Dhorizon.fixture.exit=true"
try:
run = run_fixture(command, instance, environment)
except RuntimeError:
print("HORIZON_FIXTURE_FAILURE " + json.dumps({"fixture": "dispatch", "completed": False}), flush=True)
raise RuntimeError("Dispatch fixture did not complete; full diagnostics remain private") from None
marker = "HORIZON_DISPATCH_RESULT "
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(reports) != 1:
print("HORIZON_FIXTURE_FAILURE " + json.dumps(failure_summary(run, len(reports))), flush=True)
raise RuntimeError("Dispatch fixture failed; full diagnostics remain in the private fixture.log")
report = reports[0]
if report["enabled"] != enabled or report["tasks_completed"] != 2 or report["occupied_slots"] != 0:
raise AssertionError("Fixture outcome did not match the selected hook")
results.append(report)
print(json.dumps(report), flush=True)
output = root / "dist/dispatch-integration.json"
output.write_text(json.dumps({"schema": 1, "platform": platform.platform(), "architecture": platform.machine(),
"minecraft": lab.VERSION, "distant_horizons": "3.3.4", "results": results,
"notes": ["Synthetic full physical worker queue; both modes use the actual publisher dispatcher inside Fabric.",
"Allocation and CPU measure the submission caller only; retry scheduler activity is excluded.",
"Upstream keeps the caller blocked for the requested 200 ms observation window; patched returns earlier.",
"Both modes verify exact task counts, recovered occupied slots and fixture worker shutdown.",
"Not a game FPS, terrain completion, whole-game RAM, or hardware compatibility benchmark."]}, indent=2) + "\n")
print(f"Applied-hook integration checks passed: {output}")
if __name__ == "__main__":
main()
-77
View File
@@ -1,77 +0,0 @@
#!/usr/bin/env python3
"""Compare actual terrain quad geometry and allocation with discarded-quad reuse."""
import argparse
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
except ImportError:
import build_mod
import build_pack
try:
from .test_culling_rays import run_fixture
except ImportError:
from test_culling_rays import run_fixture
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--native-display", action="store_true")
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_integration_fixture("quad-reuse", "dev.horizonlab.dispatch.QuadReuseIntegration")
mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar"
original_sha256 = hashlib.sha256(mod.read_bytes()).hexdigest()
results = []
for enabled in [False, True]:
instance = root / ".local/runtime" / ("quad-reuse-fixture-patched" if enabled else "quad-reuse-fixture-upstream")
build_pack.prepare_instance("m2-balanced", instance, mod)
if hashlib.sha256((instance / "mods" / mod.name).read_bytes()).hexdigest() != original_sha256:
raise AssertionError("Fixture runtime mod does not match the intended build")
shutil.copy2(fixture, instance / "mods/quad-reuse-fixture.jar")
(instance / "config/horizon-quad-reuse.properties").write_text(f"enabled={str(enabled).lower()}\n")
command = [sys.executable, str(root / "tools/runtime.py"), "demo", "--instance", str(instance), "--heap", "3G", "--compact-headers"]
if platform.system() == "Linux" and not args.native_display:
command = ["xvfb-run", "-a", *command]
environment = os.environ.copy()
environment["_JAVA_OPTIONS"] = "-Dhorizon.fixture.exit=true"
run = run_fixture(command, instance, environment)
marker = "HORIZON_QUAD_RESULT "
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(reports) != 1:
raise RuntimeError(f"Quad reuse fixture failed; inspect {instance / 'fixture.log'}")
report = reports[0]
if report["enabled"] != enabled or report["input_faces"] != 55296 or report["measured_faces"] != 3072000 or report["thread_workers"] != 4 or not report["applied_hook_checked"]:
raise AssertionError("Applied quad reuse fixture did not complete its geometry checks")
results.append(report)
print(json.dumps(report), flush=True)
for key in ["geometry_digest", "geometry_quads", "input_faces", "checksum", "thread_geometry_digest"]:
if results[0][key] != results[1][key]:
raise AssertionError(f"Quad reuse changed upstream geometry: {key}")
output = root / "dist/quad-reuse-integration.json"
output.write_text(json.dumps({"schema": 1, "platform": platform.platform(), "architecture": platform.machine(),
"minecraft": lab.VERSION, "distant_horizons": "3.3.4", "original_mod_sha256": original_sha256, "results": results,
"notes": ["Actual publisher quad builder inside Fabric with generated faces and lighting/material values.",
"Opaque/translucent geometry, pooled error flags and every retained quad field match before and after upstream merging.",
"Fresh allocations reuse at most one discarded successful-premerge quad; existing pool selection stays upstream.",
"Three sequential warmed caller-loop observations are not independent forks; compilation can vary.",
"Allocation reduction is not retained RAM, game FPS or a Mac GPU benchmark."]}, indent=2) + "\n")
print(f"Applied terrain quad reuse checks passed: {output}")
if __name__ == "__main__":
main()
-99
View File
@@ -1,99 +0,0 @@
#!/usr/bin/env python3
"""Measure shallow quad-reuse retention in private Fabric clients, not whole-game RAM."""
import argparse
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
import zipfile
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
from .test_culling_rays import run_fixture
except ImportError:
import build_mod
import build_pack
from test_culling_rays import run_fixture
def build_agent():
output = build_mod.BUILD / "size-agent"
classes = output / "classes"
classes.mkdir(parents=True, exist_ok=True)
source = build_mod.SOURCE / "test/java/dev/horizonlab/metrics/ObjectSizeAgent.java"
subprocess.run(["javac", "--release", "25", "-d", str(classes), str(source)], check=True)
agent = output / "size-agent.jar"
with zipfile.ZipFile(agent, "w", compression=zipfile.ZIP_DEFLATED) as archive:
archive.writestr("META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n"
"Premain-Class: dev.horizonlab.metrics.ObjectSizeAgent\n\n")
for path in sorted(classes.rglob("*.class")):
archive.write(path, path.relative_to(classes).as_posix())
return agent
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--native-display", action="store_true")
args = parser.parse_args()
root = build_pack.ROOT
agent = build_agent()
fixture = build_mod.build_integration_fixture("quad-size", "dev.horizonlab.dispatch.QuadSizeIntegration")
mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar"
mod_hash = hashlib.sha256(mod.read_bytes()).hexdigest()
results = []
for headers in [False, True]:
for enabled in [False, True]:
instance = root / ".local/runtime" / f"quad-size-{headers}-{enabled}"
build_pack.prepare_instance("m2-balanced", instance, mod)
assert hashlib.sha256((instance / "mods" / mod.name).read_bytes()).hexdigest() == mod_hash
shutil.copy2(fixture, instance / "mods/quad-size-fixture.jar")
(instance / "config/horizon-quad-reuse.properties").write_text(f"enabled={str(enabled).lower()}\n")
environment = os.environ.copy()
header_option = "-XX:" + ("+" if headers else "-") + "UseCompactObjectHeaders"
if '"' in str(agent) or "\n" in str(agent):
raise ValueError("Instrumentation agent path contains an unsupported quote or newline")
environment["_JAVA_OPTIONS"] = f'-javaagent:"{agent}" {header_option} -Dhorizon.fixture.exit=true'
command = [sys.executable, str(root / "tools/runtime.py"), "demo", "--instance", str(instance), "--heap", "3G"]
if platform.system() == "Linux" and not args.native_display:
command = ["xvfb-run", "-a", *command]
run = run_fixture(command, instance, environment)
marker = "HORIZON_SIZE_RESULT "
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(reports) != 1:
raise RuntimeError("Private quad-size fixture failed; diagnostics remain in its fixture.log")
report = reports[0]
if report["enabled"] != enabled or report["compact_headers"] != headers or report["geometry_quads"] != 1:
raise AssertionError("Size probe did not measure the requested hook/header combination")
if bool(report["pending_scratch_shallow_bytes"]) != enabled:
raise AssertionError("Size probe retained an unexpected scratch object")
results.append(report)
print(json.dumps(report), flush=True)
differences = []
for control, candidate in zip(results[::2], results[1::2]):
differences.append({"compact_headers": candidate["compact_headers"],
"additional_builder_shallow_bytes": candidate["builder_shallow_bytes"] - control["builder_shallow_bytes"],
"additional_builder_and_scratch_bytes": candidate["builder_shallow_bytes"] - control["builder_shallow_bytes"] + candidate["pending_scratch_shallow_bytes"]})
output = root / "dist/quad-size-integration.json"
output.write_text(json.dumps({"schema": 1, "platform": platform.platform(), "architecture": platform.machine(),
"minecraft": lab.VERSION, "distant_horizons": "3.3.4", "original_mod_sha256": mod_hash,
"results": results, "differences": differences,
"notes": ["Instrumentation.getObjectSize measures shallow object sizes inside real applied Fabric clients.",
"Four adjacent north-facing quads premerge to one retained geometry quad in each combination.",
"Builder plus pending scratch difference excludes referenced lists, existing pools and every other game object.",
"Object alignment/header/compressed-reference settings can differ on other JVMs or architectures.",
"Not deep heap, GC residency, whole-game RSS/unified RAM, FPS or Apple Silicon performance.",
"The agent and fixture are private test binaries excluded from playable packs."]}, indent=2) + "\n")
print(f"Quad object-size observations: {output}")
if __name__ == "__main__":
main()
-75
View File
@@ -1,75 +0,0 @@
#!/usr/bin/env python3
"""Check recording-start graphics context in a real integrated-server report."""
import argparse
import hashlib
import json
import os
import platform
import shutil
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
from .test_culling_rays import run_fixture
except ImportError:
import build_mod, build_pack
from test_culling_rays import run_fixture
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--native-display', action='store_true')
parser.add_argument('--backend', choices=['opengl', 'vulkan'], help='Require this observed backend; default accepts the game-selected backend')
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_integration_fixture('server-graphics',
'dev.horizonlab.metrics.ServerGraphicsIntegration', fixture_dependencies={})
version = build_pack.read_lock()['pack_version']
mod = root / 'dist' / f'horizon-{version}.jar'
digest = hashlib.sha256(mod.read_bytes()).hexdigest()
instance = root / '.local/runtime' / ('server-graphics-' + (args.backend or 'default'))
if instance.exists():
raise RuntimeError('Use a fresh private fixture directory; existing worlds and reports are not overwritten')
build_pack.prepare_instance('core-performance', instance, mod)
if args.backend:
options = instance / 'options.txt'
import re
text, count = re.subn(r'^preferredGraphicsBackend:.*$', 'preferredGraphicsBackend:' + json.dumps(args.backend), options.read_text(), flags=re.MULTILINE)
if count != 1:
raise AssertionError('Expected one backend preference')
options.write_text(text)
if hashlib.sha256((instance / 'mods' / mod.name).read_bytes()).hexdigest() != digest:
raise AssertionError('Runtime mod differs from intended build')
shutil.copy2(fixture, instance / 'mods/server-graphics-fixture.jar')
command = [sys.executable, str(root / 'tools/runtime.py'), 'demo', '--instance', str(instance), '--heap', '3G', '--compact-headers']
if platform.system() == 'Linux' and not args.native_display:
command = ['xvfb-run', '-a', *command]
run = run_fixture(command, instance, os.environ.copy())
marker = 'HORIZON_SERVER_GRAPHICS_RESULT '
results = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(results) != 1:
raise RuntimeError('Integrated-server graphics fixture failed; inspect its private runtime log')
result = results[0]
if result.get('server_runtime_kind') != 'integrated' or result.get('client_graphics_capture_status') != 'captured_at_recording_start':
raise AssertionError('Integrated graphics were not captured')
if args.backend and result.get('graphics_backend', '').lower() != args.backend:
raise AssertionError('Observed graphics backend differs from the requested experiment')
if not (instance / 'saves/Demo_World/level.dat').is_file():
raise AssertionError('Disposable world was not saved')
report = {'schema': 1, 'platform': platform.platform(), 'architecture': platform.machine(),
'minecraft': lab.VERSION, 'original_mod_sha256': digest, 'launcher_exit_code': run.returncode,
'requested_backend': args.backend or 'pack_default', 'result': result, 'limits': ['Short report-context check, not FPS or physical M2 performance.',
'Graphics context is captured at recording start, not continuously monitored.',
'World files and full logs remain private.']}
output = root / 'dist/server-graphics-smoke.json'
output.write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report), flush=True)
if __name__ == '__main__':
main()
-77
View File
@@ -1,77 +0,0 @@
#!/usr/bin/env python3
"""Compare the actual full-data lookup with original and equivalent position arithmetic."""
import argparse
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
except ImportError:
import build_mod
import build_pack
try:
from .test_culling_rays import run_fixture
except ImportError:
from test_culling_rays import run_fixture
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--native-display", action="store_true")
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_integration_fixture("terrain-position", "dev.horizonlab.dispatch.PositionIntegration")
mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar"
original_sha256 = hashlib.sha256(mod.read_bytes()).hexdigest()
results = []
for enabled in [False, True]:
instance = root / ".local/runtime" / ("terrain-position-fixture-patched" if enabled else "terrain-position-fixture-upstream")
build_pack.prepare_instance("m2-balanced", instance, mod)
if hashlib.sha256((instance / "mods" / mod.name).read_bytes()).hexdigest() != original_sha256:
raise AssertionError("Fixture runtime mod does not match the intended build")
shutil.copy2(fixture, instance / "mods/terrain-position-fixture.jar")
(instance / "config/horizon-terrain-position.properties").write_text(f"enabled={str(enabled).lower()}\n")
command = [sys.executable, str(root / "tools/runtime.py"), "demo", "--instance", str(instance), "--heap", "3G", "--compact-headers"]
if platform.system() == "Linux" and not args.native_display:
command = ["xvfb-run", "-a", *command]
environment = os.environ.copy()
environment["_JAVA_OPTIONS"] = "-Dhorizon.fixture.exit=true"
run = run_fixture(command, instance, environment)
marker = "HORIZON_POSITION_RESULT "
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(reports) != 1:
raise RuntimeError(f"Terrain position fixture failed; inspect {instance / 'fixture.log'}")
report = reports[0]
if report["enabled"] != enabled or report["owners"] != 30 or report["queries"] != 491520 or not report["data_unchanged"] or not report["applied_hook_checked"]:
raise AssertionError("Applied position fixture did not complete its lookup checks")
results.append(report)
print(json.dumps(report), flush=True)
for key in ["lookup_digest", "data_fingerprint", "nonzero", "checksum"]:
if results[0][key] != results[1][key]:
raise AssertionError(f"Position redirect changed upstream lookup: {key}")
output = root / "dist/terrain-position-integration.json"
output.write_text(json.dumps({"schema": 1, "platform": platform.platform(), "architecture": platform.machine(),
"minecraft": lab.VERSION, "distant_horizons": "3.3.4", "original_mod_sha256": original_sha256, "results": results,
"notes": ["Actual public full-data lookup inside Fabric with generated numeric column data.",
"Thirty owners span positive/negative origins and six detail levels; output digests and source fingerprints match.",
"The actual redirect method is checked in each mode; source column data remains unchanged.",
"Three sequential warmed caller-loop observations are not independent forks; JIT compilation can vary.",
"Not whole-game FPS/RAM, rendered-pixel equivalence or a Mac GPU benchmark."]}, indent=2) + "\n")
print(f"Applied terrain position checks passed: {output}")
if __name__ == "__main__":
main()
-71
View File
@@ -1,71 +0,0 @@
#!/usr/bin/env python3
"""Exercise interruptible blending reads on an actual transformed Minecraft IOWorker."""
import argparse
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
except ImportError:
import build_mod
import build_pack
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--native-display", action="store_true")
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_integration_fixture("terrain-read", "dev.horizonlab.dispatch.TerrainReadIntegration")
mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar"
original_sha256 = hashlib.sha256(mod.read_bytes()).hexdigest()
results = []
for enabled in [False, True]:
instance = root / ".local/runtime" / ("terrain-read-fixture-patched" if enabled else "terrain-read-fixture-upstream")
build_pack.prepare_instance("m2-balanced", instance, mod)
if hashlib.sha256((instance / "mods" / mod.name).read_bytes()).hexdigest() != original_sha256:
raise AssertionError("Runtime mod does not match the intended build")
shutil.copy2(fixture, instance / "mods/terrain-read-fixture.jar")
(instance / "config/horizon-terrain-read-wait.properties").write_text(f"enabled={str(enabled).lower()}\n")
command = [sys.executable, str(root / "tools/runtime.py"), "demo", "--instance", str(instance), "--heap", "3G", "--compact-headers"]
if platform.system() == "Linux" and not args.native_display:
command = ["xvfb-run", "-a", *command]
environment = os.environ.copy()
environment["_JAVA_OPTIONS"] = "-Dhorizon.fixture.exit=true"
run = subprocess.run(command, cwd=root, env=environment, text=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, timeout=240)
(instance / "fixture.log").write_text(run.stdout)
marker = "HORIZON_TERRAIN_READ_RESULT "
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(reports) != 1:
raise RuntimeError(f"Terrain read fixture failed; inspect {instance / 'fixture.log'}")
report = reports[0]
if report["enabled"] != enabled or not all(report.get(key) for key in [
"applied_io_worker_checked", "ordinary_join_checked", "shared_future_preserved",
"exception_identity_checked", "completed_interrupt_checked", "cancelled_completion_checked", "preinterrupted_pending_checked"]):
raise AssertionError("Applied terrain read hook did not preserve the required outcomes")
results.append(report)
print(json.dumps(report), flush=True)
output = root / "dist/terrain-read-integration.json"
output.write_text(json.dumps({"schema": 1, "platform": platform.platform(), "architecture": platform.machine(),
"minecraft": lab.VERSION, "distant_horizons": "3.3.4", "original_mod_sha256": original_sha256, "results": results,
"notes": ["Actual game IOWorker under Fabric, with controlled cached blending-read futures.",
"DH worker interruption releases only its waiter; the shared future remains consumable.",
"Ordinary callers retain join behavior; completed values, cancellation and exception identity are checked.",
"This is a shutdown correctness fixture, not an FPS or world-generation throughput benchmark."]}, indent=2) + "\n")
print(f"Applied terrain read checks passed: {output}")
if __name__ == "__main__":
main()
-68
View File
@@ -1,68 +0,0 @@
#!/usr/bin/env python3
"""Check actual DH tick transitions and allocation with the optional membership hook off/on."""
import argparse
import json
import os
import platform
import shutil
import subprocess
import sys
try:
from . import lab
except ImportError:
import lab
try:
from . import build_mod, build_pack
except ImportError:
import build_mod
import build_pack
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--native-display", action="store_true")
args = parser.parse_args()
root = build_pack.ROOT
fixture = build_mod.build_tick_dedup_fixture()
mod = root / "dist" / f"horizon-{build_pack.read_lock()['pack_version']}.jar"
results = []
for enabled in [False, True]:
instance = root / ".local/runtime" / ("tick-dedup-fixture-patched" if enabled else "tick-dedup-fixture-upstream")
build_pack.prepare_instance("m2-balanced", instance, mod)
shutil.copy2(fixture, instance / "mods/tick-dedup-fixture.jar")
(instance / "config/horizon-tick-dedup.properties").write_text(f"enabled={str(enabled).lower()}\n")
command = [sys.executable, str(root / "tools/runtime.py"), "demo", "--instance", str(instance), "--heap", "3G", "--compact-headers"]
if platform.system() == "Linux" and not args.native_display:
command = ["xvfb-run", "-a", *command]
environment = os.environ.copy()
environment["_JAVA_OPTIONS"] = "-Dhorizon.fixture.exit=true"
run = subprocess.run(command, cwd=root, env=environment, text=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, timeout=240)
(instance / "fixture.log").write_text(run.stdout)
marker = "HORIZON_TICK_DEDUP_RESULT "
reports = [json.loads(line.split(marker, 1)[1]) for line in run.stdout.splitlines() if marker in line]
if run.returncode or len(reports) != 1:
raise RuntimeError(f"Tick dedup fixture failed; inspect {instance / 'fixture.log'}")
report = reports[0]
if report["enabled"] != enabled or report["verified_transitions"] != 6000 or report["checksum"] != 10240000:
raise AssertionError("Applied hook or semantic outcome did not match")
results.append(report)
print(json.dumps(report), flush=True)
if results[0]["allocated_bytes"] <= 0 or results[1]["allocated_bytes"] >= results[0]["allocated_bytes"] / 20:
raise AssertionError("Membership hook did not remove repeated entry allocation")
output = root / "dist/tick-dedup-integration.json"
output.write_text(json.dumps({"schema": 1, "platform": platform.platform(), "architecture": platform.machine(),
"minecraft": lab.VERSION, "distant_horizons": "3.3.4", "results": results,
"notes": ["Actual publisher tick holder under Fabric, warmed with preallocated nodes and a reused action list.",
"Checks duplicate/null membership, enable/disable precedence, published iteration order and clear boundaries.",
"Only private membership checks change; action collections and traversal remain upstream.",
"CPU and allocation measure the calling thread in one isolated loop; no statistical speed claim.",
"Not a game FPS, visible terrain completion, whole-game RAM or Mac GPU benchmark."]}, indent=2) + "\n")
print(f"Applied tick membership checks passed: {output}")
if __name__ == "__main__":
main()