use bao_engine::context::JsContext;
use bao_engine::memory_stats::collect_runtime_stats;
fn test_01_non_zero_metering(cx: &mut JsContext) {
cx.eval(
"globalThis.__memstats_sink = []; \
for (let i = 0; i < 30000; i++) { __memstats_sink.push('payload-' + i + '-' + (i * 7)); }",
"memstats_load.js",
)
.expect("heap-load eval must succeed");
let stats = unsafe { collect_runtime_stats(cx.raw_cx()) }
.expect("native CollectRuntimeStats must succeed on a live context");
assert!(
stats.gc_heap_chunk_total > 0,
"gc_heap_chunk_total must be non-zero, got {:?}",
stats
);
assert!(stats.gc_heap_gc_things > 0, "gc_heap_gc_things must be non-zero");
assert!(
stats.zone_live_gc_things > 0,
"zone_live_gc_things must be non-zero"
);
assert!(
stats.realm_live_gc_things > 0,
"realm_live_gc_things must be non-zero"
);
assert!(stats.zone_count >= 1, "zone_count must be >= 1");
assert!(stats.realm_count >= 1, "realm_count must be >= 1");
assert!(stats.servo_gc_heap_used > 0, "servo_gc_heap_used must be non-zero");
assert!(stats.servo_malloc_heap > 0, "servo_malloc_heap must be non-zero");
}
fn test_02_live_gc_things_identity(ctx: &mut JsContext) {
let stats = unsafe { collect_runtime_stats(ctx.raw_cx()) }
.expect("second collection on the same context must succeed");
assert_eq!(
stats.gc_heap_gc_things,
stats.live_gc_things_parts_sum(),
"SM totals identity: gcHeapGCThings == zone + realm live GC things"
);
}
fn test_03_gc_heap_chunk_consistency(ctx: &mut JsContext) {
let stats = unsafe { collect_runtime_stats(ctx.raw_cx()) }
.expect("third collection on the same context must succeed");
let servo_parts = stats.servo_gc_heap_decommitted
+ stats.servo_gc_heap_unused
+ stats.servo_gc_heap_admin
+ stats.gc_heap_gc_things;
assert!(
stats.gc_heap_chunk_total >= servo_parts,
"gc_heap_chunk_total ({}) must cover the GC-heap parts ({})",
stats.gc_heap_chunk_total,
servo_parts
);
assert_eq!(
stats.servo_gc_heap_used, stats.gc_heap_gc_things,
"servo_gc_heap_used must equal gc_heap_gc_things (same live things, two rollups)"
);
}
#[test]
fn test_engine_memory_stats_native_collect() {
let mut ctx = JsContext::for_test().expect("Failed to create JsContext");
test_01_non_zero_metering(&mut ctx);
test_02_live_gc_things_identity(&mut ctx);
test_03_gc_heap_chunk_consistency(&mut ctx);
bao_engine::context::JsContext::shutdown_thread_sm();
}