✓
Passing This code compiles and runs correctly.
Code
// Pins the runtime profiler end-to-end: [profile]import + --profile produces
// a valid Chrome Tracing file capturing the program's real transitions, while
// the profiler's own write-* events stay invisible (opaque taps).
~import std/io
~[profile]import std/profiler
~pub tor get-number {} -> i32
~proc get-number|zig {
return 42;
}
~get-number(): n |> std/io:print.ln("Got number: {{ n:d }}")
Supporting Files
UnsupportedConstruct
~proc get-number|cs {
return 42;
}Actual · Zig
✓ passGot number: 42
Actual · C#
✗ UnsupportedConstructExpected output
✓ Zig✗ C#Got number: 42
Emitted Zig source
// Access compiler flags via the per-user compiler_env module
const CompilerEnv = @import("compiler_env").CompilerEnv;
pub const panic = if (@import("builtin").mode == .Debug)
@import("std").debug.FullPanic(@import("std").debug.defaultPanic)
else
@import("std").debug.simple_panic;
const __koru_bare = struct {
extern fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
extern fn free(ptr: ?*anyopaque) void;
fn bareAlloc(_: *anyopaque, len: usize, alignment: @import("std").mem.Alignment, _: usize) ?[*]u8 {
var p: ?*anyopaque = null;
const a = @max(alignment.toByteUnits(), @sizeOf(usize));
if (posix_memalign(&p, a, len) != 0) return null;
return @ptrCast(p);
}
fn bareResize(_: *anyopaque, _: []u8, _: @import("std").mem.Alignment, _: usize, _: usize) bool { return false; }
fn bareRemap(_: *anyopaque, _: []u8, _: @import("std").mem.Alignment, _: usize, _: usize) ?[*]u8 { return null; }
fn bareFree(_: *anyopaque, memory: []u8, _: @import("std").mem.Alignment, _: usize) void { free(@ptrCast(memory.ptr)); }
const vtable = @import("std").mem.Allocator.VTable{ .alloc = bareAlloc, .resize = bareResize, .remap = bareRemap, .free = bareFree };
const allocator = @import("std").mem.Allocator{ .ptr = undefined, .vtable = &vtable };
};
const __koru_backing = if (@import("builtin").link_libc) @import("std").heap.c_allocator else if (@import("builtin").os.tag == .freestanding and !@import("builtin").cpu.arch.isWasm()) __koru_bare.allocator else @import("std").heap.page_allocator;
var __koru_leak_count: @import("std").atomic.Value(usize) = .init(0);
var __koru_par_tasks: @import("std").atomic.Value(usize) = .init(0);
const __koru_par_CAP: usize = 128;
threadlocal var __koru_par_depth: usize = 0;
const __koru_par_DEPTH_CAP: usize = 7;
var __koru_par_pool: @import("std").Thread.Pool = undefined;
var __koru_par_pool_ready: bool = false;
var __koru_par_pool_mtx: @import("std").Thread.Mutex = .{};
fn __koru_par_pool_ensure() *@import("std").Thread.Pool {
__koru_par_pool_mtx.lock();
defer __koru_par_pool_mtx.unlock();
if (!__koru_par_pool_ready) {
@import("std").Thread.Pool.init(&__koru_par_pool, .{ .allocator = @import("std").heap.smp_allocator }) catch @panic("koru: thread pool init failed");
__koru_par_pool_ready = true;
}
return &__koru_par_pool;
}
fn __koru_alloc(ctx: *anyopaque, len: usize, alignment: @import("std").mem.Alignment, ret_addr: usize) ?[*]u8 {
_ = ctx;
const r = __koru_backing.rawAlloc(len, alignment, ret_addr);
if (comptime @import("builtin").mode == .Debug) {
if (r != null) _ = __koru_leak_count.fetchAdd(1, .monotonic);
}
return r;
}
fn __koru_resize(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, new_len: usize, ret_addr: usize) bool {
_ = ctx;
return __koru_backing.rawResize(memory, alignment, new_len, ret_addr);
}
fn __koru_remap(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
_ = ctx;
return __koru_backing.rawRemap(memory, alignment, new_len, ret_addr);
}
fn __koru_free(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, ret_addr: usize) void {
_ = ctx;
__koru_backing.rawFree(memory, alignment, ret_addr);
if (comptime @import("builtin").mode == .Debug) {
_ = __koru_leak_count.fetchSub(1, .monotonic);
}
}
const __koru_vtable = @import("std").mem.Allocator.VTable{ .alloc = __koru_alloc, .resize = __koru_resize, .remap = __koru_remap, .free = __koru_free };
pub fn koru_allocator() @import("std").mem.Allocator {
return .{ .ptr = undefined, .vtable = &__koru_vtable };
}
pub inline fn __koru_intcast(comptime T: type, x: anytype) T {
if (comptime (@import("builtin").mode == .Debug or @import("builtin").mode == .ReleaseSafe))
return @as(T, @intCast(x));
const dst = @typeInfo(T);
const src = @typeInfo(@TypeOf(x));
if (comptime (dst == .int and src == .int and dst.int.bits == src.int.bits and dst.int.signedness != src.int.signedness))
return @as(T, @bitCast(x));
return @as(T, @intCast(x));
}
fn __KoruPadI(comptime T: type) type {
const V = switch (@typeInfo(T)) { .comptime_int => i64, .comptime_float => f64, else => T };
return struct {
v: V,
width: usize,
pub fn format(self: @This(), w: *@import("std").Io.Writer) @import("std").Io.Writer.Error!void {
const rendered = @import("std").fmt.count("{d}", .{self.v});
const pad = self.width -| rendered;
for (0..pad) |_| try w.writeByte(' ');
try w.print("{d}", .{self.v});
}
};
}
pub fn __koru_pad_i(width: usize, value: anytype) __KoruPadI(@TypeOf(value)) {
return .{ .v = value, .width = width };
}
pub fn koru_leak_check() void {
if (comptime @import("builtin").mode != .Debug) return;
if (__koru_leak_count.load(.acquire) == 0) return;
if (comptime @import("builtin").target.os.tag == .freestanding) {
if (comptime @import("builtin").cpu.arch == .wasm32 or @import("builtin").cpu.arch == .wasm64) {
@panic("KORU LEAK CHECK FAILED: the produced program leaked");
} else {
const __klc = struct { extern var stdout: ?*anyopaque; extern fn fputs(__s: [*:0]const u8, __st: ?*anyopaque) c_int; };
var __lb: [128]u8 = undefined;
const __lm = "KORU LEAK CHECK FAILED: allocations still outstanding at end of run: ";
@memcpy(__lb[0..__lm.len], __lm);
var __ln: usize = __lm.len;
var __lv = __koru_leak_count.load(.acquire);
var __ld: [20]u8 = undefined;
var __lk: usize = 0;
while (__lv > 0) : (__lk += 1) { __ld[__lk] = @intCast('0' + __lv % 10); __lv /= 10; }
for (0..__lk) |__li| { __lb[__ln] = __ld[__lk - 1 - __li]; __ln += 1; }
__lb[__ln] = '\n'; __ln += 1; __lb[__ln] = 0;
_ = __klc.fputs(@as([*:0]const u8, @ptrCast(&__lb)), __klc.stdout);
@trap();
}
} else {
@import("std").debug.print("KORU LEAK CHECK FAILED: the produced program leaked (trace above)\n", .{});
@import("std").process.exit(1);
}
}
pub const main_module = struct {
pub const get_number_event = struct {
pub const Input = struct {
};
pub const Output = i32;
pub fn handler(__koru_event_input: @This().Input) @This().Output {
// >>> PROC: get_number [tests/regression/300_ADVANCED_FEATURES/360_TAPS_OBSERVERS/510_profiler_end_to_end/input.kz:10]
_ = &__koru_event_input;
return 42;
}
};
// >>> FLOW: tests/regression/300_ADVANCED_FEATURES/360_TAPS_OBSERVERS/510_profiler_end_to_end/input.kz:14 ~input:get_number()
pub fn flow0() void {
const n = main_module.get_number_event.handler(.{ });
{
const _profile_e2c2f698566c0fc1_2 = taps.Profile{
.source = "input:get-number",
.destination = "std.io:print.ln",
.branch = "result",
.timestamp_ns = __koru_std.time.nanoTimestamp(),
};
_ = &_profile_e2c2f698566c0fc1_2;
const result_1 = koru_std.koru_profiler.write_event_event.handler(.{ .source = _profile_e2c2f698566c0fc1_2.source, .timestamp_ns = _profile_e2c2f698566c0fc1_2.timestamp_ns });
_ = &result_1;
(struct { fn __kout(__fd: i32, __b: []const u8) void { if (@import("builtin").os.tag == .freestanding) { const __kc = struct { extern var stdout: ?*anyopaque; extern var stderr: ?*anyopaque; extern fn fputs(__s: [*:0]const u8, __st: ?*anyopaque) c_int; }; var __kt: [4096]u8 = undefined; for (0..(__b.len + __kt.len - 2) / (__kt.len - 1)) |__ki| { const __kn = @min(__kt.len - 1, __b.len - __ki * (__kt.len - 1)); @memcpy(__kt[0..__kn], __b[__ki * (__kt.len - 1)..][0..__kn]); __kt[__kn] = 0; @import("std").mem.doNotOptimizeAway(__kc.fputs(@as([*:0]const u8, @ptrCast(&__kt)), if (__fd == 2) __kc.stderr else __kc.stdout)); } } else { @import("std").mem.doNotOptimizeAway(@import("std").posix.write(__fd, __b) catch @as(usize, 0)); } } fn __kw(comptime __f: []const u8, __a: anytype) void { var __kb: [65536]u8 = undefined; const __ks = @import("std").fmt.bufPrint(&__kb, __f, __a) catch __kb[0..0]; __kout(1, __ks); } }).__kw("Got number: {d}\n", .{n});
{
const _profile_e2c2f698566c0fc1_3 = taps.Profile{
.source = "std.io:print.ln",
.destination = null,
.branch = "__void",
.timestamp_ns = __koru_std.time.nanoTimestamp(),
};
_ = &_profile_e2c2f698566c0fc1_3;
const result_2 = koru_std.koru_profiler.write_event_event.handler(.{ .source = _profile_e2c2f698566c0fc1_3.source, .timestamp_ns = _profile_e2c2f698566c0fc1_3.timestamp_ns });
_ = &result_2;
}
}
}
pub fn koru_start_flow() void {
const result_0 = koru_koru.start_event.handler(.{ });
const result_0_done = result_0.done;
_ = &result_0_done;
const result_1 = koru_std.koru_profiler.write_header_event.handler(.{ });
_ = &result_1;
}
pub fn koru_end_flow() void {
const result_0 = koru_koru.end_event.handler(.{ });
const result_0_done = result_0.done;
_ = &result_0_done;
const result_1 = koru_std.koru_profiler.write_footer_event.handler(.{ });
_ = &result_1;
}
};
pub const koru_std = struct {
pub const koru_profiler = struct {
const std = @import("std");
var profile_file: ?std.fs.File = null;
var first_event: bool = true;
var previous_timestamp_ns: i128 = 0;
var previous_event_name: []const u8 = "";
var profiler_finished: bool = false; // Prevents write-event from creating new file after footer
var program_start_ns: i128 = 0; // Envelope open (koru:start anchor); footer synthesizes the span from it
pub const write_header_event = struct {
pub const Input = struct {
};
pub const Output = void;
pub fn handler(__koru_event_input: @This().Input) @This().Output {
// >>> PROC: write_header [/Users/larsde/src/koru/koru_std/profiler.kz:40]
_ = &__koru_event_input;
// Only create file if not already created by write-event
// (write-event runs BEFORE write-header due to universal tap ordering)
if (profile_file == null) {
profile_file = std.fs.cwd().createFile(std.posix.getenv("KORU_PROFILE_PATH") orelse "/tmp/koru_profile.json", .{}) catch {
std.debug.print("ERROR: Failed to create profile file\n", .{});
return;
};
// Write Chrome Tracing JSON header
const header = "{\"traceEvents\":[\n";
profile_file.?.writeAll(header) catch {
std.debug.print("ERROR: Failed to write profile header\n", .{});
};
}
// Initialize profiler state for new trace (only if not already started)
// Don't reset if previous_timestamp_ns is set - that means we already buffered an tor
// (the universal tap wraps koru:start -> done BEFORE write-header fires)
if (previous_timestamp_ns == 0) {
first_event = true;
previous_event_name = "";
}
// Open the program envelope. If a transition was already buffered (the
// auto-create race above), the envelope opens at that earlier timestamp so
// the span always contains its first tor.
program_start_ns = std.time.nanoTimestamp();
if (previous_timestamp_ns != 0 and previous_timestamp_ns < program_start_ns) {
program_start_ns = previous_timestamp_ns;
}
// Name the two lanes (ph:"M" metadata), then drop the koru:start anchor
// (ph:"i" global instant) on the envelope lane.
const file = profile_file orelse return;
var buffer: [1024]u8 = undefined;
var pos: usize = 0;
if (!first_event) {
buffer[pos] = ',';
pos += 1;
buffer[pos] = '\n';
pos += 1;
}
first_event = false;
const start_us = @divFloor(program_start_ns, 1000);
const json = std.fmt.bufPrint(buffer[pos..],
"{{\"name\":\"thread_name\",\"ph\":\"M\",\"pid\":0,\"tid\":0,\"args\":{{\"name\":\"transitions\"}}}},\n" ++
"{{\"name\":\"thread_name\",\"ph\":\"M\",\"pid\":0,\"tid\":1,\"args\":{{\"name\":\"program\"}}}},\n" ++
"{{\"name\":\"koru:start\",\"cat\":\"meta\",\"ph\":\"i\",\"s\":\"g\",\"ts\":{d},\"pid\":0,\"tid\":1}}",
.{start_us}
) catch {
std.debug.print("ERROR: Failed to format envelope anchors\n", .{});
return;
};
pos += json.len;
file.writeAll(buffer[0..pos]) catch {
std.debug.print("ERROR: Failed to write envelope anchors\n", .{});
};
return;
}
};
pub const write_event_event = struct {
pub const Input = struct {
source: []const u8,
timestamp_ns: i128,
};
pub const Output = void;
pub fn handler(__koru_event_input: @This().Input) @This().Output {
// >>> PROC: write_event [/Users/larsde/src/koru/koru_std/profiler.kz:107]
const source = __koru_event_input.source;
const timestamp_ns = __koru_event_input.timestamp_ns;
_ = &source;
_ = ×tamp_ns;
_ = &__koru_event_input;
// Don't create new file after profiler has finished (prevents truncating data)
if (profiler_finished) {
return;
}
// Auto-create file if needed (handles case where universal tap's write-event
// fires BEFORE koru:start tap's write-header)
if (profile_file == null) {
profile_file = std.fs.cwd().createFile(std.posix.getenv("KORU_PROFILE_PATH") orelse "/tmp/koru_profile.json", .{}) catch {
std.debug.print("ERROR: Failed to create profile file in write-event\n", .{});
return;
};
// Write JSON header
const header = "{\"traceEvents\":[\n";
profile_file.?.writeAll(header) catch {
std.debug.print("ERROR: Failed to write profile header\n", .{});
return;
};
first_event = true;
}
const file = profile_file orelse return;
// First tor: just buffer it, don't write yet
if (previous_timestamp_ns == 0) {
previous_timestamp_ns = timestamp_ns;
previous_event_name = source;
return;
}
// We have a previous tor buffered - write it now with duration to current tor
const duration_ns = timestamp_ns - previous_timestamp_ns;
const start_us = @divFloor(previous_timestamp_ns, 1000);
const duration_us = @divFloor(duration_ns, 1000);
// Build JSON manually (fast, no allocations)
var buffer: [8192]u8 = undefined;
var pos: usize = 0;
// Add comma separator if not first tor
if (!first_event) {
buffer[pos] = ',';
pos += 1;
buffer[pos] = '\n';
pos += 1;
}
first_event = false;
// Build JSON: Complete tor (ph: "X") with duration
// Format: {"name":"tor","cat":"transition","ph":"X","ts":start,"dur":duration,"pid":0,"tid":0}
// - ph: "X" = complete tor (shows as horizontal bar with duration)
// - ts: when the PREVIOUS tor fired
// - dur: how long from previous tor until THIS tor
// - name: the PREVIOUS tor name
// This shows "time spent in previous state" and makes all bars visible!
const json = std.fmt.bufPrint(buffer[pos..],
"{{\"name\":\"{s}\",\"cat\":\"transition\",\"ph\":\"X\",\"ts\":{d},\"dur\":{d},\"pid\":0,\"tid\":0}}",
.{previous_event_name, start_us, duration_us}
) catch return;
pos += json.len;
file.writeAll(buffer[0..pos]) catch {
std.debug.print("ERROR: Failed to write profile event\n", .{});
};
// Buffer current tor for next write
previous_timestamp_ns = timestamp_ns;
previous_event_name = source;
return;
}
};
pub const write_footer_event = struct {
pub const Input = struct {
};
pub const Output = void;
pub fn handler(__koru_event_input: @This().Input) @This().Output {
// >>> PROC: write_footer [/Users/larsde/src/koru/koru_std/profiler.kz:182]
_ = &__koru_event_input;
const file = profile_file orelse return;
// Write the final buffered tor (if any) with small duration
if (previous_timestamp_ns != 0) {
var buffer: [8192]u8 = undefined;
var pos: usize = 0;
// Add comma separator if not first tor
if (!first_event) {
buffer[pos] = ',';
pos += 1;
buffer[pos] = '\n';
pos += 1;
}
// Emit final tor with 1 microsecond duration (tiny but visible)
const start_us = @divFloor(previous_timestamp_ns, 1000);
const json = std.fmt.bufPrint(buffer[pos..],
"{{\"name\":\"{s}\",\"cat\":\"transition\",\"ph\":\"X\",\"ts\":{d},\"dur\":1,\"pid\":0,\"tid\":0}}",
.{previous_event_name, start_us}
) catch {
std.debug.print("ERROR: Failed to format final event\n", .{});
return;
};
pos += json.len;
file.writeAll(buffer[0..pos]) catch {
std.debug.print("ERROR: Failed to write final event\n", .{});
};
first_event = false;
}
// Close the program envelope: koru
... [truncated - 24KB total]Emitted C# source
static class main_module {
public static void __koru_stdout_write(dynamic s) => global::System.Console.Out.Write(s);
public static void __koru_stderr_write(dynamic s) => global::System.Console.Error.Write(s);
// The mutable handle carrier — `*String`-style resources are
// `new __KoruBox { data = … }` because C# anonymous types are
// read-only: `s.data = …` (std/string append/clear, handle
// mutation generally) needs a settable member.
public class __KoruBox { public dynamic data; }
// Textification for `{{ … }}` operands: C# bool ToStrings as
// `True` where Koru prints `true`, and the operand's static type
// is unknown at this boundary — a `(x) is bool` inline test would
// be a compile error on statically-typed operands instead. Generic
// on purpose: `dynamic` boxed every value-type operand — measured
// ~1s/10M elements on 012_threat_scanner — while T specializes to
// the operand's own ToString() with no box.
public static string __koru_str<T>(T v) => v is bool b ? (b ? "true" : "false") : v?.ToString();
public static class get_number_event {
public struct Input {
}
public static int handler(Input __koru_input) {
return 42;
return default;
}
}
public static class std_io_print_ln_event {
public struct Input {
public dynamic expr;
public dynamic invocation;
public dynamic item;
public dynamic program;
public dynamic reporter;
public dynamic allocator;
}
public static dynamic handler(Input __koru_input) {
var expr = __koru_input.expr;
var invocation = __koru_input.invocation;
var item = __koru_input.item;
var program = __koru_input.program;
var reporter = __koru_input.reporter;
var allocator = __koru_input.allocator;
throw new global::System.Exception("ln: [transform] tor is lowered at compile time and must never be called");
}
}
public static class koru_start_event {
public struct Input {
}
public struct Output {
public string tag;
public dynamic done;
}
public static Output handler(Input __koru_input) => new Output { tag = "done" };
}
public static class koru_end_event {
public struct Input {
}
public struct Output {
public string tag;
public dynamic done;
}
public static Output handler(Input __koru_input) => new Output { tag = "done" };
}
public static void flow0() {
var n = main_module.get_number_event.handler(new get_number_event.Input { });
__koru_stdout_write("Got number: " + __koru_str(n) + "\n");
}
public static void flow1() {
main_module.koru_start_event.handler(new koru_start_event.Input { });
}
public static void flow2() {
main_module.koru_end_event.handler(new koru_end_event.Input { });
}
}
static class Program {
static void Main() {
main_module.flow1();
main_module.flow0();
main_module.flow2();
}
}
Flows
flow ~get-number click a branch to expand · @labels scroll to their anchor
get-number
Test Configuration
MUST_RUN LANGUAGES: zig cs
Compiler Flags:
--profilePost-validation Script:
#!/bin/bash
# Validates the Chrome Tracing trace the profiler emitted: the program's real
# transitions are present, the JSON is closed, and the profiler is invisible
# to itself (its write-* events are inserted by [opaque] taps).
if [ -f "koru_profile.snapshot.json" ]; then
PROFILE_FILE="koru_profile.snapshot.json"
else
PROFILE_FILE="/tmp/koru_profile.json"
fi
if [ ! -f "$PROFILE_FILE" ]; then
echo "ERROR: no trace at $PROFILE_FILE"
exit 1
fi
if ! grep -q '"traceEvents"' "$PROFILE_FILE"; then
echo "ERROR: missing traceEvents"
cat "$PROFILE_FILE"
exit 1
fi
if ! grep -q '"input:get-number"' "$PROFILE_FILE"; then
echo "ERROR: input:get-number transition missing"
cat "$PROFILE_FILE"
exit 1
fi
if ! grep -q '^]}$' "$PROFILE_FILE"; then
echo "ERROR: JSON not closed"
cat "$PROFILE_FILE"
exit 1
fi
# The program envelope: koru:start/koru:end are meta-events, not transitions.
# They anchor the trace as ph:"i" instants on their own lane, with one
# synthesized "program" span between them — and must never appear as
# transition rows.
if ! grep -q '"name":"koru:start","cat":"meta","ph":"i"' "$PROFILE_FILE"; then
echo "ERROR: koru:start meta anchor missing"
cat "$PROFILE_FILE"
exit 1
fi
if ! grep -q '"name":"koru:end","cat":"meta","ph":"i"' "$PROFILE_FILE"; then
echo "ERROR: koru:end meta anchor missing"
cat "$PROFILE_FILE"
exit 1
fi
if ! grep -q '"name":"program","cat":"meta","ph":"X"' "$PROFILE_FILE"; then
echo "ERROR: synthesized program span missing"
cat "$PROFILE_FILE"
exit 1
fi
if grep -qE '"name":"koru:[^"]*","cat":"transition"' "$PROFILE_FILE"; then
echo "ERROR: meta-event recorded as a transition"
cat "$PROFILE_FILE"
exit 1
fi
if grep -qE 'write-event|write-header|write-footer' "$PROFILE_FILE"; then
echo "ERROR: profiler observed itself"
cat "$PROFILE_FILE"
exit 1
fi
echo "✓ trace valid"
exit 0