← Back to Demos & Examples

16_query_dialect_engine.vk

Raw .vk
// Example 16: Homoiconic Query & Stream Pipeline Dialect Engine (VQL)
// Demonstrates `quote`, `compose` / `compose/deep`, `parse-block`, cross-backend compile-time
// `macro`s, typed `struct` records (`TraceSpan`, `QueryPlan`), `struct/with`, `filter`/`map`/`reduce`,
// `match`, `/or`, tail-recursive `recur`, and optional `os/args` latency threshold override.
//
// Track A (ORO VM) : veko run examples/16_query_dialect_engine.vk
// Track A (.vko)   : veko compile --vko examples/16_query_dialect_engine.vk -o dist/16.vko ; veko run dist/16.vko
// Track B (Wasm 3) : veko run --wasm examples/16_query_dialect_engine.vk
// Track C (Native) : veko compile --native examples/16_query_dialect_engine.vk -o dist/16.exe ; ./dist/16.exe

use [j = json, str]

TraceSpan = struct {
	id         i64
	svc        str
	region     str = 'us-east'
	severity   u8 = 1
	status     i64 = 200
	latency_ms i64
	bytes_out  i64
	err_tag    str = ''
}

QueryPlan = struct {
	name       str
	svc        str
	min_ms     i64
	status_min i64
	region     str
	limit      i64
	agg        str = 'sum_bytes'
}

make-plan = fn [name str, svc str, min_ms i64, status_min i64, region str, limit i64] QueryPlan [
	QueryPlan {
		name       = name
		svc        = svc
		min_ms     = min_ms
		status_min = status_min
		region     = region
		limit      = limit
		agg        = 'sum_bytes'
	}
]

// Cross-backend safe compile-time macros: IntLitExpr args, flat compose output
sla-budget = macro [target_ms multiplier] [
	compose [(target_ms) * (multiplier)]
]

sla-floor = macro [base_ms margin_ms] [
	compose [(base_ms) + (margin_ms)]
]

// Declarative VQL query specification parsed via homoiconic `quote` + `parse-block`
vql-spec = quote [
	name 'edge-5xx-slow'
	from 'edge-gateway'
	where .latency_gt 100
	where .status_ge 500
	where .region_eq 'eu-west'
	limit 2
	agg .sum_bytes
]

compile-vql = fn [spec any] map [
	mut qname = 'unnamed'
	mut qsvc = ''
	mut qlimit = 10
	mut qagg = .count
	mut clauses = []

	ok = parse-block spec [
		any [
			['name' nm = str!] [
				qname = nm
			]
			['from' s = str!] [
				qsvc = s
			]
			['where' op = enum! rhs = any!] [
				push mut clauses { op = op, rhs = rhs }
			]
			['limit' n = int!] [
				qlimit = n
			]
			['agg' a = enum!] [
				qagg = a
			]
		]
	]

	{ ok = ok, name = qname, svc = qsvc, limit = qlimit, agg = qagg, clauses = clauses }
]

// Typed predicate evaluation using `match` over enum clause opcodes
eval-clause = fn [row TraceSpan, clause any] bool [
	op = clause.op
	match op [
		.latency_gt [ row.latency_ms > (as-i64 clause.rhs) ]
		.status_ge  [ row.status >= (as-i64 clause.rhs) ]
		.region_eq  [ row.region == clause.rhs ]
		.svc_eq     [ row.svc == clause.rhs ]
		_           [ false ]
	]
]

// Constant-stack tail recursion (`recur`) evaluating all `where` clauses for one row
row-matches-all = fn [row TraceSpan, clauses any, idx i64] bool [
	if idx >= (len clauses) [ return true ]
	if not (eval-clause row clauses[idx]) [ return false ]
	recur row clauses (idx + 1)
]

take-n = fn [rows any, limit i64] any [
	n = len rows
	if limit <= 0 or n == 0 [ return [] ]
	end_i = if limit < n [ limit ] else [ n ]
	rows[0..end_i]
]

compute-agg = fn [rows any, agg_kind any] i64 [
	match agg_kind [
		.sum_bytes [
			rows \ map fn [r] [r.bytes_out] \ reduce 0 fn [acc x] [acc + x]
		]
		.max_latency [
			rows \ map fn [r] [r.latency_ms] \ reduce 0 fn [acc x] [if x > acc [ x ] else [ acc ]]
		]
		_ [
			len rows
		]
	]
]

