Normative Specification: ImpulseVM Virtual Machine & impOps Instruction Set
- Document Status: Standard Reference Specification
- Target Architecture: 64-bit Register-based Virtual Machine (off-heap execution focus)
This document defines the formal normative specification for the ImpulseVM register machine and its register type system, execution state layout, status flags, and the impOps bytecode instruction set. All implementations of the ImpulseVM and associated assemblers/compilers MUST comply with this specification.
1. Terminology & Compliance (RFC 2119)
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.
2. Virtual Machine Register Architecture
The ImpulseVM is a register-based virtual machine operating on a bank of general-purpose and specialized registers.
2.1 General-Purpose Registers
- The VM MUST expose exactly 64 general-purpose registers, designated
R0throughR63. - Each register is exactly 64 bits wide and SHALL store a 64-bit integer, float, pointer, or off-heap object handle.
- Each register MUST have an associated 8-bit type tag (see §2.4) that defines the semantic interpretation of the 64-bit value.
2.2 Program Counter (PC)
- The execution context MUST maintain a 32-bit unsigned Program Counter (
pc). - The
pcregister represents the zero-indexed instruction array offset of the currently executing instruction. - The
pcMUST only be incremented after the successful execution of an instruction. If an instruction halts (e.g.,OP_HALT) or faults (e.g., bounds error, trap, throw), thepcremains strictly pointed at the offset of that halting or faulting instruction.
2.3 Status Flags Register (FLAGS)
The execution state MUST maintain a 64-bit status flags register (flags). The lower bits are mapped as follows:
| Bit Index | Flag | Constant Name | Semantic Description |
|---|---|---|---|
Bit 0 |
ZF | IMPULSE_VM_FLAG_ZF |
Zero Flag: Set if candidate set or arithmetic result is empty / zero. |
Bit 1 |
LT | IMPULSE_VM_FLAG_LT |
Less Than Flag: Set if comparison result is strictly less than. |
Bit 2 |
GT | IMPULSE_VM_FLAG_GT |
Greater Than Flag: Set if comparison result is strictly greater than. |
Bit 3 |
EQ | IMPULSE_VM_FLAG_EQ |
Equal Flag: Set if comparison result is equal. |
Bit 4 |
ST | IMPULSE_VM_FLAG_ST |
Stable Flag: Set by convergence check operations. |
2.4 Register Type Tags
To ensure off-heap memory safety and prevent undefined behavior during FFI calls, the VM MUST perform strict dynamic type validation using the following 8-bit type tags:
| Value | Type Identifier | Register Type Description |
|---|---|---|
0x00 |
TYPE_NULL |
Empty, uninitialized, or invalid register state. |
0x01 |
TYPE_INT64 |
64-bit signed or unsigned integer value. |
0x02 |
TYPE_NODE_ID |
64-bit unsigned unique node identifier. |
0x03 |
TYPE_RELATION_ID |
16-bit unsigned relationship identifier. |
0x04 |
TYPE_BITSET_HANDLE |
Integer handle pointing to an off-heap BitSet. |
0x05 |
TYPE_NODE_VECTOR |
Integer handle pointing to an off-heap node array. |
0x06 |
TYPE_CSR_SPAN |
Direct memory span pointer matching CSR slice. |
0x07 |
TYPE_BOOLEAN |
Boolean flag (0 = false, 1 = true). |
0x08 |
TYPE_FLOAT |
32-bit IEEE 754 single-precision float constant. |
0x09 |
TYPE_DOUBLE |
64-bit IEEE 754 double-precision float constant. |
0x0A |
TYPE_VALUE_MAP |
Integer handle pointing to an off-heap hash map. |
0x0B |
TYPE_STRING_VECTOR |
Integer handle pointing to an off-heap string array. |
0x0C |
TYPE_FLOAT_VECTOR |
Integer handle pointing to an off-heap float array. |
0x0D |
TYPE_DOUBLE_VECTOR |
Integer handle pointing to an off-heap double array. |
0x0E |
TYPE_UINT64_VECTOR |
Integer handle pointing to an off-heap uint64 array. |
0x0F |
TYPE_FRONTIER_STATE |
Integer handle pointing to a frontier with attached per-node state. |
0x10 |
TYPE_LANE_FRONTIER |
Integer handle pointing to a pooled multi-lane 8/16/32/64-bit bit-sliced frontier buffer (uint8_t[N]..uint64_t[N]) with optional counterfactual edge trip masks (v0.10.0). |
3. Physical Layout Specifications
3.1 VM Execution State Frame (impulse_vm_state_t)
The execution state frame MUST represent a contiguous 640-byte memory block, aligned to a 64-byte boundary. The fields are defined as follows:
| Byte Offset | C-ABI Type | Field Name | Description |
|---|---|---|---|
0x0000 – 0x0003 |
uint32_t |
pc |
Program Counter offset. |
0x0004 – 0x0007 |
uint32_t |
reserved |
Alignment padding (MUST be 0). |
0x0008 – 0x000F |
uint64_t |
flags |
Lower status flags register. |
0x0010 – 0x020F |
uint64_t[64] |
registers |
64-bit general-purpose registers R0..R63. |
0x0210 – 0x024F |
uint8_t[64] |
register_types |
Associated type tags for R0..R63. |
0x0250 – 0x0257 |
void* |
query_context |
Pointer to off-heap execution context. |
0x0258 – 0x0277 |
uint32_t[8] |
call_stack |
8-frame subroutine return stack. |
0x0278 – 0x027B |
uint32_t |
call_stack_depth |
Subroutine return stack pointer / depth. |
0x027C – 0x027F |
uint32_t |
reserved2 |
Aligns struct to 640-byte boundary. |
3.2 8-Byte Packed Instruction Layout (impulse_instruction_t)
Every executable instruction MUST be packed into exactly 8 bytes (64 bits), structured as:
| Byte Offset | Field Name | Type | Semantic Role |
|---|---|---|---|
0x00 |
opcode |
uint8_t |
The impOps bytecode opcode identifier (0x00..0xFE). |
0x01 |
flags |
uint8_t |
Instruction modifiers (see §3.3). |
0x02 – 0x03 |
dst_reg |
uint16_t |
Destination register index (0..63). |
0x04 – 0x07 |
payload |
uint32_t |
Operands, constants, offsets, or jump addresses. |
3.2.1 16-Byte Extended Instruction Layout (128 bits)
If the instruction requires more than a 32-bit payload (e.g., loading a full 64-bit constant, or utilizing more than 3 source operands with 16-bit register IDs), it MAY use the 128-bit Extended Instruction format. This is dynamically signaled by setting Bit 7 (FLAG_EXTENDED) in the instruction flags.
When the VM decodes FLAG_EXTENDED, it MUST automatically consume the immediately following 64-bit slot in the instruction stream as extended payload, advancing the Program Counter by 2.
To maintain runtime security against invalid branches into the middle of a 128-bit instruction, the second 64-bit word MUST begin with the reserved tombstone opcode 0xFF (OP_EXTENSION_PAYLOAD), followed by a 0x00 padding byte to ensure flawless 16-bit and 32-bit memory alignment for the remaining 48 bits.
| Word | Byte Offset | Field Name | Type | Semantic Role |
|---|---|---|---|---|
| Word 1 | 0x00 |
opcode |
uint8_t |
Base operation opcode (0x00..0xFE). |
0x01 |
flags |
uint8_t |
Modifiers, including FLAG_EXTENDED (0x80). |
|
0x02 – 0x03 |
dst_reg |
uint16_t |
Destination register index. | |
0x04 – 0x05 |
arg1 |
uint16_t |
First extended 16-bit source argument. | |
0x06 – 0x07 |
arg2 |
uint16_t |
Second extended 16-bit source argument. | |
| Word 2 | 0x08 |
ext_marker |
uint8_t |
MUST be 0xFF (OP_EXTENSION_PAYLOAD). |
0x09 |
padding |
uint8_t |
MUST be 0x00 (Alignment padding). |
|
0x0A – 0x0B |
arg3 |
uint16_t |
Third extended 16-bit source argument. | |
0x0C – 0x0D |
arg4 |
uint16_t |
Fourth extended 16-bit source argument. | |
0x0E – 0x0F |
arg5 |
uint16_t |
Fifth extended 16-bit source argument. |
Note: For operations requiring a 32-bit integer immediate offset in the extension word, the VM backend MAY cast arg4 and arg5 (bytes 0x0C–0x0F) as a single perfectly-aligned 32-bit uint32_t via an anonymous union.
3.3 Instruction Modifier Flags
The flags byte in the instruction structure (impulse_vm.h:38-42) is a bitmask defined as:
Bit 0(0x01/IMPULSE_VM_OP_FLAG_HALT_ON_EMPTY/IMPULSE_INST_FLAG_HALT_ON_EMPTY,[early-exit]): Early-exit flag. Jump to halt (IMPULSE_VM_OK) immediately if the output frontier BitSet is empty.Bit 1(0x02/IMPULSE_VM_OP_FLAG_INPUT_SEED/IMPULSE_INST_FLAG_INPUT_SEED,[seed-inlined]): Seed-inlined flag. Indicates the traversal source is the query input seed node parameter rather than a register handle.Bit 2(0x04/IMPULSE_VM_OP_FLAG_ACCUMULATE): Accumulate flag. Instructs the VM to accumulate (union) results into the destination register rather than overwriting (0x04–0x80reserved in baseline traversal disassemblers).Bit 3(0x08/IMPULSE_VM_OP_FLAG_INVERT): Invert flag. Negates conditions, filters, or set tests.Bit 4(0x10/IMPULSE_VM_OP_FLAG_OFFHEAP): Off-heap flag. Explicitly forces off-heap memory evaluations.Bits 5..6(0x20–0x40): Reserved (0x00).Bit 7(0x80/IMPULSE_VM_OP_FLAG_EXTENDED): Extended format flag. Instructs the VM to decode the current instruction and the subsequent 64-bit block as a single 128-bitSafeExtendedInstruction.
4. VM Lifecycle and FFI API Requirements
The native engine library MUST export standard C-linkage FFI methods to interact with VM contexts and query states. The FFI boundary MUST support the following operations:
impulse_vm_context_create(const impulse_snapshot_t* snapshot): Allocates and pre-indexes an execution context.impulse_vm_context_destroy(impulse_vm_context_t* ctx): Safely deallocates all off-heap arenas.impulse_vm_context_acquire_bitset(impulse_vm_context_t* ctx): Returns a free BitSet slot handle index.impulse_vm_context_release_bitset(impulse_vm_context_t* ctx, size_t handle): Clears and frees a BitSet handle for reuse.impulse_vm_context_acquire_lane_frontier(impulse_vm_context_t* ctx)&impulse_vm_context_release_lane_frontier(impulse_vm_context_t* ctx, size_t handle): Acquires and releases pooledTYPE_LANE_FRONTIER(0x10) slots in the VM context (v0.10.0), paired with C-ABI inspection accessorsimpulse_vm_context_lane_frontier_num_lanes(ctx, handle),impulse_vm_context_lane_frontier_width(ctx, handle),impulse_vm_context_lane_frontier_active_mask(ctx, handle),impulse_vm_context_lane_frontier_node_count(ctx, handle), andimpulse_vm_context_lane_frontier_data(ctx, handle).
5. Null Safety and Validity Semantics
The Impulse Graph Engine supports nullable attributes via 128-byte aligned Validity Bitmaps (as defined in the physical format schema, where Bit 7 of the attribute type code is set to 1). When executing operations that read or interact with nullable attributes, the VM MUST strictly adhere to the following null safety semantics:
5.1 Filters and Comparisons
When evaluating predicate opcodes (e.g., OP_NODE_FILTER, OP_NODE_FILTER_STR_PREFIX, OP_CSR_WALK_FILTERED, OP_VEC_CMP_EQ):
- If the attribute validity bit for an element is
0(null), the comparison MUST immediately evaluate tofalse. - Nulls are considered unknown states.
NULL == NULLevaluates tofalse, andNULL != VALUEevaluates tofalse. - If the
INVERTflag is set on the instruction, null elements MUST STILL evaluate tofalse. An inverted filter returns all valid elements that do not match the condition; it MUST NOT return null elements.
5.2 Aggregations and Reductions
When evaluating reduction opcodes (e.g., OP_CSR_WALK_REDUCE_SUM, OP_REDUCE, OP_EWISE_REDUCE_MIN, OP_EWISE_REDUCE_MAX):
- Skip Semantics: Aggregators MUST skip (ignore) elements where the validity bit is
0. - For example,
OP_CSR_WALK_REDUCE_SUMover weights[5.0, NULL, 3.0]yields8.0. OP_SET_CARDINALITYor counting reductions over[A, NULL, B]yields2.- Empty/Null State: If a reduction operates entirely over null values (or an empty set), the VM MUST set the
ZF(Zero Flag) to1and set the destination register to a default empty value (e.g.,0for sums,MAX_INTfor mins,MIN_INTfor maxes).
5.3 Element-Wise Vector Algebra
When evaluating vector math opcodes (e.g., OP_EWISE_ADD, OP_EWISE_MULT, OP_VEC_MATH_TERNARY):
- Poison / Propagation Semantics: If any source element in a vector operation is null (validity bit is
0), the resulting vector element MUST also be marked as null. - For example,
[5.0, NULL, 2.0] + [1.0, 1.0, 1.0] = [6.0, NULL, 3.0]. - The destination register containing the resulting vector (
TYPE_FLOAT_VECTOR, etc.) MUST have an associated validity bitmap allocated in the VM Context if any source vector was nullable.
5.4 Gather and Indirect Loads
When evaluating OP_GATHER_NODE_ATTR, OP_GATHER_EDGE_ATTR, or OP_LOAD_INDIRECT:
- If the target attribute is schema-defined as nullable, the VM MUST load and bind both the data span and the validity bitmap span to the resulting vector register handle. Any downstream opcodes interacting with that register will then correctly apply the semantics from §5.1, §5.2, or §5.3.
6. impOps Instruction Set Reference
The VM MUST execute bytecode instructions matching the opcode values and rules listed below. If an instruction executes with invalid registers, type mismatches, or out-of-bounds parameters, the VM MUST halt execution and return the appropriate impulse_vm_status_t error.
6.1 Setup and Input Instructions
OP_HALT(0x00)- Behavior: Stop virtual machine execution. Return execution status
IMPULSE_VM_OK. OP_NOP(0x01)- Behavior: Increment
pc. Do nothing. OP_INIT_INPUT_NODE(0x02)- Behavior: Copy the single scalar query parameter Node ID into
dst_reg. - Type Transition:
dst_regtype tag MUST becomeTYPE_NODE_ID. OP_INIT_INPUT_SET(0x03)- Behavior: Fetch input parameters, populate a new off-heap BitSet, and store its handle in
dst_reg. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_LOAD_CONST_INT(0x04)- Behavior: Load a 64-bit integer into
dst_reg. If theOFFHEAPmodifier is set, the payload represents a pointer or offset; otherwise, it is loaded directly. - Type Transition:
dst_regtype tag MUST becomeTYPE_INT64. OP_MAP_KEYS_TO_DENSE(0x05)- Behavior: Maps external keys to continuous internal node indices.
- Usage: Expects
input_param(via FFI query parameter) containing a pointer to a structimpulse_vm_input_keyswith external string or integer keys. It matches these keys against the primary key attribute array of the domain specified bydomain_id(retrieved frompayload & 0xFFFF). Matches are populated into a BitSet. To check if a key catalog mapping exists for the domain prior to mapping, the VM SHOULD first executeOP_HAS_KEY_CATALOG(0x1C). - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. Setsflags[ZF]if the resulting BitSet is empty. OP_LOAD_CONST_FLOAT(0x06)- Behavior: Load a 32-bit single-precision float into
dst_reg. - Type Transition:
dst_regtype tag MUST becomeTYPE_FLOAT. - Note: The instruction payload is constrained to 32 bits. To load 64-bit float constants (doubles), the constants MUST be loaded indirectly from attribute arrays, vector slices, or local scratch memory using
OP_LOAD_INDIRECT, or loaded from inline float64 tables. OP_LOAD_CONST_STR_PREFIX(0x07)- Behavior: Load a string prefix reference index from the instruction payload into
dst_reg. - Type Transition:
dst_regtype tag MUST becomeTYPE_INT64. - Note: Since prefix string constants are stored in the Shared String Table, the register stores a 64-bit integer index/offset pointing to the string pool, not a string array handle.
OP_LOAD_INLINE_ARRAY(0x08)- Behavior: Load floats from the inline metadata data binding into a vector register.
- Usage: Expects a bound inline metadata buffer on the thread-local query context. It reads
count(upper 16 bits of payload) float values starting atoffset_bytes(lower 16 bits of payload) and copies them into a newly acquired float vector register. - Type Transition:
dst_regtype tag MUST becomeTYPE_FLOAT_VECTOR. OP_INIT_MOCK_GRAPH(0x09)- Behavior: Configures a mock relation slot in the VM context using inline bytecode data.
- Usage: Sets up relation slot
slot_id(specified bydst_reg) using raw row offsets and column targets from the inline data binding at byte offsetoff_bytes(lower 16 bits of payload) with node countnode_count(upper 16 bits of payload). - Note: The "mock graph" refers to a virtual, inline adjacency matrix defined directly in the thread context's inline bytecode data stream (rather than loaded from a physical
.impssnapshot file). This is used primarily for isolated assembly unit testing of traversal opcodes. - Outcome: Bypasses the need to mmap a physical
.impssnapshot file. Does not modify register values. OP_LOAD_INLINE_SET(0x0A)- Behavior: Load an inline BitSet from the inline metadata data stream into
dst_reg. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_INIT_MOCK_NODE_ATTR(0x0B)- Behavior: Initialize mock node attribute slot using inline bytecode data.
OP_INIT_MOCK_EDGE_ATTR(0x0C)- Behavior: Initialize mock edge attribute slot using inline bytecode data.
6.2 Traversal and Filter Instructions
All Walk-based traversal instructions (OP_CSR_WALK, OP_CSR_WALK_FILTERED, OP_CSC_WALK, OP_CSR_WALK_2HOP, OP_CSR_WALK_STATE) follow a common execution behavior:
- Frontier Evaluation & Flag Behavior: If the source nodes frontier is empty (contains no active node IDs), or if the traversal result set is empty, the VM MUST set the Zero Flag (
ZF) to 1 in theflagsregister. Otherwise,flags[ZF]MUST be cleared (set to 0). - BitSet Materialization: By default, Walk opcodes allocate a new off-heap BitSet handle in
dst_reg. If theACCUMULATEmodifier flag is set on the instruction, the result set is unioned directly into the existing BitSet indst_regwithout deallocation. - Valid Filters and Reductions:
- Filters: Filter-based opcodes (
OP_NODE_FILTER,OP_NODE_FILTER_STR_PREFIX,OP_CSR_WALK_FILTERED) check scalar values or prefix matching against attributes loaded from the snapshot's Structure-of-Arrays (SoA) attribute pools. These are mapped into the query context'sattribute_slots[rel_id][attr_id]during initialization. -
Reducers: Reductions (
OP_CSR_WALK_REDUCE_SUM,OP_CSR_WALK_REDUCE,OP_REDUCE) aggregate values over the traversed frontier. Valid reducers are defined by GraphBLAS binary operator IDs (e.g.,BINARY_OP_ADD,BINARY_OP_MUL). -
OP_CSR_WALK_2HOP(0x0E) - Behavior: Two-hop fused CSR walk traversing two consecutive relations in a single vectorized pass.
- Type Requirements: Source nodes register
srcMUST beTYPE_BITSET_HANDLEorTYPE_NODE_ID. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_CSR_WALK_STATE(0x0F)- Behavior: State-propagating CSR walk updating attached node frontier state vectors.
- Type Requirements: Source nodes register
srcMUST beTYPE_BITSET_HANDLEorTYPE_NODE_ID. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_CSR_WALK(0x10)- Behavior: Traverse relationship edges using Compressed Sparse Row topology. Takes source nodes from
src(lower 16 bits of payload), follows the relationrel(upper 16 bits of payload), and writes target nodes intodst_reg. - Usage: If
srccontains a BitSet handle or single Node ID, it retrieves offsets and column targets from relation slotreland performs a union of targets intodst_reg. RespectsACCUMULATEmodifier flag to append targets. - Type Requirements: Source nodes register
srcMUST beTYPE_BITSET_HANDLEorTYPE_NODE_ID. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_CSR_WALK_FILTERED(0x11)- Behavior: Walk CSR applying attribute filter constraints.
- Usage: Performs a CSR walk over relation
relfrom sourcesrcwhile validating a filter condition on edge or target node attributes. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_CSR_DEGREE(0x12)- Behavior: Computes the degree of specified nodes.
OP_CSR_WALK_PREDICATE(0x13)- Behavior: Walk CSR and evaluate boolean predicate.
OP_NODE_FILTER(0x14)- Behavior: Filter node identifiers using an attribute constraint.
- Usage: Evaluates the condition
attr[u] == registers[val_reg]for each nodeuinsrc. Attributes are pre-configured invm_state->query_context->attribute_slots[rel_id][attr_id], which are resolved from target snapshot Structure-of-Arrays (SoA) attribute blocks (withsrc=payload & 0xFF,val_reg=(payload >> 8) & 0xFF,attr_id=(payload >> 16) & 0xFF,rel_id=(payload >> 24) & 0xFF). - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_NODE_FILTER_STR_PREFIX(0x15)- Behavior: Filter nodes using a string prefix matching condition.
OP_CSR_WALK_REDUCE_SUM(0x16)- Behavior: Walk CSR and calculate reduction sum.
- Note: This opcode is specialized strictly for summation reductions. By hardcoding the float addition (
+=) and optional multiply-by-weight logic directly in the inner loop body without conditional branching, it enables aggressive compiler auto-vectorization (e.g., Fused Multiply-Add SIMD instructions) and delivers maximum execution performance. OP_CSR_WALK_REDUCE(0x17)- Behavior: Walk CSR and evaluate reduction logic.
- Note: This opcode is a generalized reduction operation that dynamically evaluates the operator (e.g.,
0= Minimum,1= Maximum) specified byreduce_op((payload >> 8) & 0xFF) via conditional branch evaluations inside the traversal loops. The branch checking overhead prevents auto-vectorization, resulting in lower execution throughput compared to the specialized0x16opcode. OP_CSC_WALK(0x18)- Behavior: Traverse relationship edges backwards using Compressed Sparse Column topology.
- Type Requirements: Source nodes register MUST be
TYPE_BITSET_HANDLEorTYPE_NODE_ID. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_HAS_CSR(0x19)- Behavior: Verify if relation has a CSR layout. Sets
flags[EQ]accordingly. OP_HAS_CSC(0x1A)- Behavior: Verify if relation has a CSC layout. Sets
flags[EQ]accordingly. OP_HAS_COO(0x1B)- Behavior: Verify if relation has a COO layout. Sets
flags[EQ]accordingly. OP_HAS_KEY_CATALOG(0x1C)- Behavior: Verify if domain catalog exists. Sets
flags[EQ]accordingly. OP_ADAPTIVE_WALK(0x1D)- Behavior: Dynamically select CSR vs COO traversal strategy based on frontier density.
- Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_CREATE_SCRATCH_INDEX(0x1E)- Behavior: Allocate a temporary scratch index for hash joins or traversal acceleration.
OP_DROP_SCRATCH_INDEX(0x1F)- Behavior: Deallocate a temporary scratch index.
6.3 Vector Predicates, SIMD Masks, and Set Mathematics Instructions
6.3.1 Vector Predicates, SIMD Masks, and Math (0x20 - 0x2F)
OP_VEC_CMP_EQ(0x20)- Behavior: Vector element-wise equality comparison returning BitSet mask of matching node IDs.
- Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. Setsflags[ZF]if result is empty. OP_VEC_CMP_GT(0x21)- Behavior: Vector element-wise greater-than comparison returning BitSet mask of matching node IDs.
- Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. Setsflags[ZF]if result is empty. OP_VEC_CMP_LT(0x22)- Behavior: Vector element-wise less-than comparison returning BitSet mask of matching node IDs.
- Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. Setsflags[ZF]if result is empty. OP_VEC_CMP_BETWEEN(0x23)- Behavior: Vector range inclusion comparison returning BitSet mask of nodes within
[low, high]. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. Setsflags[ZF]if result is empty. OP_MASK_AND(0x24)- Behavior: Bitwise AND of two SIMD masks / BitSets.
- Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_MASK_OR(0x25)- Behavior: Bitwise OR of two SIMD masks / BitSets.
- Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_MASK_NOT(0x26)- Behavior: Bitwise NOT (inversion) of a SIMD mask / BitSet up to active domain cardinality.
- Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_VEC_BLEND(0x27)- Behavior: Element-wise blend of two vector registers selected by a BitSet condition mask.
OP_ASSERT_FINITE(0x2A)- Behavior: Asserts that target numerical register or vector elements are finite (non-NaN, non-Inf). Throws
IMPULSE_VM_ERR_FLOATING_POINTif non-finite. OP_VEC_MATH_UNARY(0x2D)- Behavior: Vectorized unary transcendental/algebraic mathematical evaluation (e.g.,
exp,log,sqrt,abs). OP_VEC_MATH_BINARY(0x2E)- Behavior: Vectorized binary transcendental/algebraic mathematical evaluation (e.g.,
pow,atan2,hypot). OP_VEC_MATH_TERNARY(0x2F)- Behavior: Vectorized ternary fused mathematical evaluation (e.g.,
lerp, fused multiply-addfma).
6.3.2 Set Mathematics and Algebra Instructions (0x30 - 0x3D)
Set math and algebraic instructions are classified based on the number and structure of their operands:
- Unary Set Operations: Operations that accept a single source register (e.g.
OP_SET_CARDINALITY) and write todst_reg. - Binary Set Operations: Operations that combine two source registers (e.g.
OP_SET_UNION,OP_SET_INTERSECT,OP_SET_DIFFERENCE). For these, the first source register (src1) is specified in the lower 16 bits of the payload, and the second source register (src2) is specified in the upper 16 bits of the payload. The output is written todst_reg(transitioning it toTYPE_BITSET_HANDLE). - Vector-to-Vector (EWise) Operations: Element-wise vector algebra (e.g.
OP_EWISE_ADD,OP_EWISE_MULT) acting on float, double, or integer arrays. -
Vector-to-Scalar Reductions: Operations (e.g.
OP_VECTOR_REDUCE_SUM) that accumulate vector elements into a scalar destination register. -
OP_SET_UNION(0x30) - Behavior: Union bitset arrays from two source registers.
- Type Requirements: Source registers MUST be
TYPE_BITSET_HANDLE. OP_SET_INTERSECT(0x31)- Behavior: Intersect bitset arrays from two source registers.
- Type Requirements: Source registers MUST be
TYPE_BITSET_HANDLE. OP_SET_DIFFERENCE(0x32)- Behavior: Subtract second register bitset from the first register bitset.
- Type Requirements: Source registers MUST be
TYPE_BITSET_HANDLE. OP_SET_CARDINALITY(0x33)- Behavior: Compute population count of BitSet. Writes count to
dst_reg. - Type Transition:
dst_regtype tag MUST becomeTYPE_INT64. OP_VECTOR_MUL_ATTR(0x34)- Behavior: Element-wise multiplication of vector and attribute arrays.
OP_VECTOR_REDUCE_SUM(0x35)- Behavior: Compute sum of elements in a vector register.
OP_VECTOR_DIV(0x36)- Behavior: Element-wise division.
OP_VECTOR_STR_CONCAT(0x37)- Behavior: Join vector string fields.
OP_FLOAT_VECTOR_SCALE(0x38)- Behavior: Perform float vector scaling operation.
OP_L1_NORM_DIFF(0x39)-
Behavior: Calculate L1 Norm of differences between vectors.
-
OP_PROJECT_STATE(0x3A) - Behavior: Projects or mutates attached node state in-place across the active frontier (
state' = f(state, attr)). OP_COALESCE(0x3B)- Behavior: Coalesces a nullable vector into a dense vector by replacing null elements with a fallback value.
- Usage: Expects
dst_reg,src_reg(nullable vector), and a fallback loaded in a third register (specified in the payload). Replaces elements where validity bit is0with the fallback value. The resultingdst_regvector MUST NOT have a validity bitmap. OP_EXTRACT_VALIDITY(0x3C)- Behavior: Extracts the validity bitmap of a nullable vector as a BitSet.
- Usage: Expects
dst_regandsrc_reg(the nullable vector). Ifsrc_regis nullable, creates a BitSet handle indst_regwrapping the validity bitmap (yielding an \(O(1)\)IS NOT NULLmask). Ifsrc_regis not nullable, returns a BitSet containing all1s for the length of the vector. - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE. OP_VECTOR_TIME_VALID_AT(0x3D)- Behavior: Evaluates temporal bounds to determine which elements are active at a given timestamp.
- Usage: Expects
dst_regandts_reg. Thets_regcan dynamically contain either a scalar timestamp (TYPE_INT64) or a vector of timestamps (TYPE_UINT64_VECTOR/TYPE_NODE_VECTOR) evaluated element-wise. It requires the 128-bit Extended Instruction format to specifyrel_id(upper 16 bits of base payload),attr_id_start(lower 16 bits of extension word), andattr_id_end(upper 16 bits of extension word). Returns a BitSet containing all target nodes whereattr_start <= ts_val < attr_end. If an attribute bound is missing/null, it is treated as open (infinity). - Type Transition:
dst_regtype tag MUST becomeTYPE_BITSET_HANDLE.
6.4 GraphBLAS and Matrix Instructions
OP_CC_AFFOREST(0x40)- Behavior: Component step in Afforest algorithm.
OP_MXV(0x41)- Behavior: Multiply adjacency matrix by a vector using GraphBLAS semirings.
OP_VXM(0x42)- Behavior: Multiply vector by adjacency matrix using GraphBLAS semirings.
OP_EWISE_ADD(0x43)- Behavior: Element-wise addition.
OP_EWISE_MULT(0x44)- Behavior: Element-wise multiplication.
OP_REDUCE(0x45)- Behavior: Reduce matrix rows/columns.
OP_CC_HOOK_COMPRESS(0x46)- Behavior: Tree compress operation.
OP_TC_SWEEP_BATCH(0x47)- Behavior: Parallel batch sweep for Triangle Counting.
OP_BRANDES_FORWARD(0x48)- Behavior: Brandes betweenness centrality forward traversal.
OP_BRANDES_BACKWARD(0x49)- Behavior: Brandes betweenness centrality dependency accumulation.
OP_DELTA_STEP_RELAX(0x4A)- Behavior: Relaxes shortest path distance boundaries.
OP_READ_EDGE_WEIGHT(0x4B)- Behavior: Reads weight value associated with edge offset.
6.5 Control Flow and Branching Instructions
OP_JMP(0x50)- Behavior: Set program counter
pcto execution offset in payload. OP_JZ(0x51)- Behavior: If
flags[ZF]is set to 1, setpcto payload execution offset. OP_JNZ(0x52)- Behavior: If
flags[ZF]is set to 0, setpcto payload execution offset. OP_LOOP_DECR(0x53)- Behavior: Decrement
dst_reg(which MUST beTYPE_INT64). If result > 0, setpcto payload execution offset. OP_STABLE_CHECK(0x54)- Behavior: Check convergence between two set states. Sets
flags[ST]if converged. OP_CALL(0x55)- Behavior: Save current
pcto subroutine stack, then setpcto payload execution offset. - Constraint: If call stack pointer exceeds depth limits, return
IMPULSE_VM_ERR_STACK_OVERFLOW. OP_RET(0x56)- Behavior: Pop caller PC from subroutine stack and set
pc. - Constraint: If call stack is empty, return
IMPULSE_VM_ERR_STACK_UNDERFLOW. OP_ENTER_FRAME(0x57)- Behavior: Allocate a new execution stack frame with the frame size specified in
dst_reg. OP_LEAVE_FRAME(0x58)- Behavior: Tear down the active execution stack frame.
OP_THROW(0x5A)- Behavior: Stop execution and return custom runtime exception status. Writes the exception payload directly into
R0as aTYPE_INT64. - Outcome: Returns status
IMPULSE_VM_ERR_USER_THROW(7). OP_ASSERT(0x5B)- Behavior: Verify invariant condition on register values or flags. If check fails, return
IMPULSE_VM_ERR_ASSERTION_FAILED(8). OP_TRAP(0x5C)- Behavior: Interrupt execution context and invoke registered debugger hooks. Returns
IMPULSE_VM_ERR_TRAP(9).
Instruction Gas / Fuel Enforcement (
IMPULSE_VM_ERR_GAS_EXHAUSTED): Instruction gas exhaustion is a VM runtime status code rather than an instruction opcode. When an execution loop or query exceeds its configured instruction fuel / gas budget inimpulse_vm_context_t(impulse_vm_context_set_fuel), the VM halts execution safely and returns status codeIMPULSE_VM_ERR_GAS_EXHAUSTED(13/0x0D).
6.6 Extended Operations
OP_SAMPLE_NEIGHBORS(0x60)- Behavior: Perform neighbor sampling (GNN target).
OP_RANDOM_WALK(0x61)- Behavior: Perform node random walk traversals.
OP_SCATTER_GATHER(0x62)- Behavior: Gather attributes from neighbors and scatter to state vectors.
OP_REBAC_CHECK(0x63)- Behavior: Relationship-Based Access Control Zanzibar check path evaluation.
OP_ROARING_BITMAP_AND(0x64)- Behavior: Compute logical AND on compressed roaring bitmap structures.
OP_ISLAND_DETECT(0x65)- Behavior: Power grid component island traversal.
OP_SPARSE_MATVEC(0x66)- Behavior: Compute sparse matrix-vector product.
OP_LOUVAIN_MODULARITY(0x67)- Behavior: Louvain community clustering modularity optimization step.
OP_KCORE_DECOMPOSITION(0x68)- Behavior: Node k-core graph shell decomposition.
OP_MOTIF_MATCH_3(0x69)- Behavior: Search and list 3-node motifs/subgraphs.
OP_GRAPH_ISOMORPHISM(0x6A)- Behavior: Compare structure topology similarity.
OP_ROARING_BITMAP_OR(0x6B)- Behavior: Bitwise logical OR on roaring bitmaps.
OP_ROARING_BITMAP_AND_NOT(0x6C)- Behavior: Bitwise logical AND-NOT subtraction on roaring bitmaps.
6.7 Registers and Memory Management Instructions
OP_MOV(0x70)- Behavior: Copy value and type tag from source register (payload) into
dst_reg. OP_CLEAR_REG(0x71)- Behavior: Set
dst_regvalue to 0 and type tag toTYPE_NULL. OP_LOAD_INDIRECT(0x72)- Behavior: Load value into
dst_regfrom address located in source register. OP_ALLOC_SCRATCH(0x73)- Behavior: Allocate local thread-private memory chunk.
OP_ASSERT_SCRATCH_BYTES(0x74)- Behavior: Assert scratch space matches bounds constraints.
OP_SET_MAX_DOP(0x75)- Behavior: Set concurrency limits (maximum degree of parallelism) for multi-threaded opcodes.
6.8 Materialization, Columnar Gather, and Multi-Layout Walk Instructions
OP_LOAD_COLUMN_VECTOR(0x80),OP_GATHER_NODE_ATTR(0x81),OP_GATHER_EDGE_ATTR(0x82),OP_BRIN_ZONE_SKIP(0x83)- Behavior: Direct columnar attribute vector loads, indirect node/edge attribute gathers over active frontiers, and 2-tier BRIN / Zone Map block skipping.
OP_CSR_WALK_DIRECT_STORE(0x84),OP_CSR_WALK_DENSE_STREAM(0x85),OP_COO_WALK(0x86),OP_CSC_WALK_DIRECT_STORE(0x87),OP_FIXPOINT_KLEENE_STAR(0x88),OP_SWAP_REG(0x89),OP_FRONTIER_DIFF(0x8A),OP_COO_WALK_FILTERED(0x8B),OP_COO_WALK_REDUCE(0x8C),OP_COO_WALK_DIRECT_STORE(0x8D),OP_DENSE_WALK(0x8E),OP_DENSE_WALK_BITMATRIX(0x8F)- Behavior: Multiplicity-specialized direct-store walks (\(1:N\), \(N:1\), \(1:1\)), COO/Dense bit-matrix sweeps, in-place register swapping (
OP_SWAP_REG), frontier delta extraction (OP_FRONTIER_DIFF), and fused Kleene-star fixpoint loops. OP_COLLECT_BITSET(0x90)- Behavior: Materialize target BitSet items into caller array buffer.
OP_COLLECT_ARRAY(0x91)- Behavior: Copy values from node vector register into client memory.
OP_MAP_DENSE_TO_KEYS(0x92)- Behavior: Resolve dense offsets into user domain key formats.
OP_COLLECT_VALUE_MAP(0x93)- Behavior: Materialize map keys/values into FFI structs.
OP_DENSE_WALK_REDUCE(0x94),OP_DENSE_WALK_DIRECT_STORE(0x95)- Behavior: Monoidal reduction and injective direct-store fast paths over dense bit-matrix relations.
6.9 Reserved Opcodes
The following unallocated opcode ranges in 0x00–0xFF are strictly reserved in impulse_vm.h:
OP_RESERVED_0D(0x0D)OP_RESERVED_28throughOP_RESERVED_29(0x28–0x29) andOP_RESERVED_2BthroughOP_RESERVED_2C(0x2B–0x2C)OP_RESERVED_3EthroughOP_RESERVED_3F(0x3E–0x3F;0x3A–0x3Dare allocated toOP_PROJECT_STATE,OP_COALESCE,OP_EXTRACT_VALIDITY, andOP_VECTOR_TIME_VALID_AT)OP_RESERVED_4CthroughOP_RESERVED_4F(0x4C–0x4F)OP_RESERVED_59(0x59)OP_RESERVED_5DthroughOP_RESERVED_5F(0x5D–0x5F)OP_RESERVED_6DthroughOP_RESERVED_6F(0x6D–0x6F)OP_RESERVED_76throughOP_RESERVED_7F(0x76–0x7F;0x80–0x8Fare allocated to columnar gather and multiplicity fast-path opcodes)OP_RESERVED_96throughOP_RESERVED_9F(0x96–0x9F;0x90–0x95are allocated to output materialization and dense walk opcodes)OP_RESERVED_CCthroughOP_RESERVED_FE(0xCC–0xFE;0xA0–0xBFare allocated to §6.10 Edge Stream Shader instructions,0xC0–0xCBare allocated inv0.10.0to §6.11 Multi-Lane Bit-Sliced Execution & Hybrid Vector ANN instructions, and0xFFis reserved for the 128-bitOP_EXTENSION_PAYLOADmarker per §3.2.1)- Behavior: Execution of any reserved opcode MUST immediately halt virtual machine execution and return the status
IMPULSE_VM_ERR_RESERVED_OPCODE(10).
6.10 Edge Stream Shader Instructions (0xA0 - 0xBF)
Edge Stream Shaders enable execution of inline Common Expression Language (CEL) pipelines, per-edge predicates, and mathematical reductions natively during graph traversal loops without manifesting intermediate buffers.
OP_COO_WALK_STREAM(0xA0),OP_CSR_WALK_STREAM(0xA9),OP_CSC_WALK_STREAM(0xAA)- Behavior: Executes an edge shader pipeline over an adjacency matrix (COO, CSR, or CSC respectively).
- Usage: Expects
dst_reg(the graph/relation handle loaded viaOP_INIT_MOCK_GRAPHor similar),src_reg(source vector or node set passed inpayload_low),rel_id(relationship ID inpayload_high), andflagscontaining theshader_pc(the instruction index where the shader pipeline begins). OP_STREAM_FUNC_BEGIN(0xA1),OP_STREAM_FUNC_END(0xA2)- Behavior: Lexical delimiters defining the boundaries of an edge shader pipeline. The VM MUST ensure execution remains bounded within these markers.
OP_STREAM_LOAD_SRC(0xA3),OP_STREAM_LOAD_TGT(0xAB),OP_STREAM_LOAD_EDGE(0xA4)- Behavior: Loads data attributes associated with the current Source Node, Target Node, or Edge into a shader register (
S0-S15). - Usage:
dst_regpoints to the destination shader register. Payload indicates theattr_id. OP_STREAM_LOAD_SRC_ID(0xBA),OP_STREAM_LOAD_TGT_ID(0xBB),OP_STREAM_LOAD_EDGE_ID(0xBC)- Behavior: Loads the exact physical topological integer ID (source node ID, target node ID, or edge offset ID) as a float into the shader register.
OP_STREAM_LOAD_CONST(0xBD)- Behavior: Loads an inline scalar constant into a shader register.
- Usage:
dst_regis the target shader register. The 32-bit payload is interpreted dynamically as an exact IEEE-754 single-precision float (f32) bitcast. OP_STREAM_MATH_ADD(0xA5),SUB(0xAC),MUL(0xAD),DIV(0xA6),MOD(0xAE)- Behavior: Scalar binary math operations executed strictly between two shader registers.
- Usage:
dst_reg= Output.payload_low=src1.payload_high=src2. - Safety:
DIVandMODMUST adhere toSAFE_DIVsemantics (if the divisor is0.0, the result evaluates to0.0instead ofInfinityor trapping the VM). OP_STREAM_MATH_UNARY(0xAF)- Behavior: Maps standard scalar operations (trigonometric, exponential, algebraic, neural activations).
- Usage:
dst_reg= Output.payload_low=src.payload_high=func_id. Thefunc_idMUST strictly correlate to the canonical subset declared inimpulse_math_ops.h(e.g.0x01= ABS,0x02= SQRT,0x34= ISNAN). Out of domain bounds (e.g.SQRT(-1.0)) MUST yield an IEEE-754NaNpropagating natively without throwing an exception. OP_STREAM_CMP_EQ(0xB0),NEQ(0xB1),GT(0xB2),LT(0xB3)- Behavior: Binary comparison ops. Evaluate to
1.0if true,0.0if false. OP_STREAM_LOGIC_AND(0xB4),OR(0xB5),NOT(0xB6)- Behavior: Boolean logic ops evaluating on shader float values (
0.0= False, otherwise True). OP_STREAM_FILTER(0xA7)- Behavior: Evaluates a stream predicate (
0.0or1.0). If0.0, the shader pipeline unconditionally aborts for the current edge context, preventing further execution and skipping reductions. OP_STREAM_SELECT(0xB7)- Behavior: Ternary conditional select (multiplexer).
S[dst] = (S[cond] != 0.0) ? S[val] : S[dst]. OP_STREAM_REDUCE(0xA8)- Behavior: Accumulates a computed scalar result from the shader register bank back into a global vector register handle using a defined Monoid (
0 = SUM, 1 = MAX, 2 = MIN). OP_STREAM_REDUCE_ARGMIN(0xB8),OP_STREAM_REDUCE_ARGMAX(0xB9)- Behavior: Fuses topological reduction with index tracking, updating a global vector while capturing the node identifier that resulted in the extrema.
OP_STREAM_YIELD(0xBE)- Behavior: Emits the current target node ID
vinto the destination BitSet handle whenS[src]is non-zero (!= 0.0and!NaN). OP_STREAM_SCATTER_REDUCE(0xBF)- Behavior: Scatters and accumulates
S[src]intofloat_vector[v]using the specified monoid (0 = SUM, 1 = MAX, 2 = MIN).
6.11 Multi-Lane Bit-Sliced Execution & Hybrid Vector ANN Instructions (0xC0 - 0xCB) (v0.10.0)
Specification Versioning Note: Specification
v0.10.0freezes the baseline0x00..0xBFISA and activates the0xC0..0xCBinstruction block andTYPE_LANE_FRONTIER(0x10) register tag across all four polyglot engines.
Multi-Lane Bit-Sliced Execution generalizes single-bit frontier propagation (1 bit per node) into \(W\)-bit lane masks (\(W \in \{8, 16, 32, 64\}\) bits per node), enabling up to 64 independent traversals, counterfactual edge-outage contingencies, or concept-group expansions in a single memory-bandwidth-bound pass over the CSR/CSC topology.
6.11.1 TYPE_LANE_FRONTIER (0x10) Invariants
- Width Tier Selection: Given \(k \in [0, 64]\) active lanes, the physical lane width tier is
WIDTH_8(\(k \le 8\)),WIDTH_16(\(9 \le k \le 16\)),WIDTH_32(\(17 \le k \le 32\)), orWIDTH_64(\(33 \le k \le 64\)). - 64-Bit Safe Active Mask: The active lane bitmask MUST be computed without undefined 64-bit shift behavior (
1ULL << 64):
$\(\text{active\_mask}(k) = \begin{cases} 0 & \text{if } k \le 0 \\ \texttt{0xFFFFFFFFFFFFFFFF} & \text{if } k \ge 64 \\ (1 \ll k) - 1 & \text{if } 1 \le k < 64 \end{cases}\)$
- Strict Type Separation: Passing a
TYPE_BITSET_HANDLE(0x04) or scalar register to an opcode requiringTYPE_LANE_FRONTIER(0x10), or passing aTYPE_LANE_FRONTIERto a 1-bit set/walk opcode without an explicit bridge (OP_LANE_FILTER_QUORUM), MUST trap withIMPULSE_VM_ERR_INVALID_REGISTER(6). - Unused Upper Bits Invariant: For every node \(u \in [0, N)\),
(lanes[u] & ~active_mask) == 0MUST hold after every instruction.
6.11.2 Multi-Lane & Hybrid ANN Opcodes
OP_LANE_INIT_SEEDS(0xC0)- Behavior: Initializes a
TYPE_LANE_FRONTIERhandle indst_regby assigning up to 64 distinct seed nodes \(s_0, \dots, s_{k-1}\) to lanes \(b = 0 \dots k-1\) (lanes[s_b] |= (1ULL << b)). - Encoding:
src_reg = payload & 0xFFFF,k_or_dom = (payload >> 16) & 0xFFFF. - Allowed
src_regTypes:TYPE_NODE_VECTOR/TYPE_UINT64_VECTOR: Reads \(k = \min(64, \text{len})\) seed node IDs from the vector.TYPE_BITSET_HANDLE: Extracts the first \(k \le 64\) set bits in ascending node ID order.TYPE_NODE_ID/TYPE_INT64: Reads base seed \(s_0\); if(flags & 1) != 0andk_or_dom > 1, initializes \(k = \min(64, \text{k\_or\_dom})\) contiguous seeds \(s_0 + b\); otherwise initializes \(k = 1\) lane at \(s_0\).TYPE_NULL: Initializes \(k = \min(64, \text{k\_or\_dom} > 0 \text{ ? k\_or\_dom : } 8)\) lanes (if(flags & 1) != 0, seeds \(0 \dots k-1\); else seed \(0\) in lane \(0\)).
- Type Transition:
dst_regbecomesTYPE_LANE_FRONTIER. Setsflags[ZF] = 1iff alllanes[u] == 0. OP_LANE_INIT_GROUPS(0xC1)- Behavior: Initializes a
TYPE_LANE_FRONTIERhandle indst_regwhere multiple seed nodes may map to the same group/concept lane \(g \in [0, 63]\) (lanes[u] |= (1ULL << g)). - Encoding:
nodes_reg = payload & 0xFF,groups_reg = (payload >> 8) & 0xFF,num_groups = (payload >> 16) & 0xFFFF. - Allowed
nodes_regTypes:TYPE_NODE_VECTOR/TYPE_UINT64_VECTOR(paired withgroups_regvector or packed(group_id << 32) | node_idwhengroups_reg == 0orflags & 1 != 0) orTYPE_NULL. - Type Transition:
dst_regbecomesTYPE_LANE_FRONTIER. Setsflags[ZF] = 1iff no lane bits are set. OP_LANE_SET_EDGE_MASK(0xC2)- Behavior: Clones the source
TYPE_LANE_FRONTIERand attaches per-edge counterfactual trip masks (edge_trip_mask[rel_id][e] |= (1ULL << b)), causing lane \(b\) to treat edge index \(e\) as removed/tripped during subsequentOP_LANE_CSR_WALK/OP_LANE_CSC_WALKtraversals. - Encoding:
src_reg = payload & 0xFF,edge_reg = (payload >> 8) & 0xFF,rel_id = (payload >> 16) & 0xFFFF. - Allowed
edge_regTypes:TYPE_INT64/TYPE_NODE_ID(trips edgeregisters[edge_reg]in laneflags & 0x3F),TYPE_NODE_VECTOR/TYPE_UINT64_VECTOR(if(flags & 1) != 0, unpacks(lane_b << 32) | edge_idx; else tripsvec[b]in lane \(b\)), orTYPE_NULL. - Type Transition:
dst_regbecomesTYPE_LANE_FRONTIER. OP_LANE_CSR_WALK(0xC3) &OP_LANE_CSC_WALK(0xC4)- Behavior: Executes a bit-sliced forward (
0xC3CSR) or reverse (0xC4CSC) step across all active lanes simultaneously: $\(\text{next\_lanes}[v] \;\mathrel{\vert}=\; (\text{current\_lanes}[u] \land \text{active\_mask}) \land \neg\text{edge\_trip\_mask}[\text{rel\_id}][e]\)$ - Encoding:
src_reg = payload & 0xFFFF(MUST beTYPE_LANE_FRONTIER),rel_id = (payload >> 16) & 0xFFFF. - Modifier Flags:
flags & 0x03 != 0(ACCUMULATE): Preserves existingcurrent_lanes[u]bits innext_lanes[u].flags & 0x04 != 0(FIXPOINT): Iterates delta-frontier propagation (newly_reached = step_out[v] & ~out_lanes[v]) untilnewly_reached == 0for all \(v \in [0, N)\), with zero per-iteration heap allocations.
- Type Transition:
dst_regbecomesTYPE_LANE_FRONTIER. Setsflags[ZF] = 1iff allout_lanes[u] == 0. OP_LANE_PRUNE_MASK(0xC5)- Behavior: Prunes lane bits from a
TYPE_LANE_FRONTIERaccording tomode = flags & 0x03:- Mode
0(Explicit Deny Set / Per-Node Mask): Clears all lanes on nodes in aTYPE_BITSET_HANDLE, or clearslanes[u] &= ~deny_vec[u]for a vector, or clearslanes[u] &= ~scalar_maskforTYPE_INT64. - Mode
1(Disjoint Split-Half Collision Prune): Splits active lanes into low half \([0, \text{half})\) and high half \([\text{half}, k)\); zeroeslanes[u]if node \(u\) is not reached by at least one lane in both halves. - Mode
2(Degree-Gated Hub Quorum Prune): Formax_deg = (payload >> 8) & 0xFF,min_quorum = (payload >> 16) & 0xFF,rel_id = (payload >> 24) & 0xFF, zeroeslanes[u]whenever \(\text{deg}(u) > \text{max\_deg}\) and \(\text{popcount}(\text{lanes}[u]) < \text{min\_quorum}\).
- Mode
- Type Transition:
dst_regbecomesTYPE_LANE_FRONTIER. Setsflags[ZF] = 1iff allout_lanes[u] == 0. OP_LANE_FILTER_QUORUM(0xC6)- Behavior: Bridges from
TYPE_LANE_FRONTIER(0x10) to a 1-bitTYPE_BITSET_HANDLE(0x04) by selecting nodes \(u\) where at leastmin_krequired lanes are set and zero forbidden lanes are set: $\(\text{popcount}(\text{lanes}[u] \land \text{req\_mask}) \ge \text{min\_k} \;\land\; (\text{lanes}[u] \land \text{forbid\_mask}) = 0\)$ - Encoding: Standard mode (
(flags & 1) == 0):src_reg = payload & 0xFFFF,min_k = (payload >> 16) & 0xFFFF(defaults to1if0). Extended mask mode ((flags & 1) != 0):src_reg = payload & 0xFF,min_k = (payload >> 8) & 0xFF,req_mask_reg = (payload >> 16) & 0xFF,forbid_mask_reg = (payload >> 24) & 0xFF. - Type Transition:
dst_regbecomesTYPE_BITSET_HANDLE. Setsflags[ZF] = 1iff the output BitSet is empty. OP_LANE_REDUCE_AND(0xC7)- Behavior: Reduces a
TYPE_LANE_FRONTIERacross \(n_{\text{check}} = (\text{payload\_high} > 0) \text{ ? } \min(N, \text{payload\_high}) \text{ : } N\) nodes into a 64-bit integer indst_reg:flags == 0: Bitwise AND oflanes[u] & active_maskacross all \(u \in [0, n_{\text{check}})\) (mask of lanes reaching every checked node).(flags & 1) != 0: Complementactive_mask & ~all_reached(mask of lanes failing to reach at least one node, e.g., islanded contingencies).(flags & 2) != 0: Count of universal nodes \(u \in [0, n_{\text{check}})\) where(lanes[u] & active_mask) == active_mask.
- Type Transition:
dst_regbecomesTYPE_INT64. Setsflags[ZF] = 1iff result is0. OP_LANE_REDUCE_ATTR(0xC8)- Behavior: Performs a single-pass bit-sliced reduction of a node attribute array (
attr_idor vector register when(flags & 1) != 0) across all \(k\) active lanes simultaneously. - Encoding:
src_reg = payload & 0xFF,attr_or_reg = (payload >> 8) & 0xFF,red_op = (payload >> 16) & 0xFFFF. - Reduction Modes (
red_op):0(BINARY_OP_ADD/SUM),1(MUL),2(MIN),3(MAX),4/5(COUNT): OutputsTYPE_FLOAT_VECTORof length \(k\). Untouched lanes receive0.0f.NaNattribute values are skipped.6(BINARY_OP_ARGMIN),7(BINARY_OP_ARGMAX): OutputsTYPE_UINT64_VECTOR/TYPE_NODE_VECTORof length \(k\) containing the witness node ID for each lane (-1if untouched). Deterministic Tie-Breaking: Strictly uses<(forARGMIN) or>(forARGMAX) in ascending node ID order \(u = 0 \dots N-1\) so the lowest node ID wins ties.
OP_LANE_SET_COVER(0xC9)- Behavior: Computes a greedy minimum witness node cover over
src_reg(TYPE_LANE_FRONTIER). At each step (up tomax_k), selects the node \(u\) that covers the maximum number of remaining uncovered lanes inuncovered_mask(with optional positive cost weighting fromcost_regwhen(flags & 1) != 0). Deterministic Tie-Breaking: Lowest node ID \(u\) wins ties. - Encoding:
src_reg = payload & 0xFF,cost_reg = (payload >> 8) & 0xFF,max_k = (payload >> 16) & 0xFFFF. - Type Transition:
dst_regbecomesTYPE_NODE_VECTORcontaining the selected witness node IDs. Setsflags[ZF] = 1iffuncovered_mask != 0after termination (i.e., full cover was not achieved). OP_VECTOR_ANN_SEARCH(0xCA)- Behavior: Executes top-\(k\) approximate nearest neighbor seed retrieval from a query embedding vector in
q_reg(TYPE_FLOAT_VECTOR). - Encoding:
q_reg = payload & 0xFF,top_k = (payload >> 8) & 0xFF(or(payload >> 16) & 0xFFFF). - Type Transition: If
(flags & 1) != 0, initializes aTYPE_LANE_FRONTIERwith \(k = \text{top\_k}\) lanes; otherwise outputs aTYPE_BITSET_HANDLE. OP_VECTOR_RERANK_DOT(0xCB)- Behavior: Computes exact dot-product reranking scores for candidate nodes in
cand_reg(TYPE_BITSET_HANDLEorTYPE_LANE_FRONTIER) against query vectorq_reg(TYPE_FLOAT_VECTOR). - Encoding:
cand_reg = payload & 0xFF,q_reg = (payload >> 8) & 0xFF,attr_id = (payload >> 16) & 0xFFFF. - Type Transition:
dst_regbecomesTYPE_FLOAT_VECTOR. Setsflags[ZF] = 1iff candidate set is empty.
7. Concurrency & Execution Design Factors
Any implementation of the ImpulseVM query interpreter MUST conform to the following performance, alignment, and multi-threading invariants:
7.1 Context Thread-Locality & Concurrency Behavior
- Context Isolation: The VM query execution context (
impulse_vm_context_t) MUST be thread-local and thread-private. Multiple system threads executing concurrent queries SHALL NOT share context instances, registers, stacks, or state frames. - Lock-Free Read Path: Since Snapshots are read-only, all execution paths over memory-mapped snapshot structures MUST run lock-free without acquiring mutexes or synchronization barriers.
7.2 Intra-Opcode Parallelism (Only)
- Parallel Dispatch Boundaries: The VM interpreter MUST NOT execute multi-threaded pipeline execution across separate instructions (i.e., no instruction-level parallelism / ILP or multi-threaded instruction scheduling).
- Intra-Instruction Parallelization: Parallelization MUST be strictly confined to the loop internals of single heavy traversal or matrix opcodes (e.g.,
OP_CSR_WALK,OP_CSC_WALK,OP_MXV). Loop chunks MAY be dispatched to multiple worker threads (e.g., via OpenMP#pragma omp parallel for) when the frontier or workload exceeds a compiler-defined size threshold.
7.3 Concurrency Control (max_dop)
- Parallelism Setting: The VM context MUST allow configuring a maximum degree of parallelism (
max_dop). - Sequential Safety Check: If
max_dopis configured to1(single-threaded mode), the interpreter MUST execute standard, sequential loop bodies without using atomic instructions (e.g.,bitset_addinstead ofbitset_add_atomic) to bypass CPU-level hardware synchronization overhead. - OP_SET_MAX_DOP Execution: The instruction
OP_SET_MAX_DOP(0x75) SHALL dynamically update the context's thread worker count for subsequent instruction iterations.
7.4 Register Frame Windowing
- Recursive Integrity: Subroutines (
OP_CALL,OP_RET) MUST protect register contexts. Subroutine recursion (e.g., evaluating nested ReBAC transitivities or recursive traversals) MUST implement register frame windowing or context state stacking to prevent sibling subroutines from overwriting the registers of caller frames.
7.5 Allocation-Free Hot Path
- Zero Heap Allocations: The interpreter's main opcode dispatch loop (the instruction processing path) MUST NOT allocate or free heap memory (e.g., no
malloc/freeor C++new/deletecalls). - Arena-Based Resource Pooling: All intermediate structures, BitSets, vectors, and value maps MUST be pre-allocated and pooled. Opcodes needing temporary objects MUST acquire and release handles through the context's arenas (e.g., calling
acquire_bitset/release_bitset).
7.6 Caller-Assigned Result Buffers
- FFM Zero-Copy Collection: Output materialization opcodes (
OP_COLLECT_BITSET,OP_COLLECT_ARRAY,OP_COLLECT_VALUE_MAP) MUST NOT allocate memory buffers to return results to the client. - In-Place Writes: The caller MUST pre-allocate and pass the target memory destination buffers (such as Java FFM off-heap
MemorySegmentpointers or C array pointers) to the VM. The interpreter MUST write elements directly into these caller-assigned buffers in-place.
8. ImpAsm (.impas) Assembly Text Format Specification
ImpAsm (.impas) is the human-readable assembly language and polyglot compliance test-vector format for ImpulseVM. An .impas file consists of two sections (.data and .text) plus optional ; {{EXPECT: ...}} post-execution assertions:
8.1 .data Section Directives
.rel <NAME> = <ID>/.vrel <NAME> = <ID>: Binds a physical or virtual relation ID..fuel <AMOUNT>: Sets the instruction execution gas/fuel limit (e.g.,.fuel 1000)..csr_inline <NAME> = { <src>: [<tgt>, ...], ... }: Defines an inline mock CSR adjacency matrix for isolated opcode testing without an external.impsfile..array_float/.array_int/.array_node <NAME> = [...]: Defines inline typed arrays in the VM context..set/.set_roaring/.set_dense <NAME> = [<id>, ...]: Defines inline polymorphic BitSet fixtures.
8.2 .text Section & {{EXPECT: ...}} Directives
Instructions follow [address]: <OPCODE_MNEMONIC> <ARG1>, <ARG2>, ... using registers R0..R63. Polyglot test runners (four_way_validation.py) verify identical post-halt state across C++ (O3/O0), Java 25, and the OCaml Reference Oracle using comment assertions:
; {{EXPECT: STATUS = IMPULSE_VM_OK}}
; {{EXPECT: FLAG = ZF}}
; {{EXPECT: REG[R4] = 0}}
.data
.array_float MOCK_PRICES = [1.5, 0.0, 3.14, 0.0]
.set_roaring FRONTIER = [0, 2]
.text
0x00: OP_LOAD_INLINE_ARRAY R0, MOCK_PRICES
0x01: OP_INIT_MOCK_NODE_ATTR 0, R0, R255
0x02: OP_LOAD_INLINE_SET_ROARING R3, FRONTIER
0x03: OP_NODE_FILTER R4, R3, R0, 0
0x04: OP_SET_CARDINALITY R0, R4
0x05: OP_HALT
9. Deterministic Execution Context State Hash (ICTX v1 Specification)
To guarantee 100% bitwise cross-engine consensus without floating-point drift, memory pointer discrepancies, or uninitialized padding artifacts, ImpulseVM specifies the ICTX v1 Deterministic State Hash protocol.
Given a completed VM execution state frame (impulse_vm_state_t), execution status code (int32_t status), and query execution context (impulse_vm_context_t), the C-ABI functions impulse_vm_state_hash and impulse_vm_state_hash_hex serialize execution state into a canonical binary byte stream and compute its standard SHA-256 cryptographic digest.
9.1 Binary Stream Serialization Layout
All multi-byte integer and floating-point values MUST be encoded in Little-Endian byte order. The byte stream is structured sequentially as follows:
| Offset / Section | Field / Component | Encoding | Length | Description |
|---|---|---|---|---|
| 1. Header | magic |
ASCII "ICTX" |
4 Bytes | Bytes 0x49, 0x43, 0x54, 0x58. |
version |
uint16_t LE |
2 Bytes | Protocol version (strictly 1). |
|
reserved |
uint16_t LE |
2 Bytes | Reserved padding (strictly 0). |
|
| 2. State Metadata | status |
int32_t LE |
4 Bytes | VM return status code (0 = IMPULSE_VM_OK, negative = error code). |
pc |
uint32_t LE |
4 Bytes | Final Program Counter value. | |
flags |
uint64_t LE |
8 Bytes | 64-bit VM condition flags register (ZF, LT, GT, EQ, ST, etc.). |
|
| 3. Call Stack | call_stack_depth |
uint32_t LE |
4 Bytes | Number of active subroutine frames (0..8). |
call_stack[0..7] |
uint32_t[8] LE |
32 Bytes | 8 frame PC slots. Inactive slots (\(i \ge \text{depth}\)) MUST be serialized as 0. |
|
| 4. Architectural Registers | register_types[0..63] & registers[0..63] |
Interleaved (uint8_t, uint64_t LE) |
576 Bytes | For each register \(r = 0 \dots 63\): 1 byte register_types[r], followed by 8 bytes registers[r]. |
| 5. Active Handle Dereferencing | Dynamic handles | Variable | Variable | Evaluated in register index order \(r = 0 \dots 63\) (see §9.2). |
9.2 Handle Dereferencing Invariants
When register \(r\) contains an off-heap object handle, its canonical payload is serialized into the stream based on its type tag:
TYPE_BITSET_HANDLE(0x04):cardinality(uint64_tLE): Total count of set bits across the BitSet.node_ids(uint64_t[cardinality]LE): Monotonically ascending list of set node IDs.- If the handle is null, out of bounds, or unallocated,
cardinality = 0is serialized. TYPE_FLOAT_VECTOR(0x0C):length(uint32_tLE): Number of float elements.values(float32[length]LE): IEEE 754 single-precision floats.- Canonical Float Normalization: All
NaNrepresentations are normalized to0x7FC00000. Negative zero (-0.0f) is normalized to positive zero (+0.0f). - If handle is invalid,
length = 0is serialized. TYPE_DOUBLE_VECTOR(0x0D):length(uint32_tLE): Number of double elements.values(float64[length]LE): IEEE 754 double-precision floats.- Canonical Double Normalization: All
NaNrepresentations are normalized to0x7FF8000000000000ULL. Negative zero (-0.0) is normalized to positive zero (+0.0). - If handle is invalid,
length = 0is serialized. TYPE_NODE_VECTOR(0x05) &TYPE_UINT64_VECTOR(0x0E):length(uint32_tLE): Number of 64-bit integer elements.values(uint64_t[length]LE): Contiguous 64-bit elements.- If handle is invalid,
length = 0is serialized. TYPE_LANE_FRONTIER(0x10):num_lanes(uint32_tLE): Number of configured logical lanes (\(1 \le k \le 64\)).max_lanes(uint32_tLE): Physical bit-slice capacity (8,16,32, or64).active_mask(uint64_tLE): Active bitmask indicating live lanes.node_count(uint32_tLE): Number of domain nodes.lanes(uint64_t[node_count]LE): Dense array of per-node bit-sliced masks.- If handle is invalid, four zero words (
0U,0U,0ULL,0U) are serialized. TYPE_STRING_VECTOR(0x0B):count(uint32_tLE): Number of strings.- For each string \(j = 0 \dots \text{count}-1\): length
slen(uint32_tLE) followed byslenraw UTF-8 bytes. TYPE_VALUE_MAP(0x0A):count(uint32_tLE): Number of key-value pairs.- For each entry \(j = 0 \dots \text{count}-1\): key length
klen(uint32_tLE),klenUTF-8 key bytes, andfloat32LE value. - Scalar and Null Registers: No extra bytes are appended.
9.3 C-ABI State Hash Functions
/* Compute 32-byte binary SHA-256 digest of VM execution state */
IMPULSE_API int impulse_vm_state_hash(
const impulse_vm_state_t* state,
int32_t status,
uint8_t hash_out[32]
);
/* Compute 64-character null-terminated lowercase hexadecimal digest string */
IMPULSE_API int impulse_vm_state_hash_hex(
const impulse_vm_state_t* state,
int32_t status,
char hex_out[65]
);
9.4 Four-Way Polyglot Validation Harness
The four_way_validation.py test harness runs .impas test vectors across four independent execution engines:
1. C++ Kernel (Optimizations ON) (-O3, Highway SIMD, OpenMP)
2. C++ Kernel (Optimizations OFF) (-O0, baseline interpretation)
3. Pure Java 25 Engine (MemorySegment off-heap FFM, jdk.incubator.vector, MethodHandle C2 JIT)
4. OCaml Reference Engine (Normative formal specification AST & bytecode oracle)
All four engines MUST produce an identical 64-character lowercase hexadecimal hash. Any hash mismatch immediately fails the validation suite with a register-by-register and bitset diff.
10. 188 Formal Executable Opcode Contracts & Verification Specification
To eliminate undefined behavior, register aliasing corruptions, and invalid type states at machine-cycle speeds, ImpulseVM specifies 188 Formal Executable Opcode Contracts covering all 166 ISA opcodes (0x00..0xCB).
10.1 Contract Schema Definition (ImpulseOpcodeVariantContract)
Each opcode variant contract defines the static structural layout, dynamic input register type constraints, flag requirements, and post-execution invariant guarantees:
struct ImpulseOpcodeVariantContract {
uint8_t opcode; // Opcode numeric value (0x00..0xCB)
const char* mnemonic; // Instruction mnemonic (e.g. "OP_LANE_CSR_WALK")
const char* variant_name; // Specific variant name (e.g. "OP_LANE_CSR_WALK_STANDARD")
uint8_t flags_mask; // Relevant bits in inst.flags
uint8_t flags_match; // Required matching bits for this variant
uint8_t defined_flags_mask; // All valid flag bits permitted for this opcode
uint32_t fixed_payload_bits; // Non-register payload bits (rel_id, mode, etc.)
RegFieldLayout dst_layout; // Destination register location
RegFieldLayout src_layout; // Source 1 register location
RegFieldLayout aux1_layout; // Source 2 register location
RegFieldLayout aux2_layout; // Source 3 register location
uint32_t allowed_src_types; // Bitmask of allowed input types for src
uint32_t allowed_aux1_types; // Bitmask of allowed input types for aux1
uint32_t allowed_aux2_types; // Bitmask of allowed input types for aux2
uint32_t output_dst_types; // Valid resulting type mask for dst_reg
bool allow_zero_skip_aux1; // True if aux1 == 0 skips register checking
bool allow_zero_skip_aux2; // True if aux2 == 0 skips register checking
uint64_t sets_vm_flags_mask; // Status flags modified by this opcode
bool requires_context; // True if non-null impulse_vm_context_t is required
bool modifies_dst_state; // True if dst_reg value or type is modified
};
10.2 Operand Register Field Layouts (RegFieldLayout)
Operands inside 64-bit packed instructions are extracted and injected via deterministic layout descriptors:
| Layout Constant | Value | Bit Extraction Expression | Typical Usage |
|---|---|---|---|
RegFieldLayout::NONE |
0 |
None | Instruction does not read this operand. |
RegFieldLayout::DST_REG |
1 |
inst.dst_reg |
Primary destination register (0..63). |
RegFieldLayout::PAYLOAD_LOW8 |
2 |
inst.payload & 0xFF |
8-bit source register in low payload byte. |
RegFieldLayout::PAYLOAD_LOW16 |
3 |
inst.payload & 0xFFFF |
16-bit register or relation ID. |
RegFieldLayout::PAYLOAD_BYTE1 |
4 |
(inst.payload >> 8) & 0xFF |
Secondary register operand (aux1). |
RegFieldLayout::PAYLOAD_BYTE2 |
5 |
(inst.payload >> 16) & 0xFF |
Tertiary register operand (aux2). |
RegFieldLayout::PAYLOAD_BYTE3 |
6 |
(inst.payload >> 24) & 0xFF |
Quaternary operand or mode flags. |
RegFieldLayout::PAYLOAD_HIGH16 |
7 |
(inst.payload >> 16) & 0xFFFF |
High 16 bits of payload (rel_id, threshold, count). |
10.3 Branchless Type Checking (IMPULSE_CHECK_REG_TYPE)
Type checking is performed branchlessly in \(\le 2\) CPU cycles using 17-bit register type bitmasks (IMP_TYPES_*):
#define IMP_TYPE_BIT(t) (1u << static_cast<uint32_t>(t))
#define IMPULSE_CHECK_REG_TYPE(vm_state, reg, allowed_mask) \
do { \
if (IMPULSE_UNLIKELY(((1u << static_cast<uint32_t>((vm_state)->register_types[(reg)])) & (allowed_mask)) == 0u)) { \
return IMPULSE_VM_ERR_INVALID_REGISTER; \
} \
} while (0)
10.4 Automated 5-Pass Contract Verification Suite
The test_opcode_contracts.cpp test suite automatically verifies all 188 contracts through five exhaustive passes:
- Pass 1: Disallowed Register Type Rejection:
- Synthesizes instructions with each of the 17 possible register dynamic types (
TYPE_NULLthroughTYPE_LANE_FRONTIER) injected intosrc,aux1, andaux2. - Verifies that any type excluded by
allowed_src_types,allowed_aux1_types, orallowed_aux2_typesimmediately returnsIMPULSE_VM_ERR_INVALID_REGISTER. - Pass 2: Allowed Type Acceptance & Destination Conformity:
- Executes the opcode with valid input mock operands and verifies that execution returns
IMPULSE_VM_OK. - Confirms that
vm_state.register_types[dst_reg]matchesoutput_dst_types. - Pass 3: Out-of-Bounds Register Validation:
- Injects invalid register indices (\(r \ge 64\), e.g.
64,128,255) into operand positions. - Verifies that the interpreter traps or returns
IMPULSE_VM_ERR_INVALID_REGISTERwithout memory access violations. - Pass 4: In-Place Register Aliasing Safety:
- Tests operand aliasing conditions (
dst == src,dst == aux1,dst == aux2,src == aux1). - Asserts that in-place mutation does not read overwritten destination state prematurely.
- Pass 5: Null Context & Snapshot Safety:
- For opcodes where
requires_context == true, executes the instruction withquery_context = nullptr. - Verifies that the VM safely returns
IMPULSE_VM_ERR_NULL_SNAPSHOTwithout null-pointer dereferences.