[ ZR-41 · EXECUTION RESEARCH ] Code

Execution Notes. Five sketches.

Original examples for the ideas in the research series. PHP is ordinary PHP; everything else is labelled as conceptual code or pseudocode. There is no repository, engine build or download behind these notes.

1. A PHP function and its conceptual ZIR

A small, strict-typed helper. The lowering makes the cast and the two identity checks explicit operations; the (int) cast is total, so no exception path appears.

page_size.phpPHP
<?php
declare(strict_types=1);

// Normalise a user-supplied page size, with PHP's own clamp semantics.
function page_size(?string $raw, int $default = 20): int {
    if ($raw === null || $raw === '') {
        return $default;
    }
    $n = (int) $raw;            // "12abc" -> 12, "abc" -> 0
    return max(1, min($n, 100));
}
page_size.zirZIR pseudocode
; ZIR pseudocode. Conceptual lowering of page_size; not compiler output.
fn page_size(%raw: ?str, %default: int) -> int
  %isnull = cmp.identical %raw null
  br %isnull use_default
  %empty  = cmp.identical %raw ""
  br %empty use_default
  %n      = cast.int %raw          ; PHP (int) cast: leading digits, else 0; never throws
  %lo     = call.builtin min %n 100
  %v      = call.builtin max 1 %lo
  ret %v
use_default:
  ret %default

2. A request-local handle in Rust

Handles carry an index and a generation. Releasing a slot bumps its generation so a stale handle fails a comparison instead of reading reused memory. The lifetime parameter ties handles to the arena of the request that issued them.

arena.rsRust, illustrative
// Rust: generation-checked handle into a request-owned arena.
// Illustrative; shown for structure, not claimed to compile as-is.
use std::marker::PhantomData;

pub struct Handle<'req, T> { index: u32, generation: u32, _owner: PhantomData<&'req T> }
impl<'req, T> Clone for Handle<'req, T> { fn clone(&self) -> Self { *self } }
impl<'req, T> Copy for Handle<'req, T> {}

struct Slot<T> { generation: u32, value: Option<T> }

pub struct RequestArena<'req, T> { slots: Vec<Slot<T>>, _scope: PhantomData<&'req mut ()> }

#[derive(Debug)]
pub enum HandleError { Stale, Released }

impl<'req, T> RequestArena<'req, T> {
    pub fn new() -> Self { RequestArena { slots: Vec::new(), _scope: PhantomData } }

    pub fn insert(&mut self, value: T) -> Handle<'req, T> {
        let index = self.slots.len() as u32;
        self.slots.push(Slot { generation: 0, value: Some(value) });
        Handle { index, generation: 0, _owner: PhantomData }
    }

    pub fn get(&self, h: Handle<'req, T>) -> Result<&T, HandleError> {
        let slot = self.slots.get(h.index as usize).ok_or(HandleError::Stale)?;
        if slot.generation != h.generation { return Err(HandleError::Stale); }
        slot.value.as_ref().ok_or(HandleError::Released)
    }

    pub fn release(&mut self, h: Handle<'req, T>) -> Option<T> {
        let slot = self.slots.get_mut(h.index as usize)?;
        if slot.generation != h.generation { return None; }
        slot.generation = slot.generation.wrapping_add(1); // old handles now fail get()
        slot.value.take()
    }
}

3. Capability authorization

Every external effect funnels through one function. All three refusal paths raise a catchable error before any service is contacted, and arguments cross the boundary only as copies.

perform.pseudoPseudocode
# Pseudocode: capability-mediated effect dispatch.
fn perform(cell, op, cap_id, args):
    let cap = cell.caps.lookup(cap_id)
    if cap is none or cap.generation != cell.caps.generation_of(cap_id):
        raise CapabilityError("no such capability")       # program may catch this
    if not cap.permits(op.kind):
        raise CapabilityError("operation not permitted")
    if not cap.scope.contains(op.target):                # e.g. path stays under root
        raise CapabilityError("target outside scope")
    charge(cell.budget, op.estimated_cost)               # may move cell to Exhausted
    let request = deep_copy_out(args, cell.region)       # services never see the region
    let reply = cap.service.call(op, request)            # the only place an effect occurs
    return deep_copy_in(reply, cell.region)

4. Teardown and cancellation

All four ways a request can end share one sequence. Destructors run under a fixed allowance; resources release in reverse order; revoking capabilities precedes reclaiming memory.

teardown.pseudoPseudocode
# Pseudocode: teardown and cancellation for one request cell.
fn end_request(cell, reason):            # reason: done | error | cancelled | exhausted
    cell.state = Ending                  # scheduler stops issuing ZIR operations
    with allowance(TEARDOWN_BUDGET) as a:
        for obj in cell.pending_destructors():
            if a.exhausted(): log("teardown overrun", cell.id); break
            run_destructor(obj, budget = a)       # may not acquire new capabilities
    for token in reverse(cell.open):
        token.release(deadline = RELEASE_DEADLINE) # rollback open transactions first
    cell.caps.revoke_all()               # generation++: stale handles now fail
    cell.region.reclaim()                # one operation, not per-object frees
    cell.state = Sealed

fn on_client_disconnect(cell):
    if cell.state == Running:
        cell.cancel_flag = true          # checked between operations and in waits
        end_request(cell, cancelled)

5. Differential test outline

The comparison includes diagnostics and destructor order, not only stdout, because those are observable behaviour too. Divergences are minimised and kept as regression cases.

differential.pseudoTest outline
# Pseudocode: differential test comparing observable PHP behaviour.
for each case in corpus + fuzz_generator(seed):
    let ref  = run_reference_php(case.source, case.input, ini = PINNED_INI)
    let cand = run_candidate(case.source, case.input, ini = PINNED_INI)
    compare:
        ref.stdout            == cand.stdout
        ref.exit_status       == cand.exit_status
        ref.diagnostics       == cand.diagnostics       # type, message, order
        ref.uncaught          == cand.uncaught          # class + message
        ref.destructor_order  == cand.destructor_order  # traced via __destruct echo
    if any differ:
        minimise(case) and record(case, ref, cand)      # divergence is a finding
    assert cand.engine_faults == []                     # a fault is always a bug
Not evidence of a working engine.

These sketches have not been compiled or executed as part of any runtime. They exist to make the design concrete enough to criticise.