// Sample telemetry stream constructed with `TraceSpan` defaults and `struct/with`
base_span = TraceSpan {
	id         = 1
	svc        = 'edge-gateway'
	region     = 'eu-west'
	severity   = as-u8/or 3 [as-u8 1]
	status     = 502
	latency_ms = 145
	bytes_out  = 2400
	err_tag    = 'upstream-timeout'
}

stream = [
	base_span
	(base_span \ struct/with { id = 2, severity = 1, latency_ms = 65, status = 200, err_tag = '' })
	(base_span \ struct/with { id = 3, region = 'us-east', latency_ms = 210, status = 503, bytes_out = 4100 })
	(base_span \ struct/with { id = 4, severity = 5, latency_ms = 320, status = 504, bytes_out = 5120, err_tag = 'gateway-504' })
	(base_span \ struct/with { id = 5, svc = 'auth-core', latency_ms = 180, status = 500, bytes_out = 1200 })
	(base_span \ struct/with { id = 6, latency_ms = 260, status = 502, bytes_out = 3000, err_tag = 'bad-gateway' })
]

// Optional CLI `os/args` latency override (`-- <min_ms>` or `min_ms`)
default_min_ms = sla-floor 80 20
cli_min_ms = if (len os/args) > 0 [
	str/to-i64/or os/args[0] [default_min_ms]
] else [
	default_min_ms
]

// 1. Compile and run declarative VQL program
compiled = compile-vql vql-spec
svc_filtered = if compiled.svc != '' [
	stream \ filter fn [r] [r.svc == compiled.svc]
] else [
	stream
]
matched_all = svc_filtered \ filter fn [r] [row-matches-all r compiled.clauses 0]
limited = take-n matched_all compiled.limit
agg_bytes = compute-agg limited compiled.agg

projected = limited \ map fn [r] [
	str/join [(mold r.id) ':' r.svc '@' r.region ':' (mold r.status) ':' (mold r.latency_ms) 'ms'] ''
]

// 2. Compile-time macro budget + typed `QueryPlan` + `struct/with` override
budget_ms = sla-budget 120 2
base_plan = make-plan 'sla-watchdog' 'edge-gateway' default_min_ms 500 'eu-west' 5
active_plan = base_plan \ struct/with { min_ms = cli_min_ms }

plan_matches = stream
	\ filter fn [r] [r.svc == active_plan.svc and r.latency_ms > active_plan.min_ms and r.status >= active_plan.status_min and r.region == active_plan.region]
plan_max_lat = compute-agg plan_matches .max_latency
over_budget = plan_matches \ filter fn [r] [r.latency_ms > budget_ms]

// 3. Checked conversion fallback demonstration
bad_u8 = as-u8/or 999 [as-u8 255]

// 4. Diagnostic report AST via `compose/deep`
q_name = compiled.name
q_ok = compiled.ok
q_matched = len matched_all
q_returned = len limited
p_name = active_plan.name
p_breaches = len over_budget
report_ast = compose/deep [
	vql (q_name) [
		parsed (q_ok)
		matched (q_matched)
		returned (q_returned)
		sum_bytes (agg_bytes)
	]
	sla [
		plan (p_name)
		budget_ms (budget_ms)
		breaches (p_breaches)
		max_ms (plan_max_lat)
	]
]

println (str/join ['vql-parsed=' (mold compiled.ok) '|name=' compiled.name '|clauses=' (mold (len compiled.clauses))] '')
println (str/join ['vql-matched=' (mold (len matched_all)) '|limited=' (mold (len limited)) '|sum-bytes=' (mold agg_bytes)] '')
println (str/join ['vql-rows=' (str/join projected ',')] '')
println (str/join ['macro-plan=' (j/encode active_plan)] '')
println (str/join ['sla-budget=' (mold budget_ms) '|breaches=' (mold (len over_budget)) '|max-ms=' (mold plan_max_lat) '|clamped-u8=' (mold bad_u8)] '')
println (str/join ['report-ast=' (mold report_ast)] '')