Part VI · Complete Annotated Examples & Showcase Applications
Appendix C.4
Complete Examples Catalog: Refinements, Interfaces, PNG, Zstd, Flamegraphs, Zero-FFI SQLite, Fuzzing, Registry & Wayland (Examples 33–40)
Unabridged listings covering slash refinements, template strings, interfaces, PNG charts, Range/SSE/KV queries, regex, Zstd, OTel, clipboard/Hi-DPI, X11/Wayland wire protocols, SVG flamegraphs, Zero-FFI SQLite & ORM, fuzzing, and veko-lang.org packages
Complete unabridged source listings for Examples 33 through 40, showcasing user /refinements, universal /or [e -> ...], .secret-safe backtick templates, structural interfaces, lossless image/png & chart widgets, SSE/multipart/Range 206 & indexed db/query, Thompson NFA text/re, RFC 8878 compress/zstd, OpenTelemetry, OS clipboard/Hi-DPI, X11 & Wayland wire-protocol framing, Light-Mode SVG flamegraphs, Zero-FFI SQLite 3 & homoiconic ORM (db/sqlite), deterministic fuzzing (testing/fuzz), and veko-lang.org / HTTPS .vkp registry & veko.lock verification.
Example 33: 33_ergonomic_refinements_templates_and_interfaces.vk
Run command: veko -A examples/33_ergonomic_refinements_templates_and_interfaces.vk
Demonstrates Veko's ergonomic language upgrades across all 3 execution tracks: - User-declarable /refinement parameters with defaults - Universal /or with [e -> fallback] error binding on user functions - Backtick `...{expr}...` string interpolation with automatic .secret redaction - 2-variable for [i x] block & for [k v] map, destructuring, structural match, and interface
1 │ // examples/33_ergonomic_refinements_templates_and_interfaces.vk
2 │ // Demonstrates Veko's ergonomic language upgrades across all 3 execution tracks:
3 │ // - User-declarable `/refinement` parameters with defaults
4 │ // - Universal `/or` with `[e -> fallback]` error binding on user functions
5 │ // - Backtick `` `...{expr}...` `` string interpolation with automatic `.secret` redaction
6 │ // - 2-variable `for [i x] block` & `for [k v] map`, destructuring, structural `match`, and `interface`
7 │
8 │ pub MetricSink = interface {
9 │ name str
10 │ emit fn[str, i64 -> str]
11 │ }
12 │
13 │ pub ConsoleSink = struct {
14 │ name str
15 │ emit any
16 │ }
17 │
18 │ dial-endpoint = fn [host str /port p i64 = 443 /tls use_tls bool = true] str [
19 │ if host == '' [ return (err 'empty upstream host') ]
20 │ scheme = if use_tls [ 'https' ] else [ 'http' ]
21 │ `{scheme}://{host}:{p}`
22 │ ]
23 │
24 │ describe-sink = fn [sink MetricSink, metric str, val i64] str [
25 │ res = (sink.emit metric val)
26 │ `[{sink.name}] {res}`
27 │ ]
28 │
29 │ main = fn [] any [
30 │ // 1. User-declarable slash refinements + universal `/or` with `[e -> ...]`
31 │ u1 = dial-endpoint 'api.veko.dev'
32 │ u2 = dial-endpoint/port/tls '127.0.0.1' 8080 false
33 │ u3 = dial-endpoint/or '' [e -> `fallback({mold e})`]
34 │ if u1 != 'https://api.veko.dev:443' or u2 != 'http://127.0.0.1:8080' [
35 │ return (err 'refinement call mismatch')
36 │ ]
37 │ if not (str/contains? u3 'empty upstream host') [
38 │ return (err 'universal /or error binding mismatch')
39 │ ]
40 │
41 │ // 2. `.secret`-aware template interpolation (propagates .secret taint to interpolated string!)
42 │ mut tok = bytes/with-secret 8
43 │ _ = bytes/push-all mut tok (bytes/from-str 'top-sec!')
44 │ redacted = `auth={tok}`
45 │ if (mold redacted) != '<secret>' [
46 │ return (err 'expected .secret taint & redaction on interpolated string')
47 │ ]
48 │
49 │ // 3. Block & map/struct destructuring + 2-variable `for [i x]` and `for [k v]`
50 │ [first_h second_h] = ['edge-01' 'edge-02']
51 │ cfg = { region = 'ca-west', replicas = 3 }
52 │ { region, replicas } = cfg
53 │
54 │ mut weighted = 0
55 │ for [idx weight] [10 20 30] [
56 │ weighted = weighted + (idx + 1) * weight
57 │ ]
58 │
59 │ mut kv_sum = 0
60 │ for [k v] { a = 4, b = 6, c = 10 } [
61 │ if k != '' [ kv_sum = kv_sum + v ]
62 │ ]
63 │ if first_h != 'edge-01' or second_h != 'edge-02' or region != 'ca-west' or replicas != 3 or weighted != 140 or kv_sum != 20 [
64 │ return (err 'destructuring or 2-var for loop mismatch')
65 │ ]
66 │
67 │ // 4. Structural `match` & structural `interface` contract
68 │ pkt = { kind = .frame, seq_no = 7, bytes = 512 }
69 │ summary = match pkt [
70 │ { kind = .ping } [ 'ping' ]
71 │ { kind = .frame, seq_no = n, bytes = b } [ `frame#{n}:{b}B` ]
72 │ _ [ 'other' ]
73 │ ]
74 │ if summary != 'frame#7:512B' [
75 │ return (err 'structural match mismatch')
76 │ ]
77 │
78 │ sink = ConsoleSink {
79 │ name = 'prom-edge'
80 │ emit = fn [m str, v i64] str [ `{m}={v}` ]
81 │ }
82 │ line = describe-sink sink 'requests_total' 128
83 │ if line != '[prom-edge] requests_total=128' [
84 │ return (err 'interface dispatch mismatch')
85 │ ]
86 │
87 │ println `[Example 33 OK] {u1} | {summary} | {line}`
88 │ .ok
89 │ ]
90 │
91 │ res = main
92 │ if err? res [
93 │ println (str/append 'FAIL: ' (mold res))
94 │ os/exit 1
95 │ ]Example 34: 34_png_charts_and_flex_widgets.vk
Run command: veko -A examples/34_png_charts_and_flex_widgets.vk
Demonstrates pure-Veko Light-Mode UI rendering, flex/grid layout, charts, and lossless PNG roundtrip: - ui/layout & ui/widgets (flex-row, flex-col, grid, stat-card, bar-chart, line-chart) - ui/font proportional mixed-case typography - image/png RFC 2083 RGBA32 encode & decode roundtrip (zero capabilities required!)
1 │ // examples/34_png_charts_and_flex_widgets.vk
2 │ // Demonstrates pure-Veko Light-Mode UI rendering, flex/grid layout, charts, and lossless PNG roundtrip:
3 │ // - `ui/layout` & `ui/widgets` (`flex-row`, `flex-col`, `grid`, `stat-card`, `bar-chart`, `line-chart`)
4 │ // - `ui/font` proportional mixed-case typography
5 │ // - `image/png` RFC 2083 RGBA32 encode & decode roundtrip (zero capabilities required!)
6 │
7 │ use [
8 │ cv = ui/canvas
9 │ png = image/png
10 │ w = ui/widgets
11 │ ]
12 │
13 │ main = fn [] any [
14 │ mut c = cv/new-canvas 380 220
15 │ mut st = w/new-state
16 │ th = w/light-theme
17 │ cv/clear mut c th.bg
18 │
19 │ outer = w/Rect { x = 10, y = 10, w = 360, h = 200 }
20 │ rows = w/flex-col outer [(w/px 56) (w/flex 1)] 8
21 │ kpis = w/grid rows[0] 1 3 8
22 │ w/stat-card mut c kpis[0] 'Requests' '94k/s' '+12%' 'ok' th
23 │ w/stat-card mut c kpis[1] 'Binary' '28 KB' 'AOT' 'info' th
24 │ w/stat-card mut c kpis[2] 'Latency' '0.4ms' '0 GC' 'ok' th
25 │
26 │ cols = w/flex-row rows[1] [(w/flex 1) (w/flex 1)] 8
27 │ w/panel mut c cols[0] 'Throughput' th
28 │ w/bar-chart mut c (w/panel-body cols[0] true 6) ['VM' 'Wasm' 'x64'] [65 130 250] th.accent th
29 │
30 │ w/panel mut c cols[1] 'P99 Trend' th
31 │ series = [
32 │ w/ChartSeries { name = 'x64', values = [18 16 15 14 12], color = th.accent }
33 │ ]
34 │ w/line-chart mut c (w/panel-body cols[1] true 6) ['t0' 't1' 't2' 't3' 't4'] series th
35 │ _ = st
36 │
37 │ // Extract 80x56 KPI+chart snapshot region for fast cross-track (VM/Wasm/Native) lossless PNG roundtrip
38 │ mut snap = cv/new-canvas 80 56
39 │ mut sy = 0
40 │ while sy < 56 [
41 │ mut sx = 0
42 │ while sx < 80 [
43 │ cv/set-pixel mut snap sx sy (cv/get-pixel c (10 + sx) (10 + sy))
44 │ sx = sx + 1
45 │ ]
46 │ sy = sy + 1
47 │ ]
48 │ raw_png = png/encode snap
49 │ dec = png/decode raw_png
50 │ if dec.width != 80 or dec.height != 56 [
51 │ return (err 'PNG dimension mismatch')
52 │ ]
53 │ p_orig = cv/get-pixel snap 14 14
54 │ p_dec = cv/get-pixel dec 14 14
55 │ if p_orig.r != p_dec.r or p_orig.g != p_dec.g or p_orig.b != p_dec.b [
56 │ return (err 'lossless PNG pixel mismatch')
57 │ ]
58 │
59 │ println `[Example 34 OK] canvas=380x220 snap_png={len raw_png}B lossless_verified=true`
60 │ .ok
61 │ ]
62 │
63 │ res = main
64 │ if err? res [
65 │ println (str/append 'FAIL: ' (mold res))
66 │ os/exit 1
67 │ ]Example 35: 35_sse_multipart_and_kv_queries.vk
Run command: veko -A examples/35_sse_multipart_and_kv_queries.vk
Demonstrates Phase 6 web & storage primitives: - web/sse-event, web/sse-resp, web/build-multipart, web/parse-multipart, and Range: 206 Partial Content - db/query secondary-indexed tables over crash-safe db/kv - conc/scope structured concurrency task groups
1 │ // examples/35_sse_multipart_and_kv_queries.vk
2 │ // Demonstrates Phase 6 web & storage primitives:
3 │ // - `web/sse-event`, `web/sse-resp`, `web/build-multipart`, `web/parse-multipart`, and `Range:` `206 Partial Content`
4 │ // - `db/query` secondary-indexed tables over crash-safe `db/kv`
5 │ // - `conc/scope` structured concurrency task groups
6 │
7 │ use [
8 │ web
9 │ kv = db/kv
10 │ q = db/query
11 │ sc = conc/scope
12 │ ]
13 │
14 │ main = fn [] any [
15 │ // 1. SSE event stream formatting + multipart form-data roundtrip
16 │ ev_stream = str/join [
17 │ (web/sse-event 'deploy' '{"status":"started"}' '1')
18 │ (web/sse-event 'deploy' '{"status":"healthy"}' '2')
19 │ ] ''
20 │ sse_r = web/sse-resp ev_stream
21 │ if sse_r.status != 200 or (not (str/contains? (bytes/to-str sse_r.body) 'event: deploy')) [
22 │ return (err 'SSE formatting failed')
23 │ ]
24 │
25 │ boundary = 'vekoBoundary42'
26 │ mp_body = web/build-multipart boundary { env = 'prod' } [
27 │ web/MultipartPart {
28 │ name = 'bundle'
29 │ filename = 'app.vkp'
30 │ content_type = 'application/octet-stream'
31 │ data = bytes/from-str 'VKP1-PAYLOAD'
32 │ }
33 │ ]
34 │ parts = web/parse-multipart mp_body boundary
35 │ if (len parts) != 2 [
36 │ return (err 'multipart roundtrip part count mismatch')
37 │ ]
38 │
39 │ // 2. Secondary-indexed `db/query` table + HTTP Range static serving
40 │ tmp_dir = os/temp-dir
41 │ db_path = str/join [tmp_dir '/veko_ex35_query.vkkv'] ''
42 │ asset_path = str/join [tmp_dir '/veko_ex35_range.bin'] ''
43 │ _ = os/remove/or db_path [.ok]
44 │ _ = os/write-file asset_path '0123456789ABCDEF'
45 │
46 │ r206 = web/serve-static-range tmp_dir 'veko_ex35_range.bin' 'bytes=4-9'
47 │ _ = os/remove/or asset_path [.ok]
48 │ if r206.status != 206 or (bytes/to-str r206.body) != '456789' [
49 │ return (err 'HTTP 206 Range slice mismatch')
50 │ ]
51 │
52 │ mut db = kv/open-fast db_path
53 │ nodes = q/define-table 'nodes' 'id' ['zone' 'tier']
54 │ _ = q/put-row mut db nodes { id = 'n1', zone = 'us-west', tier = 'edge' }
55 │ _ = q/put-row mut db nodes { id = 'n2', zone = 'eu-central', tier = 'core' }
56 │ _ = q/put-row mut db nodes { id = 'n3', zone = 'us-west', tier = 'core' }
57 │ west = q/where-eq db nodes 'zone' 'us-west'
58 │ _ = kv/close mut db
59 │ _ = os/remove/or db_path [.ok]
60 │ if (len west) != 2 [
61 │ return (err 'db/query secondary index lookup failed')
62 │ ]
63 │
64 │ // 3. Structured concurrency `conc/scope`
65 │ mut grp = sc/new
66 │ sc/add mut grp (spawn [ 14 * 3 ])
67 │ sc/add mut grp (spawn [ 29 * 2 ])
68 │ vals = sc/await-all mut grp
69 │ if vals[0] != 42 or vals[1] != 58 [
70 │ return (err 'conc/scope results mismatch')
71 │ ]
72 │
73 │ println `[Example 35 OK] multipart={len parts} range_206={bytes/to-str r206.body} indexed_rows={len west} scope={vals[0] + vals[1]}`
74 │ .ok
75 │ ]
76 │
77 │ res = main
78 │ if err? res [
79 │ println (str/append 'FAIL: ' (mold res))
80 │ os/exit 1
81 │ ]Example 36: 36_regex_zstd_otel_and_bindgen.vk
Run command: veko -A examples/36_regex_zstd_otel_and_bindgen.vk
Demonstrates Phase 6 batteries (zero capabilities required!): - text/re linear-time Thompson NFA regex matching, extraction, and replacement - compress/zstd RFC 8878 Zstandard frame compression & decompression - otel W3C traceparent propagation, OTLP JSON span export, and Prometheus metrics
1 │ // examples/36_regex_zstd_otel_and_bindgen.vk
2 │ // Demonstrates Phase 6 batteries (zero capabilities required!):
3 │ // - `text/re` linear-time Thompson NFA regex matching, extraction, and replacement
4 │ // - `compress/zstd` RFC 8878 Zstandard frame compression & decompression
5 │ // - `otel` W3C `traceparent` propagation, OTLP JSON span export, and Prometheus metrics
6 │
7 │ use [
8 │ re = text/re
9 │ zstd = compress/zstd
10 │ otel
11 │ ]
12 │
13 │ main = fn [] any [
14 │ // 1. Linear-time Thompson NFA regex (`text/re`)
15 │ rx = re/compile '[a-z]+-[0-9]+|v[0-9]+\\.[0-9]+'
16 │ // Match service tags and versions in log line
17 │ rx_ver = re/compile 'v[0-9]+\\.[0-9]+\\.[0-9]+'
18 │ log_line = 'deploy node-07 running v1.0.0 -> upgraded to v1.2.4'
19 │ vers = re/find-all rx_ver log_line
20 │ scrubbed = re/replace-all (re/compile '[0-9]+') 'token=94821 user=42' '#'
21 │ _ = rx
22 │ if (len vers) != 2 or vers[0].text != 'v1.0.0' or vers[1].text != 'v1.2.4' or scrubbed != 'token=# user=#' [
23 │ return (err 'text/re match or replace failed')
24 │ ]
25 │
26 │ // 2. RFC 8878 Zstandard frame roundtrip (`compress/zstd`)
27 │ raw_payload = bytes/from-str 'telemetry-frame: AAAAAAAAAAAAAAAAAAAAAAAA status=200 ok'
28 │ compressed = zstd/compress raw_payload
29 │ restored = zstd/decompress compressed
30 │ if (not (zstd/zstd-frame? compressed)) or restored != raw_payload [
31 │ return (err 'compress/zstd roundtrip failed')
32 │ ]
33 │
34 │ // 3. OpenTelemetry W3C `traceparent` + OTLP JSON + Prometheus metrics (`otel`)
35 │ ctx = otel/make-context 0x0af7651916cd43dd 0x8448eb211c80319c 0x00f067aa0ba902b7 true
36 │ tp_hdr = otel/format-traceparent ctx
37 │ parsed_ctx = otel/parse-traceparent tp_hdr
38 │ mut sp = otel/start-span 'GET /api/nodes' parsed_ctx 0x1122334455667788 1000000
39 │ otel/set-attr mut sp 'http.method' 'GET'
40 │ _ = otel/finish-span mut sp 1420000
41 │ otlp_json = otel/export-otlp-json 'veko-gateway' [sp]
42 │
43 │ mut reg = otel/new-registry 'veko-gateway'
44 │ _ = otel/inc-counter/help mut reg 'http_requests_total' 5 'Total HTTP requests'
45 │ _ = otel/set-gauge mut reg 'active_connections' 12
46 │ prom_txt = otel/export-prometheus reg
47 │ if (not (str/contains? otlp_json 'veko-gateway')) or (not (str/contains? prom_txt 'http_requests_total')) [
48 │ return (err 'otel export mismatch')
49 │ ]
50 │
51 │ println `[Example 36 OK] regex={vers[1].text} zstd={len compressed}B traceparent={tp_hdr[0..19]}...`
52 │ .ok
53 │ ]
54 │
55 │ res = main
56 │ if err? res [
57 │ println (str/append 'FAIL: ' (mold res))
58 │ os/exit 1
59 │ ]Example 37: 37_clipboard_x11_flamegraph_and_lock.vk
Run command: veko -A examples/37_clipboard_x11_flamegraph_and_lock.vk
Demonstrates OS/session clipboard with .secret firewall protection, zero-libc X11 wire-protocol scanline-band PutImage chunking (ui/x11), Light-Mode interactive SVG flamegraphs (profile/flamegraph), and homoiconic cryptographic package lockfiles (pkg/lock + pkg/vkp).
1 │ // examples/37_clipboard_x11_flamegraph_and_lock.vk
2 │ // Demonstrates OS/session clipboard with `.secret` firewall protection, zero-`libc` X11 wire-protocol
3 │ // scanline-band `PutImage` chunking (`ui/x11`), Light-Mode interactive SVG flamegraphs (`profile/flamegraph`),
4 │ // and homoiconic cryptographic package lockfiles (`pkg/lock` + `pkg/vkp`).
5 │
6 │ use [
7 │ ui
8 │ fg = profile/flamegraph
9 │ hex = codec/hex
10 │ lk = pkg/lock
11 │ vkp = pkg/vkp
12 │ x11 = ui/x11
13 │ ]
14 │
15 │ main = fn [] any [
16 │ // 1. Clipboard round-trip + .secret firewall verification
17 │ _ = ui/set-clipboard 'https://edge.veko.dev:8443'
18 │ plain_cb = ui/clipboard-text
19 │ sec_cb = ui/clipboard-secret
20 │ if plain_cb != 'https://edge.veko.dev:8443' or (mold sec_cb) != '<secret>' [
21 │ return (err 'clipboard or secret redaction mismatch')
22 │ ]
23 │
24 │ // 2. Zero-libc X11 wire protocol: Setup packet + 960x600 PutImage scanline-band chunking
25 │ sock_p = x11/display-socket-path 'unix:0.0'
26 │ setup_pkt = x11/encode-setup (bytes/with-cap 0)
27 │ bands = x11/plan-put-image-bands 960 600
28 │ if sock_p != '/tmp/.X11-unix/X0' or (len setup_pkt) != 12 or (len bands) != 18 or bands[0].byte_count > 131100 [
29 │ return (err 'x11 band planning failed')
30 │ ]
31 │
32 │ // 3. Light-Mode interactive SVG flamegraph from folded call-stack samples
33 │ samples = fg/parse-folded (str/join [
34 │ 'main;compile-project;parse-module;tokenize 1850000'
35 │ 'main;compile-project;parse-module;parse-expr 2400000'
36 │ 'main;compile-project;check-types 1920000'
37 │ 'main;compile-project;emit-native-x64 3650000'
38 │ ] '\n')
39 │ svg = fg/render-svg 'Veko Native Compiler Pipeline' samples
40 │ if not (str/contains? svg 'Reset Zoom') or not (str/contains? svg '#FAFAF7') [
41 │ return (err 'flamegraph SVG missing interactive Light-Mode elements')
42 │ ]
43 │
44 │ // 4. Homoiconic veko.lock + signed VKP1 Merkle verification
45 │ seed = hex/decode '0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20'
46 │ if err? seed [ return seed ]
47 │ vkp_raw = vkp/pack-ed25519 { name = 'telemetry_ext', version = '1.4.2' } {
48 │ 'mod.vk' = (bytes/from-str 'pub tag = fn [] str [ \'ok\' ]\n')
49 │ } seed
50 │ if err? vkp_raw [ return vkp_raw ]
51 │ entry = lk/lock-vkp-bytes 'telemetry_ext' 'pkgs/telemetry_ext.vkp' vkp_raw []
52 │ if err? entry [ return entry ]
53 │ lock_txt = lk/encode (lk/Lockfile { version = 1, packages = [ entry ] })
54 │ decoded = lk/decode lock_txt
55 │ verified = lk/verify-locked-bytes decoded.packages[0] vkp_raw []
56 │ if err? verified [ return verified ]
57 │
58 │ println `[Example 37 OK] clip={plain_cb} | x11_bands={len bands} | svg={len svg}B | lock={decoded.packages[0].name}@{decoded.packages[0].version}`
59 │ 0
60 │ ]
61 │
62 │ mainExample 38: 38_zero_ffi_sqlite_and_orm.vk
Run command: veko -A examples/38_zero_ffi_sqlite_and_orm.vk
Demonstrates Veko's pure-Veko Zero-FFI SQLite 3 engine ("SQLite format 3\0" 4096-byte slotted B-tree pages) and homoiconic ORM / query DSL (db/sqlite) across VM, Wasm, and Native.
1 │ // examples/38_zero_ffi_sqlite_and_orm.vk
2 │ // Demonstrates Veko's pure-Veko Zero-FFI SQLite 3 engine (`"SQLite format 3\0"` 4096-byte
3 │ // slotted B-tree pages) and homoiconic ORM / query DSL (`db/sqlite`) across VM, Wasm, and Native.
4 │
5 │ use [sq = db/sqlite]
6 │
7 │ main = fn [] any [
8 │ mut db = sq/open ':memory:'
9 │
10 │ // 1. Parameterized SQL DDL, UNIQUE index, transaction rollback, and aggregates
11 │ r1 = sq/exec mut db 'CREATE TABLE invoices (id INTEGER PRIMARY KEY, customer TEXT, cents INTEGER, status TEXT)' []
12 │ if err? r1 [ return r1 ]
13 │ r2 = sq/exec mut db 'CREATE UNIQUE INDEX idx_inv_cust ON invoices (customer)' []
14 │ if err? r2 [ return r2 ]
15 │
16 │ _ = sq/exec mut db 'INSERT INTO invoices (customer, cents, status) VALUES (?, ?, ?)' ['Acme Corp' 12500 'paid']
17 │ _ = sq/exec mut db 'INSERT INTO invoices (customer, cents, status) VALUES (?, ?, ?)' ['Veko Labs' 28000 'paid']
18 │ _ = sq/exec mut db 'INSERT INTO invoices (customer, cents, status) VALUES (?, ?, ?)' ['North Star' 4900 'draft']
19 │
20 │ // Verify BEGIN / ROLLBACK restores exact B-tree snapshot
21 │ _ = sq/exec mut db 'BEGIN' []
22 │ _ = sq/exec mut db 'DELETE FROM invoices WHERE status = ?' ['paid']
23 │ _ = sq/exec mut db 'ROLLBACK' []
24 │
25 │ agg_rows = sq/query-sql db 'SELECT COUNT(*) AS n, SUM(cents) AS total FROM invoices WHERE status = ?' ['paid']
26 │ if err? agg_rows or (len agg_rows) != 1 [ return (err 'aggregate query failed') ]
27 │ agg = agg_rows[0]
28 │ if agg.n != 2 or agg.total != 40500 [
29 │ return (err `unexpected SQL aggregate: {mold agg}`)
30 │ ]
31 │
32 │ // 2. Homoiconic Veko ORM (`define-table`, `migrate`, `insert`, `find-by-id`, `q`)
33 │ deployments = sq/define-table 'deployments' (quote [
34 │ id i64 .pk
35 │ region str .index
36 │ env str
37 │ ok bool
38 │ ])
39 │ rm = sq/migrate mut db deployments
40 │ if err? rm [ return rm ]
41 │
42 │ id1 = sq/insert mut db deployments { region = 'ca-central-1', env = 'prod', ok = true }
43 │ id2 = sq/insert mut db deployments { region = 'eu-west-1', env = 'prod', ok = true }
44 │ _ = sq/insert mut db deployments { region = 'us-east-1', env = 'staging', ok = false }
45 │ if err? id1 or err? id2 [ return (err 'orm insert failed') ]
46 │
47 │ prod_rows = sq/q db (quote [
48 │ from deployments
49 │ where [env == 'prod']
50 │ order-by [region .asc]
51 │ limit 10
52 │ ])
53 │ if err? prod_rows [ return prod_rows ]
54 │ if (len prod_rows) != 2 or prod_rows[0].region != 'ca-central-1' or prod_rows[1].region != 'eu-west-1' [
55 │ return (err `unexpected ORM query rows: {mold prod_rows}`)
56 │ ]
57 │
58 │ // 3. Round-trip genuine 4096-byte SQLite 3 binary image ("SQLite format 3\0")
59 │ wire = sq/to-bytes db
60 │ if (len wire) < 4096 or ((len wire) % 4096) != 0 or (bytes/to-str wire[0..15]) != 'SQLite format 3' [
61 │ return (err 'invalid SQLite 3 binary image header or page alignment')
62 │ ]
63 │ reopened = sq/from-bytes wire
64 │ if err? reopened [ return reopened ]
65 │ dep1 = sq/find-by-id reopened deployments id1
66 │ if err? dep1 or dep1.region != 'ca-central-1' [
67 │ return (err 'SQLite 3 B-tree round-trip verification failed')
68 │ ]
69 │
70 │ println `[Example 38 OK] sqlite_pages={(len wire) / 4096} | paid_cents={agg.total} | orm_prod={len prod_rows} | region0={dep1.region}`
71 │ 0
72 │ ]
73 │
74 │ mainExample 39: 39_debugger_coverage_and_fuzzing.vk
Run command: veko -A examples/39_debugger_coverage_and_fuzzing.vk
Demonstrates deterministic property fuzzing and automatic delta-debugging counterexample shrinking (testing/fuzz) across byte slices, UTF-8 strings, and homoiconic Veko blocks.
1 │ // examples/39_debugger_coverage_and_fuzzing.vk
2 │ // Demonstrates deterministic property fuzzing and automatic delta-debugging counterexample
3 │ // shrinking (`testing/fuzz`) across byte slices, UTF-8 strings, and homoiconic Veko blocks.
4 │
5 │ use [fz = testing/fuzz]
6 │
7 │ encode-tlv = fn [tag i64, payload bytes] bytes [
8 │ mut out = bytes/with-cap (3 + (len payload))
9 │ _ = bytes/push mut out (tag & 0xff)
10 │ _ = bytes/push-u16-be mut out (len payload)
11 │ _ = bytes/push-all mut out payload
12 │ out
13 │ ]
14 │
15 │ decode-tlv = fn [frame bytes] bytes [
16 │ if (len frame) < 3 [ return (err 'truncated TLV header') ]
17 │ plen = bytes/get-u16-be frame 1
18 │ if (3 + plen) != (len frame) [ return (err 'TLV length mismatch') ]
19 │ frame[3..(3 + plen)]
20 │ ]
21 │
22 │ main = fn [] any [
23 │ cfg = fz/FuzzConfig { seed = 20261203, runs = 120, max_len = 48 }
24 │
25 │ // 1. Property holds: TLV round-trip preserves arbitrary byte slices
26 │ tlv_ok = fz/fuzz-bytes cfg fn [raw bytes] any [
27 │ dec = decode-tlv (encode-tlv 7 raw)
28 │ if err? dec [ return dec ]
29 │ bytes/eq dec raw
30 │ ]
31 │ chk = fz/assert-fuzz tlv_ok 'tlv-roundtrip'
32 │ if err? chk [ return chk ]
33 │
34 │ // 2. Planted byte-parser bug: automatic delta-debugging shrinks random input down to 2 bytes!
35 │ bug_bytes = fz/fuzz-bytes cfg fn [buf bytes] any [
36 │ // Planted defect whenever any byte >= 0xC0 is followed anywhere by a byte >= 0x80
37 │ mut seen_hi = false
38 │ mut i = 0
39 │ while i < (len buf) [
40 │ if seen_hi and buf[i] >= 0x80 [
41 │ return (err 'unhandled multi-byte marker')
42 │ ]
43 │ if buf[i] >= 0xC0 [ seen_hi = true ]
44 │ i = i + 1
45 │ ]
46 │ true
47 │ ]
48 │ if bug_bytes.ok or (len bug_bytes.shrunk_input) != 2 [
49 │ return (err `expected 2-byte shrunk reproducer, got {mold bug_bytes}`)
50 │ ]
51 │
52 │ // 3. Homoiconic block fuzzer shrinks nested block failure to 1-element minimal block `[.ping]`
53 │ bug_blk = fz/fuzz-block cfg fn [blk block] any [
54 │ mut i = 0
55 │ while i < (len blk) [
56 │ el = blk[i]
57 │ if (type-of el) == .enum_sym and el == .ping [
58 │ return (err 'unexpected .ping token in AST block')
59 │ ]
60 │ i = i + 1
61 │ ]
62 │ true
63 │ ]
64 │ if bug_blk.ok or bug_blk.shrunk_input != [.ping] [
65 │ return (err `expected shrunk block [.ping], got {mold bug_blk.shrunk_input}`)
66 │ ]
67 │
68 │ println `[Example 39 OK] tlv_runs={tlv_ok.runs} | shrunk_bytes={len bug_bytes.shrunk_input}B | shrunk_block={mold bug_blk.shrunk_input}`
69 │ 0
70 │ ]
71 │
72 │ mainExample 40: 40_sdk_https_registry_and_wayland.vk
Run command: veko -A examples/40_sdk_https_registry_and_wayland.vk
Demonstrates Veko's single-binary portable SDK & veko-lang.org / decentralized HTTPS .vkp registry conventions (pkg/lock), VEKO_LIB shared-library resolution (ffi), and pure-Veko Linux Wayland (wl_shm + xdg_wm_base) wire-protocol framing (ui/wayland).
1 │ // examples/40_sdk_https_registry_and_wayland.vk
2 │ // Demonstrates Veko's single-binary portable SDK & `veko-lang.org` / decentralized HTTPS `.vkp`
3 │ // registry conventions (`pkg/lock`), `VEKO_LIB` shared-library resolution (`ffi`), and pure-Veko
4 │ // Linux Wayland (`wl_shm` + `xdg_wm_base`) wire-protocol framing (`ui/wayland`).
5 │
6 │ use [
7 │ ffi
8 │ hex = codec/hex
9 │ lk = pkg/lock
10 │ vkp = pkg/vkp
11 │ wl = ui/wayland
12 │ ]
13 │
14 │ main = fn [] any [
15 │ // 1. Official veko-lang.org registry expansion + decentralized HTTPS spec preservation
16 │ official_url = lk/expand-spec-with-registry 'http_router@1.2.0' 'https://veko-lang.org/pkg'
17 │ custom_url = lk/expand-spec-with-registry 'https://pkg.example.org/veko/kv_extra-0.4.0.vkp' 'https://veko-lang.org/pkg'
18 │ if official_url != 'https://veko-lang.org/pkg/http_router/1.2.0.vkp' [
19 │ return (err `unexpected official registry URL: {official_url}`)
20 │ ]
21 │ if custom_url != 'https://pkg.example.org/veko/kv_extra-0.4.0.vkp' [
22 │ return (err `unexpected custom HTTPS URL: {custom_url}`)
23 │ ]
24 │
25 │ // 2. Signed .vkp bundle + ~/.veko_modules content-addressed cache layout
26 │ seed = hex/decode '1112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30'
27 │ if err? seed [ return seed ]
28 │ pkg_bytes = vkp/pack-ed25519 { name = 'http_router', version = '1.2.0' } {
29 │ 'mod.vk' = (bytes/from-str 'pub version = fn [] str [ \'1.2.0\' ]\n')
30 │ } seed
31 │ if err? pkg_bytes [ return pkg_bytes ]
32 │ locked = lk/lock-vkp-bytes 'http_router' official_url pkg_bytes []
33 │ if err? locked [ return locked ]
34 │
35 │ // 3. VEKO_LIB shared-library candidate expansion
36 │ lib_cands = ffi/candidate-paths 'zstd' '/opt/veko/lib:/usr/local/lib' false
37 │ if (len lib_cands) < 3 [
38 │ return (err 'expected VEKO_LIB candidate search paths')
39 │ ]
40 │
41 │ // 4. Zero-libc Linux Wayland wire-protocol framing (wl_registry.bind, wl_shm, present)
42 │ wl_sock = wl/socket-path '/run/user/1000' 'wayland-0'
43 │ bind_pkt = wl/encode-registry-bind 2 4 'wl_shm' 1 5
44 │ pool_pkt = wl/encode-shm-create-pool 5 7 (800 * 600 * 4)
45 │ frame_pkt = wl/encode-surface-present 9 8 800 600
46 │ hdr = wl/decode-hdr bind_pkt 0
47 │ if err? hdr [ return hdr ]
48 │ if wl_sock != '/run/user/1000/wayland-0' or hdr.object_id != 2 or (len pool_pkt) != 16 or (len frame_pkt) != 52 [
49 │ return (err 'wayland wire framing mismatch')
50 │ ]
51 │
52 │ println `[Example 40 OK] reg={official_url} | sha256={locked.sha256[0..12]}... | wl_sock={wl_sock} | present={len frame_pkt}B`
53 │ 0
54 │ ]
55 │
56 │ mainExample 41: 41_oro_latency_and_memory_proof.vk
Run command: veko -A examples/41_oro_latency_and_memory_proof.vk
Reproducible ORO Tail-Latency & Deterministic Memory Proof: executes 500 realistic HMAC-SHA256 + JSON + Zero-FFI SQLite B-Tree webhook transactions and reports p50..p99.9 latency.
1 │ // examples/41_oro_latency_and_memory_proof.vk
2 │ // Reproducible ORO Tail-Latency & Deterministic Memory Proof: executes 500 realistic
3 │ // HMAC-SHA256 + JSON + Zero-FFI SQLite B-Tree webhook transactions and reports p50..p99.9 latency.
4 │
5 │ use [
6 │ hex = codec/hex
7 │ sha = crypto/sha256
8 │ sq = db/sqlite
9 │ ]
10 │
11 │ sort-latencies = fn [mut xs block] [
12 │ n = len xs
13 │ mut gap = n / 2
14 │ while gap > 0 [
15 │ mut i = gap
16 │ while i < n [
17 │ temp = as-i64 xs[i]
18 │ mut j = i
19 │ while j >= gap and (as-i64 xs[j - gap]) > temp [
20 │ put mut xs j xs[j - gap]
21 │ j = j - gap
22 │ ]
23 │ put mut xs j temp
24 │ i = i + 1
25 │ ]
26 │ gap = gap / 2
27 │ ]
28 │ .ok
29 │ ]
30 │
31 │ pct-us = fn [sorted_ns block, numer i64, denom i64] str [
32 │ n = len sorted_ns
33 │ if n == 0 [ return '0.0' ]
34 │ mut idx = (n * numer) / denom
35 │ if idx >= n [ idx = n - 1 ]
36 │ ns_val = as-i64 sorted_ns[idx]
37 │ tenths = (ns_val + 50) / 100
38 │ whole = tenths / 10
39 │ frac = tenths % 10
40 │ str/join [(mold whole) '.' (mold frac)] ''
41 │ ]
42 │
43 │ process-webhook-tx = fn [mut db sq/SqliteDb, events_tbl sq/TableSpec, wh_key bytes, seq_id i64, raw_body str, want_sig str] any [
44 │ got_sig = hex/encode (sha/hmac-sha256 wh_key (bytes/from-str raw_body))
45 │ if got_sig != want_sig [ return (err 'invalid hmac signature') ]
46 │ ev = json/decode raw_body
47 │ row_id = sq/insert mut db events_tbl {
48 │ event_id = (str/append 'evt_' (mold seq_id))
49 │ account_id = (str/append '' (map/get ev 'account'))
50 │ amount_cts = (as-i64 (map/get ev 'amount')) + (seq_id % 7)
51 │ }
52 │ if err? row_id [ return row_id ]
53 │ json/encode { ok = true, id = row_id, status = 'settled' }
54 │ ]
55 │
56 │ main = fn [] any [
57 │ wh_key = sha/sha256 (bytes/from-str 'veko-deterministic-oro-webhook-key')
58 │ sample_body = '{"account":"acct_enterprise_01","amount":4900,"currency":"USD"}'
59 │ valid_sig = hex/encode (sha/hmac-sha256 wh_key (bytes/from-str sample_body))
60 │
61 │ events_tbl = sq/define-table 'webhook_events' (quote [
62 │ id i64 .pk
63 │ event_id str .unique
64 │ account_id str
65 │ amount_cts i64
66 │ ])
67 │
68 │ mut db = sq/open ':memory:'
69 │ _ = sq/migrate mut db events_tbl
70 │
71 │ // Warm up 25 iterations, then measure 500 full webhook transactions end-to-end
72 │ mut w = 0
73 │ while w < 25 [
74 │ _ = process-webhook-tx mut db events_tbl wh_key w sample_body valid_sig
75 │ w = w + 1
76 │ ]
77 │
78 │ iters = 500
79 │ mut samples_ns = []
80 │ mut i = 0
81 │ t_total0 = time/now
82 │ while i < iters [
83 │ t0 = time/now
84 │ resp = process-webhook-tx mut db events_tbl wh_key (1000 + i) sample_body valid_sig
85 │ dt = as-i64 (((time/now) - t0) / 1ns)
86 │ if err? resp [ return resp ]
87 │ push mut samples_ns dt
88 │ i = i + 1
89 │ ]
90 │ elapsed_ms = as-i64 (((time/now) - t_total0) / 1ms)
91 │ _ = sq/close mut db
92 │
93 │ sort-latencies mut samples_ns
94 │ p50 = pct-us samples_ns 500 1000
95 │ p95 = pct-us samples_ns 950 1000
96 │ p99 = pct-us samples_ns 990 1000
97 │ p999 = pct-us samples_ns 999 1000
98 │
99 │ println '=== Veko 1.0 ORO Tail-Latency & Memory Determinism Proof ==='
100 │ println `Workload : {iters} HMAC-SHA256 + JSON + Zero-FFI SQLite B-Tree transactions`
101 │ println `Elapsed : {elapsed_ms} ms total (zero GC stop-the-world pauses)`
102 │ println `Latency : p50={p50} us | p95={p95} us | p99={p99} us | p99.9={p999} us`
103 │ .ok
104 │ ]
105 │
106 │ res = main
107 │ if err? res [
108 │ println (str/append 'proof failed: ' (mold res))
109 │ os/exit 1
110 │ ]