# Impulse Graph Engine — Complete Documentation & Specification Corpus # Source: https://www.impulsegraph.org/llms-full.txt # Index: https://www.impulsegraph.org/llms.txt # Skill: https://www.impulsegraph.org/ai/SKILL.md ================================================================================ FILE: docs/ai/SKILL.md | URL: https://www.impulsegraph.org/ai/SKILL.md ================================================================================ --- name: impulse-graph description: Architectural rules, engine-native Kleisli set traversal idioms, per-domain dense ID invariants, JVM/Python/C-ABI configuration, and CLI verification commands for the Impulse Graph Engine (.imps). Activate whenever writing, reviewing, or debugging code, schemas, or pipelines using Impulse Graph. --- # Impulse Graph Engine — AI Coding Agent Skill & Rules (`impulse-graph`) Follow these seven architectural invariants whenever generating code, queries, schemas, build configurations, or deployment manifests for **Impulse Graph Engine** (`org.impulsegraph` / `impulse-graph`). --- ## 1. What Impulse Graph Is (and Isn't) * **Immutable Binary Snapshot Engine (`.imps`)**: Impulse Graph pairs a 4KB-page-aligned, 128-byte-section-aligned read-only binary file format (`.imps`) mapped via `mmap` with a 64-register bytecode Virtual Machine (`ImpulseVM` executing `impOps`). It is the **Apache Arrow / Parquet equivalent for Graph Analytics**—not a mutable OLTP row-store graph database. * **NEVER Generate In-Place Graph Mutations**: Do **not** generate Neo4j/SQL mutation statements (`CREATE`, `MERGE`, `INSERT`, `SET`, `DELETE`, `DETACH DELETE`) or invent `graph.addNode()` / `graph.addEdge()` runtime mutation calls on a loaded `ImpulseGraphSnapshot` / `Snapshot`. * **Rebuild + Atomic Blue/Green Swap**: Data updates compile a fresh `.imps` file out-of-band (`impulse-graph build` or Java `SnapshotBuilder`) and rotate it into live reader processes with zero lock contention via `SnapshotLifecycleManager` (`v0.11`) or `SnapshotSwapManager` (`impulse-storage`). --- ## 2. Strict Per-Domain Dense ID Independence (`0 .. N_d - 1`) * **No Global Node ID Space**: Every node domain (`User`, `Account`, `Product`, `Gene`) owns an independent `0`-indexed contiguous dense integer space `0 .. N_d - 1` (`uint16`, `uint32`, or `uint64`). Dense ID `0` in `User` is completely distinct from Dense ID `0` in `Account`. * **Always Anchor Traversals to an Explicit Domain**: Start every query from an explicit domain view (`snap.domain("User")` in Java/Python/C++, or AOT-generated `bankSnap.users()` in Java `v0.11`). Never pass unanchored raw integer IDs across domains. * **Never Persist Ephemeral Dense IDs Externally**: Dense IDs (`0 .. N_d - 1`) are internal per-snapshot coordinates that intentionally permute when snapshots are rebuilt or optimized (`--rcm`, `--vamana-locality`). Always resolve external business keys (`UUID`, `String`, `int64`) at query boundaries via `fromKey(...)` / `fromKeys(...)` and materialize results via `toKeyList()` / `toKeySet()`. --- ## 3. 100% Engine-Native Kleisli Set Traversals (Zero Imperative Loops) * **NEVER Write Client-Side Point-Lookup Loops**: Do **not** iterate over node IDs in application `for` loops (`for (long id : frontier)` in Java or `for u in nodes:` in Python) calling single-node neighbor lookups or manual attribute checks hop-by-hop. That treats the engine as a dumb key-value table and destroys SIMD vectorization and cache locality. * **Single Pipeline Execution**: Express multi-hop walks (`.out(...)`, `.in(...)`), attribute filters (`.filter("node.age >= 21")` or typed AOT predicates), state projections (`.project(...)`), monoidic aggregations (`Reducer.SUM`, `MIN`, `MAX`, `.outWithState("REL", "state.total:SUM = edge.amount")`), and unbounded transitive closures (`.repeatUntilStable("PARENT_GROUP")`) inside **one engine pipeline** or **one prepared query** (`openCypher`, `ImpLog`, `ImpK`, `ImpScheme`). * **Honest Capability Reporting**: If an application requires stateful per-path backtracking or an operator not supported by `ImpulseVM`, state that explicitly rather than fabricating client-side imperative traversal loops. ```java // WRONG — Client-side imperative N+1 point-lookup loop (NEVER DO THIS): Set flagged = new HashSet<>(); for (long accId : snap.domain("User").fromKey(userId).out("OWNS").toList()) { for (long dstId : snap.domain("Account").from(accId).out("TRANSFERRED_TO").toList()) { flagged.add(snap.domain("Account").toKey(dstId)); } } // CORRECT — Single engine-native Kleisli set traversal: List flagged = snap.domain("User") .fromKey(userId) .out("OWNS") .out("TRANSFERRED_TO", "edge.amount >= 10000.0") .filter("node.risk_score >= 80") .toKeyList(); ``` --- ## 4. Set Semantics (Not Multi-Set Path Bags) * **Frontier Compression**: Every step $\langle D, \text{Frontier}, \text{State} \rangle \xrightarrow{R} \langle D', \text{Frontier}', \text{State}' \rangle$ collapses converging incoming edges onto a per-domain `BitSet` (and optional monoid-reduced state vector `SUM` / `MIN` / `MAX` / `ARGMIN` / `ARGMAX`), or a bit-sliced `VmLaneFrontier` (`0xC0`..`0xC9`, up to 64 parallel lanes). * **No Path Explosion**: Queries never materialize $O(d^k)$ path bags in heap memory, and terminal collectors (`toBitSet()`, `toKeyList()`, `count()`) emit results strictly from the **final active target domain**. --- ## 5. Idiomatic Java Enterprise Configuration (`impulse-graph-java`) * **Prefer Schema-First AOT Codegen (`v0.11`)**: Define graph contracts in `.imps.schema.yaml` and generate zero-dependency typed wrappers (`Snapshot`, `Id`, `Traversal`, `Attrs`, flyweight `RowView`) via `org.impulsegraph:impulse-maven-plugin` (`generate` goal) or `impulse-j codegen`. * **Use `impulse-bom`**: Import `org.impulsegraph:impulse-bom` (`0.11.0` for full AOT/CLI suite; `0.10.0` for core Maven Central runtime artifacts `impulse-api`, `impulse-storage`, `impulse-vm`, `impulse-compiler`, `impulse-builder`). Core runtime modules have **zero third-party dependencies**. * **Mandatory JDK Compiler & Runtime Flags**: * **JDK 22+ / JDK 25 LTS (Recommended)**: * `javac`: `--release 25 --add-modules jdk.incubator.vector` (do **not** pass `--enable-native-access` to `javac`). * `java` / Surefire / Failsafe: `--add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED`. * **JDK 21 LTS**: Add `--enable-preview` to **both** `javac` (`--release 21 --enable-preview --add-modules jdk.incubator.vector`) and `java` (FFM `Arena`/`MemorySegment` is preview in JDK 21 JEP 442). * **Container & Kubernetes Memory Sizing**: `.imps` files reside off-heap in the OS `mmap` page cache (counted against container `cgroups v2` memory limits, **not** `-Xmx` or `-XX:MaxDirectMemorySize`). Size the JVM heap lean (`-Xms2g -Xmx4g -XX:+UseZGC -XX:+ZGenerational`) and leave container memory headroom for mapped `.imps` pages. Use `Arena.ofShared()` for concurrent multi-threaded snapshots. --- ## 6. Idiomatic Python, PyTorch & Native C-ABI Usage * **Build Snapshots via Official Tooling Only**: Never write ad-hoc Python/C++/shell byte-packing scripts to create `.imps` files. Always compile CSV/TSV/Parquet datasets with `impulse-graph build --manifest manifest.json -o graph.imps` (or `SnapshotBuilder` / `SnapshotWriter` / `impulse_writer_t`). Enable `"include_csc": true` on relations that will be traversed in reverse (`.in(...)` / `.in_(...)` / `<-[]-`). * **Python & Multi-Worker PyTorch (`impulse-graph`)**: * Open snapshots with `with Snapshot("graph.imps") as snap:` (`pip install impulse-graph==0.10.0`). * Anchor traversals via `snap.domain("User").from_key("...").out("...").to_key_list()` or `snap.cypher(query, params={...})`. * Access CSR and SoA tensors zero-copy via `snap.get_row_offsets_array(rel_idx)`, `snap.get_col_indices_array(rel_idx)`, `snap.get_attribute_array(rel_idx, attr_idx, dtype=np.float32, shape=...)`, and `snap.sample_neighbors(...)`. * In `multiprocessing` or PyTorch `DataLoader(num_workers > 0)`, pass only the `.imps` **file path string** to workers and instantiate `Snapshot(path)` lazily inside each worker so all processes share one read-only OS page-cache mapping (`0 bytes` CoW duplication). * **Native C / C++20 / Rust (`impulse-cpp` & `impulse-rust`)**: * Use caller-allocated prepared statements (`impulse_stmt_prepare` $\to$ `impulse_stmt_buffer_size` $\to$ `impulse_stmt_execute` $\to$ `impulse_stmt_finalize`) for zero-`malloc` execution, C++20 `impulse::vm::SnapshotView` (`impulse_vm_fluent.hpp`), or Rust `impulse_graph::reader::SnapshotReader`. --- ## 7. Self-Verification via Structured JSON CLI Output Whenever creating, modifying, or debugging `.imps` snapshots, manifests, or `.imps.schema.yaml` contracts, verify your work using machine-readable CLI checks before finishing: ```bash # 1. Inspect domains, relations, attribute types, and 128B section offsets as JSON impulse-graph snapshot inspect graph.imps --format json # 2. Validate 128-byte alignment, CRC-16 header, CSR/CSC transpose invariants, and SHA-256 impulse-graph snapshot validate graph.imps --strict-alignment --deep-audit # 3. Profile degree skew and high-degree supernodes (Z-score >= 3.0) impulse-graph snapshot stats graph.imps --supernode-threshold 3.0 --format json # 4. Pure-Java schema conformance & consumer-driven compatibility gates (impulse-j, v0.11) impulse-j schema validate src/main/resources/schema.yaml --snapshot graph.imps --format json impulse-j schema check-compat --snapshot candidate.imps --consumer schema.yaml --format json ``` ================================================================================ FILE: docs/index.md | URL: https://www.impulsegraph.org/ ================================================================================ # Impulse Graph Engine ![Impulse Graph Engine Banner](assets/banner_letterbox.jpg) **Impulse Graph Engine** (`impulse-graph`) is an embedded, read-only graph engine built around an open, 128-byte-aligned binary snapshot format (**`.imps`**) and a 64-register bytecode virtual machine (**`ImpulseVM`**). It decouples static and micro-batch graph analytics from stateful database servers—acting as an **Apache Arrow / Parquet equivalent for multi-domain property graphs**. ```mermaid flowchart LR S1["1. Build Once\nParquet / CSV / JDBC + Schema\n──► Snapshot Builder / CLI"] --> S2["2. Immutable .imps File\n128B-Aligned CSR/CSC & SoA\n──► OS mmap (< 10 ms)"] S2 --> S3["3. Query In-Process\nSet-Reduced Kleisli Traversal\n──► ImpulseVM (impOps)"] ``` --- ## Start From Your Stack or Problem | Your Stack or Problem | Problem-First Architectural Guide | Ecosystem Hub & Tooling | | :--- | :--- | :--- | | **Python, Data Science & PyTorch GNNs** | **[From NetworkX & Parquet to `.imps`](getting-started/from-networkx-and-parquet.md)** — Eliminate `dict` RAM blowups and multi-second CSV/Parquet reloads. | **[Python & PyTorch Hub](ecosystems/python/index.md)** | | **Java & JVM Enterprise Services** | **[Embedded `.imps` vs. Networked Graph DB](getting-started/embedded-vs-graph-db.md)** — Remove TCP/JSON hops for ReBAC, fraud, and catalog hierarchies. | **[Java & JVM Hub](ecosystems/java/index.md)** | | **C/C++20, Rust & Cross-Team Pipelines** | **[Polyglot "Parquet for Graphs" Workflow](getting-started/polyglot-workflow.md)** — Build once from Parquet, query identically in Java and Python. | **[Native, Rust & Polyglot Hub](ecosystems/native/index.md)** | | **AI Coding Assistants & Agents** | Machine-readable context indices (`llms.txt`, `llms-full.txt`) and installable `SKILL.md` rules for Claude, Cursor, and Antigravity. | **[AI Assistants & Skills](ai/index.md)** | *(Browse all language guides in the **[Ecosystems Overview](ecosystems/index.md)** or jump straight to the **[5-Minute Quickstart](getting-started/quickstart.md)**.)* --- ## 1. Core Design * **Single-File `.imps` Snapshots**: Compile node domains, CSR/CSC adjacency matrices, and Structure-of-Arrays (SoA) columns once into a single immutable binary file and `mmap` it directly from disk (`0.038 ms` in C++20, `9.75 ms` in Java 25 with Leyden AOT on a 6.04 GB, 1.47B-edge graph)—no server process, no deserialization, and no heap loading. * **Set-Reduced Frontiers & Pre-Calculated Buffers**: Intermediate traversals collapse converging paths into per-domain bitsets or monoidic state vectors at every hop. Because domain cardinalities ($0 \dots N_d - 1$) are fixed per snapshot, exact query scratch memory is known at `prepare` time (`impulse_stmt_buffer_size`), avoiding path explosion and hot-loop heap allocations. * **One VM, Multiple Query Frontends**: Schema-generated AOT fluent builders, domain-bound traversals (`snap.domain(...)`), read-only parameterized **openCypher**, Datalog (**ImpLog**), GraphBLAS (**ImpK**), and **Google CEL** predicates all lower through `ImpScheme` IR into 64-bit `impOps` bytecode. * **`v0.10.0` Capabilities**: 8/16/32/64-lane bit-sliced frontiers (`0xC0`..`0xC9`) for batched seeds and $N-1$ contingency walks, plus embedded Vamana ANN vector search (`0x08`, `0xCA`..`0xCB`). For the architectural rationale, JFR/C++ empirical analysis, and foundational CS literature, see **[Why Impulse Graph?](concepts/why-impulse.md)**, **[Benchmarks](benchmarks.md)**, and **[Research Literature & Design Lineage](academic/literature-and-influences.md)**. --- ## 2. One Portable Specification & ISA, Pluggable Execution Runtimes Impulse Graph separates the **normative data and bytecode contract** from the **execution runtimes** that evaluate it: 1. **Open Data & Bytecode Contract (`impulse-graph-spec`)**: * **`.imps` Binary Snapshot Format**: 128-byte-aligned sections containing per-domain key indices, CSR/CSC topologies, SoA columns, and Vamana ANN indices. * **`.imps.schema.yaml` / `manifest.json`**: Declarative schema contract defining independent node domains ($0 \dots N_d - 1$), integer widths (`uint16`/`uint32`/`uint64`), directed relations, and attribute types. * **`impOps` 64-Register ISA (`R0`..`R63`)**: Fixed-width 64-bit bytecode instructions verified by compliance test vectors (`tc01`–`tc38`, `vm-impas/`). 2. **Independent Execution Runtimes**: | Runtime | Implementation & Memory Access | Language Ecosystem | Distribution (`0.10.0`) | | :--- | :--- | :--- | :--- | | **Pure JVM Engine** (`impulse-graph-java`) | 100% Java 21 LTS / 25 (`MemorySegment`, `Arena`, Vector API, `MethodHandle` JIT); zero JNI, zero third-party runtime dependencies | Java, Kotlin, Scala 3, Clojure | Maven Central (`org.impulsegraph`) | | **Native C++20 / C-ABI Engine** (`impulse-graph-core`) | C++20 (`libimpulse_graph`, `impulse_graph.h`) with OS `mmap`, Google Highway SIMD, and OpenMP; zero third-party runtime dependencies | C, C++20, Rust, Python (NumPy/PyTorch), Go, .NET (P/Invoke), Node.js | PyPI (`impulse-graph`), crates.io (`impulse-graph`), GitHub Releases | | **Formal Reference Oracle** (`impulse-ocaml`) | Pure functional OCaml implementation of `ImpulseVM` and `ICTX` v1 state hashing | Differential fuzzing & four-way parity verification | Source (`impulse-ocaml`) | !!! note "Extensible Runtime Target Architecture" Because `.imps` layouts and `impOps` bytecode are self-contained and hardware-aligned with no engine-specific object headers, every compliant runtime produces bitwise-identical register state, status codes, and query outputs. Additional standalone runtimes—such as a pure managed `.NET` (`Span` / `Vector512`) engine or an in-browser `WebAssembly` (`wasm64` / SIMD128) runtime—can implement the specification without modifying existing `.imps` files, `.imps.schema.yaml` contracts, or user queries. --- ## 3. When Impulse Graph Is — and Isn't — the Right Fit | Workload Characteristic | Strong Fit for Impulse Graph | Not a Direct Replacement (Recommended Pattern) | | :--- | :--- | :--- | | **High-QPS Multi-Hop Service Reads** (ReBAC/Zanzibar authz, fraud rings, catalog/BOM hierarchies) | **Yes** — Sub-microsecond in-process traversals (`0.026 µs – 0.552 µs` on 600k-user ReBAC; `4.13 µs` targeted BFS on 1.47B edges) with zero network or JSON serialization overhead. | — | | **Near-Real-Time (`5s – 5 min`) or Batch Updates** | **Yes** — Rebuild `.imps` out-of-band in seconds, publish to S3/GCS, and execute lock-free Blue/Green `Arena` swaps across stateless pods. | — | | **Large-Scale Graph Analytics & GNN Sampling** | **Yes** — Mount multi-GB `.imps` files via `mmap` across Python/PyTorch `DataLoader` workers sharing a single OS page cache (`24.2 µs` 4-hop Hetionet query vs. `42.1 ms` in NetworkX). | — | | **Strict OLTP Mutations (`< 10 ms` Read-Your-Own-Writes)** | — | **No** — `.imps` snapshots are immutable. Keep transactional writes in PostgreSQL, MySQL, or RocksDB and project read-heavy graph views into Impulse ([Changing Data & Live Updates](getting-started/handling-mutations.md)). | | **Arbitrary Multi-Set Path Enumeration** | — | **By Design** — Impulse reduces converging paths into per-domain sets/monoids at every hop to guarantee bounded memory rather than enumerating exponential path bags. | --- ## 4. See It in Action === "Java 25 (Fluent API)" ```java try (Arena arena = Arena.ofShared()) { ImpulseGraphSnapshot snap = BinarySnapshotLoader.loadSnapshot(Path.of("social.imps"), arena).getGraph(); List friends = snap.domain("User") .fromKey("usr_alice") .out("FOLLOWS") .filter("node.age >= 21 && node.active == true") .toList(); } ``` === "Java 25 (openCypher)" ```java try (ImpulseStatement stmt = snap.prepare( "MATCH (u:User)-[:FOLLOWS]->(f:User) WHERE u.id = $uid AND f.age >= $minAge RETURN f.id")) { stmt.bindNode("uid", 42L).bindLong("minAge", 21L); try (RowReader rows = stmt.execute()) { while (rows.next()) { long friendId = rows.getNodeId(0); } } } ``` === "C / C++20 (C-ABI)" ```c impulse_stmt_t* stmt = NULL; impulse_stmt_prepare(snap, "MATCH (u:User)-[:FOLLOWS]->(f:User) WHERE u.id = $uid RETURN f.id", &stmt); size_t buf_size = impulse_stmt_buffer_size(stmt); impulse_stmt_bind_node(stmt, "uid", 42); impulse_stmt_execute(stmt, preallocated_buffer, buf_size); const uint64_t* ids = (const uint64_t*)impulse_stmt_column_data(stmt, 0); impulse_stmt_finalize(stmt); ``` === "Python" ```python from impulse_graph import Snapshot with Snapshot("social.imps") as snap: followed = snap.traverse(start_node=42, catalog={"FOLLOWS": 0}).out("FOLLOWS").to_list() friend_ids = snap.cypher( "MATCH (u:User)-[:FOLLOWS]->(f:User) WHERE u.id = $uid RETURN f", params={"uid": 42}, catalog={"FOLLOWS": 0}, ) row_offsets = snap.get_row_offsets_array(0) col_indices = snap.get_col_indices_array(0) ``` --- ## Explore the Documentation * **[Getting Started](getting-started/index.md)** & **[Ecosystem Hubs](ecosystems/index.md)**: Problem-first onboarding for [Java/JVM](ecosystems/java/index.md), [Python/PyTorch](ecosystems/python/index.md), and [C++/Rust/Polyglot](ecosystems/native/index.md). * **[Querying & DSLs Decision Matrix](query-api/index.md)**: Choose between AOT/Fluent Java & Python APIs, Google CEL, openCypher, ImpLog, and ImpK. * **[Why Impulse Graph?](concepts/why-impulse.md)** & **[Data-Oriented Design](concepts/data-oriented-design.md)**: CSR/CSC locality, per-domain dense IDs, pre-allocated query buffers, and Java vs. C++ performance analysis. * **[SDK References](reference/java-api.md)**: [Java](reference/java-api.md) ([Javadocs](/javadoc/index.html)), [Python](reference/python-api.md), [C / C++20](reference/c-abi.md), [Rust](reference/rust-api.md), and [CLI](reference/cli.md). * **[Specifications & Validation](reference/spec/format-specification.md)**: [`.imps` Format](reference/spec/format-specification.md), [ImpulseVM ISA](reference/spec/vm-specification.md), [Schema Spec](reference/spec/schema-specification.md), [Polyglot Validation](contributing/polyglot-validation.md), and [Benchmarks](benchmarks.md). ================================================================================ FILE: docs/benchmarks.md | URL: https://www.impulsegraph.org/benchmarks/ ================================================================================ # Impulse Graph Engine Benchmarks & Performance ## Executive Summary Once both Impulse Graph engines map the same `.imps` CSR/CSC and SoA segments off-heap and scan them with SIMD (`jdk.incubator.vector` vs. Highway / OpenMP), throughput is bounded primarily by DRAM bandwidth and cache-line transfers rather than the language runtime. * **Sub-10 Millisecond JVM Cold Start (`341x` Faster than GAPBS `.sg`)**: Off-heap `FileChannel.map` paired with JDK 25 Project Leyden AOT Caching (`-XX:AOTCache`) loads the **6.04 GB `twitter-2010.imps`** snapshot (`1.47B` edges, `41.65M` nodes) in **`9.748 ms`** (and **`0.038 ms`** in C++20 `mmap`), compared to `3,326.05 ms` for standard GAPBS `.sg` file loading and `612.31 ms` for Apache Arrow IPC record-batch loading. * **Pure Java 25 Within `1.65x` of 10-Thread Native C++20**: On full-graph direction-optimizing Breadth-First Search (BFS) across all 1.47 billion edges of `twitter-2010`, the Native C++20 kernel executes in **`145.00 ms`** (10 threads) and the warmed Pure Java 25 engine executes in **`240.29 ms` (`1.65x`)**—with **zero heap object allocations** in the hot loop. * **Sub-10 Microsecond Targeted Queries & Polyglot FFI**: Targeted multi-hop traversals execute in **`4.13 µs`** in Java 25 (post-C2 JIT warmup) and **`18.4 µs – 26.8 µs`** across C++20, Rust, Go, Python, .NET, and Node.js on the 2.25M-edge Hetionet biomedical graph. ```mermaid graph LR subgraph ColdStart["Cold Start Load (twitter-2010, 6.04 GB)"] GAPBS_Load["Standard GAPBS C++ (.sg)
3,326.05 ms"] Arrow_Load["Apache Arrow IPC
612.31 ms"] Java_Load["Impulse Java 25 (mmap + Leyden AOT)
9.75 ms"] Cpp_Load["Impulse C++20 (mmap)
0.038 ms"] end subgraph MicroQuery["Full-Graph 10T BFS & Micro-Query"] Bfs_Cmp["Full-Graph 1.47B-Edge BFS (10T)
C++20: 145.00 ms │ Java 25: 240.29 ms (1.65x)"] C2_JIT["Targeted Multi-Hop BFS (C2 JIT)
4.13 µs / query"] end Java_Load --> Bfs_Cmp Cpp_Load --> Bfs_Cmp Java_Load --> C2_JIT ``` --- ## 1. Full-Graph `twitter-2010` Macro-Benchmarks (1.47B Edges, 41.65M Nodes) All macro-benchmarks below were executed on an **Apple Silicon M-Series (ARM64 NEON 128-bit SIMD, 10 Threads)** platform over the canonical **`twitter-2010.imps` Graph Snapshot** (**6.040 GB**, **1,468,365,182 Edges**, **41,652,230 Nodes**): ### 1.1 Cold-Start Dataset Load Time (`twitter-2010`, 6.04 GB) | Loader / Format | Cold-Start Load Latency | Speedup vs. Stock GAPBS (`.sg`) | Architectural Mechanism | | :--- | :---: | :---: | :--- | | **Stock GAPBS C++ (`.sg` Deserialize)** | `3,326.05 ms` | `1.0x` Baseline | Heap allocation + file read into CSR buffers | | **Apache Arrow IPC (`mmap` + `ReadRecordBatch`)** | `612.31 ms` | `5.4x` | `66.0 ms` `mmap` + `546.2 ms` Arrow record-batch extraction | | **Impulse Java 25 VM (Standard Cold JVM)** | `14.557 ms` | `228.5x` | Off-heap `FileChannel.map` (`READ_ONLY`) + catalog slice setup | | **Impulse Java 25 VM (`-XX:AOTCache` Leyden AOT)** | **`9.748 ms`** | **`341.2x`** | Off-heap `FileChannel.map` + pre-linked Leyden AOT class/method cache | | **Impulse Native C++20 Kernel (`impulse_snapshot_open`)** | **`0.038 ms`** (`38 µs`) | **`87,527x`** | Direct OS `mmap` + 4KB Page 0 header pointer cast | ### 1.2 Head-to-Head Full-Graph Direction-Optimizing BFS (Root 0, 1.47B Edges) In head-to-head full-graph Breadth-First Search (BFS) from Hub Node 0 (`35,016,137` reachable nodes across `1,468,365,182` edges), the warmed Pure Java 25 engine executes within **`1.65x` of native compiled C++20** (closing from an initial `1.87x` baseline after hoisting `VmQueryContext` bitset allocations outside the BFS level loop): | Benchmark Configuration (`twitter-2010.imps`, Root 0) | Threads | Cold Latency | Warmed Latency (HotSpot C2) | Speedup vs. 1T GAPBS C++ | Ratio vs. 10T Native C++20 | | :--- | :---: | :---: | :---: | :---: | :---: | | **Stock GAPBS C++ Baseline** | 1 Thread | `13,305 ms` | `13,305 ms` | `1.0x` | `91.8x` slower | | **Stock GAPBS C++ (OpenMP)** | 10 Threads | `149.00 ms` | `149.00 ms` | `89.3x` | `1.03x` | | **Impulse Native C++20 Kernel** | 10 Threads | **`145.00 ms`** | **`145.00 ms`** | **`91.8x`** | **`1.00x` Baseline** | | **Impulse Pure Java 25 VM (Optimized)** | 1 Thread | `4,420 ms` | `1,015.99 ms` | `13.1x` | — | | **Impulse Pure Java 25 VM (Baseline)** | 10 Threads | `1,130 ms` | `272.24 ms` | `48.8x` | `1.87x` | | **Impulse Pure Java 25 VM (Optimized)** | 10 Threads | `942 ms` | **`240.29 ms`** | **`55.4x`** | **`1.65x` of C++20** | ### 1.3 Connected Components (`OP_CC_AFFOREST`) & PageRank (`OP_MXV`) on `twitter-2010` | GAPBS Algorithm Workload (`twitter-2010.imps`, 10 Threads) | Stock GAPBS C++ (10T) | Impulse Native C++20 (`impulse_vm.cpp`) | Impulse Java VM (HotSpot C2) | Impulse Java VM (Graal JIT) | Notes / Primary Kernel | | :--- | :---: | :---: | :---: | :---: | :--- | | **Connected Components (CC)** *(39,681,514 components)* | `138.69 ms` | `156.73 ms` | `349.60 ms` | **`311.23 ms`** | Afforest neighbor sampling + lock-free Union-Find (`OP_CC_AFFOREST`) | | **PageRank (PR, per iteration)** *(10 Iterations)* | `2,286.45 ms` | `1,940.12 ms` | `1,890.30 ms` | **`1,680.10 ms`** | CSR/CSC SpMV pull accumulation (`OP_MXV` + `jdk.incubator.vector`) | ### Why Native C++20 Retains a `1.5x–2.0x` (`1.65x`) Edge on Full-Graph BFS Java Flight Recorder (**JFR**) allocation profiling and `-XX:+PrintCompilation` confirm that **zero `java.lang.Object` heap allocations** occur inside the Java 25 BFS inner loop. The residual `1.65x` speed advantage of the native C++20 kernel comes down to three low-level runtime invariants that the JVM cannot completely elide in data-dependent CSR loops: 1. **`MemorySegment` Bounds & Liveness Checking**: Even with `ValueLayout.JAVA_INT_UNALIGNED`, the Java 25 FFM API validates segment bounds and arena scope liveness, adding ~1 cycle per random CSR read compared to raw C pointer dereference. 2. **JVM Safepoint Polling**: HotSpot inserts safepoint poll instructions at loop back-edges, adding ~1–3 cycles per inner loop iteration for thread coordination. 3. **`ForkJoinPool` Task Dispatch vs. OpenMP**: Java's work-stealing `ForkJoinPool` incurs ~200–500 ns of task dispatch overhead compared to OpenMP's lightweight static thread scheduling. --- ## 2. Project Leyden AOT, Single-Query Micro-Latencies & Polyglot FFI Overhead ### 2.1 JDK 25 Project Leyden AOT Cache & HotSpot C2 Tier-4 Warmup (`twitter-2010.imps`) | Workload / Experiment Mode (`twitter-2010.imps`) | JVM Flags / AOT Mode | Warmup Iterations | Cold-Start Load Time | First Invocation Latency | Post-Warmup Steady Latency | | :--- | :--- | :---: | :---: | :---: | :---: | | **BFS Baseline (Cold JVM)** | Standard JVM flags | `0` | `14.557 ms` | `332 µs` (`0.332 ms`) | — | | **BFS Leyden AOT Production** | `-XX:AOTCache=impulse.aotcache` | `0` | **`9.748 ms`** (`1.49x` faster) | `369 µs` (`0.369 ms`) | — | | **BFS Vector API + C2 JIT** | `--add-modules jdk.incubator.vector` | `10,000` | `5.784 ms` | `222 µs` (`0.222 ms`) | **`4.13 µs`** (`0.0041 ms`) | | **CC Baseline (Cold JVM)** | Standard JVM flags | `0` | `16.501 ms` | `776 µs` (`0.776 ms`) | — | | **CC Leyden AOT Production** | `-XX:AOTCache=impulse_cc.aotcache` | `0` | **`9.899 ms`** (`1.67x` faster) | **`321 µs`** (**`2.42x` faster cold**) | — | | **CC Vector API + C2 JIT** | `--add-modules jdk.incubator.vector` | `10,000` | `5.784 ms` | `329 µs` (`0.329 ms`) | **`9.88 µs`** (`0.0098 ms`) | | **Powergrid N-2 Outage Sweep** | Pure Java 25 VM | `10,000` | — | — | **`3.33 µs` / pair** (`300,000 outages/sec`) | ### 2.2 Multi-Language FFI Binding Overhead (Hetionet Biomedical Graph: 47K Nodes, 2.25M Edges) Evaluating a 4-hop drug-repurposing traversal (`Disease::DOID:10652 -> [:DaG] -> [:GpPW] <- [:GpPW] <- [:CbG]`, returning `1,317` candidate compounds) across all C-ABI language bindings: | Language / SDK Binding | Runtime Environment | Mean 4-Hop Latency | FFI Overhead vs. Native C++20 | | :--- | :--- | :---: | :---: | | **Native C++20** (`impulse-cpp`) | Clang, Computed Goto + SIMD | **`18.4 µs`** | Baseline (`0.0 µs`) | | **Rust** (`impulse-rust`) | Safe Rust Wrapper over C-ABI | **`19.1 µs`** | `+0.7 µs` | | **Go** (`impulse-go`) | Go CGo | **`21.5 µs`** | `+3.1 µs` | | **C# / .NET** (`impulse-dotnet`) | .NET P/Invoke (`LibraryImport`) | **`23.0 µs`** | `+4.6 µs` | | **Python** (`impulse-python`) | Python `pybind11` | **`24.2 µs`** | `+5.8 µs` | | **Node.js** (`impulse-node`) | Node.js N-API | **`26.8 µs`** | `+8.4 µs` | | *Comparison: PyTorch Geometric (PyG)* | *In-Memory CSR Tensor* | *`850.0 µs`* (`0.85 ms`) | *`46.2x` slower (`450 ms` cold load)* | | *Comparison: Python NetworkX* | *In-Memory Python Dicts* | *`42,100.0 µs`* (`42.1 ms`) | *`2,288x` slower (`1,850 ms` cold load)* | *Note on Python baseline comparisons: PyTorch Geometric (PyG 2.4.0) and NetworkX (3.2.1) benchmarks were executed in-process on Python 3.11 under macOS ARM64 using pre-loaded CSR adjacency tensors and in-memory adjacency dictionaries respectively.* --- ## 3. Enterprise Service Reality: JSON Serialization Is Slower Than the Graph Query Why is `1.65x` of C++20 wholly suitable for demanding enterprise workloads? Because in real-world microservice architectures (Spring Boot, REST/gRPC APIs, ReBAC authorization servers), **formatting the response into JSON consumes far more CPU time than the Impulse Graph query itself.** When we profiled enterprise ReBAC authorization and navigation queries with **Java Flight Recorder (JFR)** and ran a 100,000-operation in-process side-by-side benchmark (`JsonVsCsrBenchmarkRunner`) comparing off-heap CSR query evaluation against Jackson (`ObjectMapper`) JSON serialization to `/dev/null` over an enterprise directory corpus of 600,000 user entities with realistic hierarchical permissions: | Operation (100,000-Request Benchmark) | Average Latency | Relative CPU Cost vs. CSR Query (`large`) | | :--- | :---: | :--- | | **Impulse Java 25 Multi-Hop CSR Query (`small` corpus)** | **`0.026 µs`** (`26 ns`) | `0.047x` (**`73.4x` faster than JSON stream**) | | **Impulse Java 25 Multi-Hop CSR Query (`medium` corpus)** | **`0.088 µs`** (`88 ns`) | `0.159x` (**`21.7x` faster than JSON stream**) | | **Impulse Java 25 Multi-Hop CSR Query (`large` corpus, 600k users)** | **`0.552 µs`** (`552 ns`) | **`1.00x` Baseline** | | **Jackson Streaming JSON Serialization (`/dev/null`)** | **`1.908 µs`** (`1,908 ns`) | **`3.46x` MORE CPU than the graph query** | | **Jackson JSON String + UTF-8 Byte Output (`/dev/null`)** | **`2.558 µs`** (`2,558 ns`) | **`4.63x` MORE CPU than the graph query** | While the Impulse Graph engine executes SIMD vector reads and bitwise `OR` reductions in L1/L2 cache with zero heap allocations, Jackson must allocate heap buffers, inspect DTO fields, and encode integers and UUIDs into UTF-8 JSON characters. When serializing the HTTP response takes `3.5x–73x` longer than traversing the graph, the Pure Java 25 engine gives enterprise teams near-C++ memory-bandwidth speed with **zero JNI deployment complexity** and **zero inherited CVEs**. --- ## 4. Architectural Pillars of Java VM Excellence ### 1. Zero-Copy Off-Heap Scaling All graph relation offsets, target lists, and property vectors are accessed zero-copy off-heap via Java 25 Foreign Function & Memory (FFM) `FileChannel.map` and `MemorySegment.asSlice(...)`. Zero JVM heap garbage collection occurs during query execution. ### 2. JDK 25 Project Leyden AOT Cache (`-XX:AOTCache`) Leyden AOT pre-maps class hierarchies, LambdaForms, MethodHandle linkages, and C2 profiles into `impulse.aotcache`. Cold-start JVM launch time is reduced from **$14.55\text{ ms}$ down to $9.74\text{ ms}$** with zero warmup delay. ```bash # Production Launch with Zero JIT Cold Start java --enable-preview --add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED \ -XX:AOTCache=impulse.aotcache \ -jar impulse-platform.jar ``` ### 3. Java 25 Vector API (`FloatVector.SPECIES_PREFERRED` SIMD) Fused edge attribute filtering in `RelationSnapshot.java` uses hardware-adaptive SIMD vector tiles (`FloatVector.fromMemorySegment` with `FLOAT_SPECIES`), automatically dispatching **128-bit ARM NEON** instructions on Apple Silicon / AWS Graviton and **256-bit AVX2 / 512-bit AVX-512** instructions on x86_64 servers when neighbor degree meets the optimization threshold (`count >= 64`): ```java // RelationSnapshot.java SIMD Vectorized Edge Filtering private static final VectorSpecies FLOAT_SPECIES = FloatVector.SPECIES_PREFERRED; public void copyTargetsSimdFilteredFloat(int nodeId, MemorySegment attrSegment, float threshold, byte cmpOp, ImpulseBitSet outBs) { long start = readEdgeIndex(rowOffsetsSegment, nodeId); long end = readEdgeIndex(rowOffsetsSegment, nodeId + 1); int count = (int) (end - start); if (count <= 0) return; int i = 0; if (nodeIdWidth == 4 && count >= OptimizerConfig.SIMD_PREDICATE_EVAL_MIN_DEGREE_THRESHOLD) { int upperBound = FLOAT_SPECIES.loopBound(count); VectorOperators.Comparison op = switch (cmpOp) { case CMP_GT -> VectorOperators.GT; case CMP_GTE -> VectorOperators.GE; case CMP_LT -> VectorOperators.LT; case CMP_LTE -> VectorOperators.LE; case CMP_EQ -> VectorOperators.EQ; case CMP_NEQ -> VectorOperators.NE; default -> VectorOperators.GE; }; for (; i < upperBound; i += FLOAT_SPECIES.length()) { var vecAttr = FloatVector.fromMemorySegment( FLOAT_SPECIES, attrSegment, (start + i) * 4L, ByteOrder.LITTLE_ENDIAN ); var mask = vecAttr.compare(op, threshold); for (int lane = 0; lane < FLOAT_SPECIES.length(); lane++) { if (mask.laneIsSet(lane)) { outBs.set(columnTargetsSegment.getAtIndex(ValueLayout.JAVA_INT_UNALIGNED, start + i + lane)); } } } } for (; i < count; i++) { float val = attrSegment.getAtIndex(ValueLayout.JAVA_FLOAT_UNALIGNED, start + i); if (matches(val, cmpOp, threshold)) { outBs.set(columnTargetsSegment.getAtIndex(ValueLayout.JAVA_INT_UNALIGNED, start + i)); } } } ``` ### 4. 512k Frontier ST vs. MT Threshold Heuristic To eliminate thread pool scheduling overhead on small and medium queries, `VmHandlers.java` dynamically evaluates frontier size against `PARALLEL_FRONTIER_THRESHOLD = 524_288`: - **Frontier $< 512,000$ active edges**: Executes single-threaded SIMD with zero thread pool coordination overhead. - **Frontier $\ge 512,000$ active edges**: Automatically switches to multi-threaded parallel execution across physical CPU cores (`ForkJoinPool.commonPool()`). ================================================================================ FILE: docs/status.md | URL: https://www.impulsegraph.org/status/ ================================================================================ # Project Status, Announcements & Roadmap This page tracks the current development status, subsystem readiness, announcements, and the path to the **`v1.0`** release across the **Impulse Graph Engine** ecosystem. For version-by-version changelogs, see **[Release Notes](release-notes.md)**. --- ## Latest Announcements !!! success "November 2026 — Official `v0.10.0` Packages Live on PyPI, Maven Central & crates.io" `v0.10.0` packages are now published and installable directly from public language registries: * **PyPI (`pip install impulse-graph==0.10.0`)**: Pre-built wheels for Linux (`x86_64` / `aarch64`), macOS (`arm64`), and Windows (`amd64`), plus `sdist` with SLSA Level 3 provenance attestations. * **Maven Central (`org.impulsegraph:*:0.10.0`)**: Published `impulse-spec`, `impulse-api`, `impulse-storage`, `impulse-vm`, `impulse-compiler`, `impulse-builder`, `impulse-kotlin`, `impulse-scala_3`, and `impulse-clojure` with `-sources.jar` and `-javadoc.jar` artifacts. * **crates.io (`cargo add impulse-graph@0.10.0`)**: Self-contained `.crate` bundling the C++20/Highway kernel sources (with optional `IMPULSE_SDK_DIR` prebuilt SDK override). !!! tip "November 2026 — Impulse Graph `v0.10.0` Released" Tagged `v0.10.0` across `impulse-graph-spec`, `impulse-graph-core`, `impulse-graph-java`, `impulse-ocaml`, and `impulse-verification`: * **Binary Snapshot Format `v0.10.0` (`0x000A`)**: Inline node domain attributes, virtual/flat/COO relation layouts, nullable attribute bitmaps, `INT8`/`INT16` primary keys, and Section 2.6 `IMP_INDEX_VAMANA_ANN = 0x08`. * **Multi-Lane Bit-Sliced Frontiers (`TYPE_LANE_FRONTIER = 0x10`, `0xC0`..`0xC9`) & Embedded Vamana ANN (`0xCA`..`0xCB`)**: 8/16/32/64-bit bit-sliced multi-lane execution, counterfactual edge trip masks, delta-frontier fixpoint tracking, `BQ1`/`SQ8`/`FP16` quantized routing, and exact SIMD reranking across C++, Java, Rust, and OCaml. * **Kleene 3VL, 54-Function CEL & Compiler Parity**: Full Kleene 3-valued logic, `VmCelEvaluator` / `kleisli_json_runner`, NaN/signed-zero/nullability parity, and `ImpK` / `ImpLog` / `CypherCompiler` lowering for multi-lane and vector ANN queries. * **Unified `impulse-cli`, Security & Compatibility**: Consolidated `impulse-cli` inside `impulse-graph-core`, eliminated `thrift` (`CVE-2026-43868`) via Arrow/Parquet `60.1.0`, updated `jackson-*` to `2.18.11`, restored JDK 21 LTS FFM compatibility alongside JDK 22+/25 LTS, and hardened parsers/VM with ASan/UBSan/TSan, libFuzzer, and Jazzer. !!! info "October 2026 — Unified Documentation Portal & API References" * **Documentation Website (`www.impulsegraph.org`)**: Overhauled the documentation portal (currently **85% complete**), integrating [Data-Oriented Design](concepts/data-oriented-design.md) guides, [Aggregated Java Javadocs](/javadoc/index.html), and the [C-ABI Kernel & VM Reference](reference/c-abi.md). * **Pure Read-Only Engine Architecture Finalized**: Core execution kernels (`impulse-graph-java` and `impulse-graph-core`) focus 100% on read-only, lock-free vector traversals over immutable `.imps` binary snapshots. * **Java `MethodHandle` Combinator JIT & Lua-Inspired VM**: Completed `ImpulseMethodHandleCompiler` and `ShaderCompiler` pipeline fusion in the Pure Java engine alongside four-way polyglot VM parity. --- ## Subsystem Readiness Matrix | Subsystem / Repository | Status | Readiness | Notes | | :--- | :--- | :--- | :--- | | **[Binary Snapshot Format (`.imps`)](reference/spec/format-specification.md)** | Frozen (`v0.10.0`) | [=100% "100%"] | Format `v0.10.0` (`tc01`–`tc38` vectors) and Section 2.6 `IMP_INDEX_VAMANA_ANN` (`0x08`) | | **[Four-Way Polyglot VM Parity](contributing/polyglot-validation.md)** | Passing | [=100% "100%"] | Bitwise consensus across C++ (`-O3`/`-O0`), Java 25, and OCaml (`166/166` opcodes, `531` `.impas` vectors via `ICTX` v1) | | **[Pure Java Engine (`impulse-graph-java`)](reference/java-api.md)** | `v0.10.0` Live | [=95% "95%"] | Dual-target JDK 21 LTS & JDK 22+/25 LTS, FFM off-heap engine, `MethodHandle` JIT, Multi-Lane & Vamana ANN | | **[Native C++20 / C-ABI Engine (`impulse-graph-core`)](reference/c-abi.md)** | `v0.10.0` Live | [=95% "95%"] | C++20 & C-ABI kernel (`libimpulse_graph`), Highway SIMD, OpenMP, `TYPE_LANE_FRONTIER` & `0xC0`..`0xCB` | | **[Multi-Frontend Compiler (`ImpScheme` / `openCypher` / `CEL`)](concepts/compiler-architecture.md)** | `v0.10.0` Tagged | [=90% "90%"] | Two-stage optimizer (logical AST rewriting + cost-based physical selection), Multi-Lane width selection & SQLite-style prepared statements | | **[Documentation Portal (`impulse-website`)](index.md)** | Active | [=85% "85%"] | Core guides, specifications, Javadocs & C-ABI references live; remaining tutorials in progress | | **[Developer CLI Suite (`impulse-cli`)](reference/cli.md)** | `v0.10.0` Tagged | [=90% "90%"] | Consolidated in `impulse-graph-core/impulse-cli`: `build`, `inspect`, `validate`, `compile`, `assemble`, `disassemble`, `run`, `index`, `sample`, `transmute`, `attach-embeddings`, `bench-vector`, `opt` | | **[Polyglot Language SDKs](software-modules.md)** | Beta | [=80% "80%"] | Python (`pybind11` / NumPy / PyTorch), Rust (`impulse-rust`), Go (`CGo`), .NET/C# (`P/Invoke`), Node.js (`N-API`) | --- ## Target Package Registry Distribution Status !!! note "Registry & Pre-v1.0 Distribution" **Maven Central**, **PyPI**, and **crates.io** are live for `v0.10.0`. Pre-built CLI/SDK binaries (`.deb`, `.rpm`, `.pkg`, `.msi`, `.tar.gz`) are available on GitHub Releases, while **NuGet** and **npm** registry publishing is staged for `v1.0`. | Package Manager / Registry | Target Ecosystem | Package Coordinates / Artifacts | Status | Readiness | Notes | | :--- | :--- | :--- | :--- | :--- | :--- | | **[Maven Central](reference/packages.md)** | Java 25 / Kotlin / Scala 3 / Clojure | `org.impulsegraph:impulse-api`, `impulse-storage`, `impulse-vm`, `impulse-compiler`, `impulse-builder`, `impulse-spec`, `impulse-kotlin`, `impulse-scala_3`, `impulse-clojure` | Live (`0.10.0`) | [=100% "100%"] | Signed & published on Maven Central with `-sources.jar` and `-javadoc.jar` | | **[PyPI](reference/python-api.md)** | Python (`>= 3.9`) | `impulse-graph` (`manylinux`, `macosx_11_0_arm64`, `win_amd64` wheels & `sdist`) | Live (`0.10.0`) | [=100% "100%"] | Static C++20 `pybind11` wheels with zero-copy NumPy, SciPy CSR, and PyTorch `mmap` tensor views | | **[Crates.io](reference/rust-api.md)** | Rust (`2021` Edition) | `impulse-graph` | Live (`0.10.0`) | [=100% "100%"] | Self-contained Rust crate (`cargo add impulse-graph@0.10.0`) with bundled C++20/Highway sources | | **[NuGet.org](reference/polyglot-sdks.md)** | .NET 8+ / C# / F# | `ImpulseGraph`, `ImpulseGraph.Native`, `ImpulseGraph.FSharp` | Beta | [=80% "80%"] | Managed P/Invoke SDK + cross-platform native runtime packs (staged for `v1.0`) | | **[npm](reference/polyglot-sdks.md)** | Node.js / TypeScript / Bun | `impulse-graph` | Beta | [=80% "80%"] | N-API native addon + TypeScript `.d.ts` definitions (staged for `v1.0`) | | **[Go Modules](reference/polyglot-sdks.md)** | Go (`1.22+` CGo) | `github.com/impulse-graph/impulse-graph/go` | Beta | [=80% "80%"] | CGo bindings linked against `libimpulse_graph_static.a` | | **[Vcpkg / Conan / Homebrew](reference/c-abi.md)** | C / C++20 & macOS/Linux CLI | `impulse-graph` (`libimpulse_graph_static.a`, `.dylib`, `.so`, `.dll`, `.deb`, `.rpm`, `.pkg`, `.msi`) | In Progress | [=75% "75%"] | CMake install targets & static packaging ready; registry port manifests staged for `v1.0` | | **[GHCR / Docker](reference/packages.md)** | Containers / Kubernetes | `ghcr.io/impulse-graph/impulse-tools`, `impulse-platform-server` | In Progress | [=75% "75%"] | Static `musl-libc` Alpine/scratch CLI & platform server images | --- ## Goals Before `v1.0` Release - [x] Finalize `.imps` Binary Snapshot Format (`v0.10.0`) - [x] Achieve four-way VM parity across C++, Java 25, and OCaml ([Polyglot Validation](contributing/polyglot-validation.md)) - [x] Implement 64-register VM (`R0`..`R63`) and Java 25 `MethodHandle` JIT compilation - [x] Focus core kernels on lock-free, read-only `.imps` traversal - [x] Launch documentation site (`www.impulsegraph.org`) with Javadocs and C-ABI references - [x] Release `v0.10.0` across all core repos (Multi-Lane `0xC0`..`0xC9`, Vamana ANN `0x08` / `0xCA`..`0xCB`, Kleene 3VL & 54-func CEL) - [x] Publish `0.10.0` packages to Maven Central, PyPI, and crates.io - [ ] Complete remaining documentation (cookbooks, operational runbooks, and showcase deep dives) - [ ] Publish NuGet and npm packages and finalize `v1.0` release pipelines - [ ] Publish complete reproducible empirical benchmark suite (`impulse-benchmarks`) across hardware targets --- ## Post-`v1.0` Roadmap ### 1. Multi-Snapshot Federated Traversals (C-ABI & Cross-Snapshot VM Opcodes) * Note: Composite multi-file `manifest.yaml` loading into a unified `GraphSnapshot` is supported today in the Pure Java 25 engine via `BinarySnapshotLoader.loadFromManifest(manifestPath, arena)`. * Post-`v1.0` extends this to cross-snapshot relation namespacing (`SnapshotA::RelationName`) in C-ABI and `ImpulseVM` bytecode, allowing a single VM pipeline to traverse across independently versioned `.imps` files via zero-copy dense ID translation vectors (`OP_REMAP_ID_SPACE`). ### 2. GPU & Accelerator Offload (`cuFile` GPUDirect Storage) * Direct DMA transfers of 128-byte-aligned `.imps` CSR and SoA sections into NVIDIA GPU HBM via `cuFile` (GPUDirect Storage), bypassing host CPU page cache for multi-terabyte graph analytics and GNN neighborhood sampling. ### 3. Cost-Based Optimizer (CBO) & Adaptive Runtime Execution * Expanded histogram and characteristic-set cardinality estimation in Section 2 catalog headers for multi-join `openCypher` and `ImpLog` Datalog rule ordering. ================================================================================ FILE: docs/release-notes.md | URL: https://www.impulsegraph.org/release-notes/ ================================================================================ # Release Notes Chronological technical changelog across the **Impulse Graph Engine** repositories (`impulse-graph-spec`, `impulse-graph-core`, `impulse-graph-java`, `impulse-ocaml`, and `impulse-verification`). --- ## `v0.10.0` — Multi-Lane Bit-Sliced Execution, Embedded Vamana ANN & Registry Packages **Release Date**: November 2026 **Format Version**: `.imps` Binary Snapshot Format `v0.10.0` (`0x000A`) ### 1. Public Package Registry Availability * **Maven Central (`org.impulsegraph:*:0.10.0`)**: Signed artifacts (`-sources.jar`, `-javadoc.jar`) published for `impulse-spec`, `impulse-api`, `impulse-storage`, `impulse-vm`, `impulse-compiler`, `impulse-builder`, `impulse-kotlin`, `impulse-scala_3`, and `impulse-clojure`. * **PyPI (`impulse-graph==0.10.0`)**: Pre-built `pybind11` wheels for Linux (`manylinux` `x86_64` / `aarch64`), macOS (`arm64`), and Windows (`amd64`), plus `sdist` with SLSA Level 3 build provenance attestations. * **crates.io (`impulse-graph@0.10.0`)**: Self-contained Rust crate bundling the C++20 and Highway SIMD kernel sources (with optional `IMPULSE_SDK_DIR` override for pre-installed native SDKs). * **GitHub Releases & Cosign v3 Attestations**: Standalone `impulse-cli` and C/C++20 SDK archives signed with Sigstore Cosign v3 (`--bundle SHA256SUMS.sigstore.json`) and GitHub Artifact Attestations. ### 2. Binary Snapshot Format `v0.10.0` (`0x000A`) * **Embedded Vamana ANN Index (`IMP_INDEX_VAMANA_ANN = 0x08`)**: Added Section 2.6 disk-aligned Vamana proximity graph index supporting two-stage quantized routing (`BQ1` 1-bit binary, `SQ8` scalar 8-bit, `FP16` half-precision, or `NONE`) paired with exact SIMD reranking over 128-byte-aligned `[N, D]` embedding columns. * **Domain & Relation Layout Extensions**: Added inline node domain attribute tables, virtual/flat/COO relation encodings alongside CSR/CSC, nullable attribute validity bitmaps, `INT8`/`INT16` compact primary keys, and compliance test vectors through `tc38`. ### 3. `ImpulseVM` ISA Extensions (`0xC0`..`0xCB`) * **Multi-Lane Bit-Sliced Frontiers (`TYPE_LANE_FRONTIER = 0x10`, `0xC0`..`0xC9`)**: Generalized 1-bit node frontiers to 8-, 16-, 32-, and 64-lane bit-sliced word arrays (`OP_LANE_INIT_SEEDS`, `OP_LANE_INIT_GROUPS`, `OP_LANE_WALK`, `OP_LANE_SET_EDGE_MASK`, `OP_LANE_PRUNE_MASK`, `OP_LANE_FILTER_QUORUM`, `OP_LANE_REDUCE_AND`, `OP_LANE_REDUCE_ATTR`, `OP_LANE_SET_COVER`) to evaluate batched seed queries and $N-1$ counterfactual edge-outage sweeps in a single CSR scan without expanding the 640-byte VM register frame. * **Vector ANN Search & Reranking (`0xCA`..`0xCB`)**: Added `OP_VECTOR_ANN_SEARCH` and `OP_VECTOR_RERANK_DOT` for single-pass hybrid graph + vector candidate retrieval inside `ImpulseVM`. * **Four-Way Polyglot Parity**: Verified bitwise register, PC, status, and `ICTX` v1 SHA-256 state-hash identity across C++ (`-O3`), C++ (`-O0`), Pure Java 25, and the OCaml reference oracle (`166/166` active opcodes across `531` `.impas` compliance vectors). ### 4. Compiler, Query Surfaces & Runtime Hardening * **Kleene 3-Valued Logic (3VL) & 54-Function CEL**: Implemented full Kleene `TRUE`/`FALSE`/`NULL` propagation across nullable columns, IEEE-754 `NaN`/signed-zero parity, and 54 built-in Google CEL functions across Java and C++. * **Frontend Lowering**: Added multi-lane traversal (`MultiLaneBuilder` / `MultiLaneTraversal`) and vector ANN lowering across the Fluent API, `openCypher`, `ImpLog`, and `ImpK`. * **Java 21 LTS & Java 22+/25 Dual-Target Runtime**: Restored full JDK 21 LTS FFM compatibility alongside JDK 22+/25 LTS, added bounded shared virtual-thread bitset/state buffer pools in `impulse-vm`, and expanded JMX / Prometheus engine telemetry. * **CLI Consolidation & Dependency Hygiene**: Consolidated developer tooling into `impulse-graph-core/impulse-cli` (`attach-embeddings`, `convert-tensors`, `bench-vector`, `--vamana-locality`, `--quick-check`, `--deep-audit`), upgraded Rust Arrow/Parquet to `60.1.0` (removing transitive `thrift` `CVE-2026-43868`), updated `jackson-*` to `2.18.11` in non-core tooling, and added ASan/UBSan/TSan, libFuzzer, Jazzer, and OCaml Bigarray bounds checks. --- ## `v0.9.0` — Register VM, Unified In-Kernel Compiler & Read-Only Snapshot Baseline **Format Version**: `.imps` Binary Snapshot Format `v0.9.0` (`0x0009`) * **128-Byte Aligned `.imps` C-ABI Layout**: Fixed 4KB Page 0 header (`IMPS` magic `0x494D5053`), shared Section 2 string pool, per-domain independent dense IDs ($0 \dots N_d-1$) with configurable `uint16_t` / `uint32_t` / `uint64_t` widths, CSR/CSC adjacency slices, and Structure-of-Arrays (SoA) attribute columns with Arrow-compatible validity bitmaps. * **64-Register `ImpulseVM` & `MethodHandle` JIT**: Fixed 64-bit `impOps` instruction encoding over registers `R0`..`R63`, C++20 Highway SIMD + OpenMP kernels, and Pure Java FFM + `jdk.incubator.vector` + `MethodHandle` combinator compilation. * **SQLite-Style Prepared Statements**: In-kernel `ImpScheme` two-stage optimizing compiler lowering `openCypher`, `CEL`, `ImpLog`, and `ImpK` into caller-buffered `impulse_stmt_t` / `ImpulseStatement` handles (`impulse_stmt_buffer_size`) with zero hot-path heap allocations. * **Pure Read-Only Kernel Architecture**: Removed in-memory mutable delta overlays from core execution kernels in favor of single-pass streaming `SnapshotBuilder` / `impulse build` generation and lock-free RCU Blue/Green snapshot rotation. ================================================================================ FILE: docs/showcase/index.md | URL: https://www.impulsegraph.org/showcase/ ================================================================================ # Showcase Applications: One Engine, Every Domain The showcase applications in the Impulse Graph ecosystem exist for two reasons: 1. **To show how the exact same graph primitives apply across wildly different industries**: Whether your nodes are users and documents, bank accounts, electrical substations, shipping containers, or genes and proteins, underneath they all compile down to the same **domain-to-domain frontier steps, SIMD attribute filters, and monoidic reductions** over `.imps` snapshots. 2. **To show how extreme traversal speed makes *entirely new analyses* practical**: When a multi-hop graph query drops from tens of milliseconds to **microseconds**, you don't just make an existing dashboard faster—you can run **millions of "what-if" simulations in real time** that previously had to be overnight batch jobs (or couldn't be computed at all). --- ## Triggering Your Imagination: How Different Domains Map to Impulse Graph | Industry & Domain | Nodes (Domains) & Edges (Relations) | Core Graph Operation | What Impulse Graph's Speed Makes Practical | | :--- | :--- | :--- | :--- | | **[Security & ReBAC (Zanzibar)](authz.md)** | `User` $\to$ `Group` $\to$ `Role` $\to$ `Resource` | Fixed-point reachability & zero-allocation BitSet lookups | Checking deep, transitive group/folder permissions in-process on API requests (sub-microsecond in 600k-user RBAC benchmarks) with zero external network hops. | | **[FinTech & Anti-Money Laundering](aml.md)** | `Account` $\xrightarrow{\text{TRANSFERRED\_TO}}$ `Account` | Fixed-point cycle detection (`repeatUntilStable`) & `SUM`/`MIN` reductions | Detecting multi-hop circular money-laundering rings and running interactive **"what-if" node-exclusion scenarios** in milliseconds. | | **[Electrical Power Grids](powergrid.md)** | `Substation Bus` $\xrightarrow{\text{BRANCH}}$ `Substation Bus` | Exhaustive $N-1$ & $N-2$ edge-removal island detection | Simulating **all 10.5 million $N-2$ dual-line outage combinations** across a continental grid in **24 seconds** instead of **3+ hours**. | | **Logistics, Shipping & Aviation** *(Upcoming Showcase)* | `Container` $\to$ `Depot/Port` $\xrightarrow{\text{LEG}}$ `Port` | Constrained multi-hop reachability & `MIN` cost reduction | **Recalculating all empty-container repositioning move options** across a shipping fleet (or airline crew/aircraft recovery routes) in real time when a port or hub is disrupted. | | **Pharma, Genomics & Drug Discovery** | `Compound` $\to$ `Protein` $\to$ `Pathway` $\to$ `Gene` $\to$ `Disease` | Multi-domain Kleisli walks & path-weight reduction | Screening millions of multi-hop **drug-pathway-gene interactions** and off-target toxicity cascades interactively over biomedical knowledge graphs (Hetionet, DRKG). | | **[AI & Graph Neural Networks](gnn.md)** | `Node` $\to$ `Neighbor` / `Token` $\to$ `Expert` | Zero-copy `.imps -> PyTorch` `mmap` tensors & C-ABI neighborhood sampling | Training and sampling over **graphs way larger than physical RAM** with `< 1 ms` cold start and `0 bytes` of `DataLoader` worker duplication (impossible with `Parquet -> PyTorch`). | --- ## Explore the Showcases * **[Authorization (ReBAC / Zanzibar)](authz.md)**: Sub-microsecond in-process permission checks paired with periodic `.imps` Blue/Green snapshot rotation. * **[Anti-Money Laundering (AML) & Fraud Rings](aml.md)**: Algorithmic walkthrough of transitive cycle detection and interactive "what-if" intermediary exclusion using `repeatUntilStable` and CEL predicates. * **[Power Grid Stability ($N-1$ & $N-2$ Contingency Simulator)](powergrid.md)**: How zero-copy `.imps` snapshots and SIMD bitsets turn a 3-hour continental grid outage sweep into a 24-second real-time check. * **[Graph Neural Networks & PyTorch (`impulse-gnn`)](gnn.md)**: If you live in PyTorch, you'll be right at home—zero-copy `mmap` tensor views, zero `DataLoader` RAM duplication, and high-speed GPU/CPU sparse matrix operations. ================================================================================ FILE: docs/showcase/authz.md | URL: https://www.impulsegraph.org/showcase/authz/ ================================================================================ # Showcase: ReBAC Authorization (Zanzibar) The **`impulse-authz`** showcase models enterprise hierarchical permissions (users, groups, roles, datasets) and demonstrates how Impulse Graph powers sub-microsecond, fine-grained **Relationship-Based Access Control (ReBAC)**—modeled after Google's Zanzibar architecture—directly inside your application process. --- ## 1. The Real-World Problem In modern enterprise software, permissions aren't just simple role strings—they form a deep hierarchy of relationships: * A `User` belongs to a `Group` (which may be nested inside parent `Group`s). * A `Group` is assigned a `Role`. * A `Role` grants `Permission` over a `Folder` or `Resource` (which itself has child `Document`s). Answering *"Can User $U$ edit Document $D$?"*—or worse, *"Which of these 10,000 search results is User $U$ allowed to see?"*—requires walking a multi-hop graph on **every single API request**. Traditional SQL recursive CTEs or external authorization microservices add milliseconds of network and join latency to every call. --- ## 2. How Impulse Graph Solves It Because authorization policies are read-heavy and change at a human/administrative cadence, they fit Impulse Graph's **"mmap and go"** model naturally: 1. **Multi-Domain Set Traversal**: Starting from a `User`, the query steps across `MEMBER_OF` (with transitive group nesting via `repeatUntilStable`), `HAS_ROLE`, and `GRANTS_ACCESS_TO` to reach the `Resource` domain. 2. **Set Semantics Eliminate Redundant Paths**: If a user belongs to 5 overlapping groups that all grant access to the same parent folder, Impulse collapses those converging paths into a single bit at each step—never walking the folder's children multiple times. 3. **Zero-Allocation Early Exit & Point Tests**: When an intermediate frontier empties (e.g. a user belongs to no groups granting access), the VM halts immediately (`FLAG_HALT_ON_EMPTY`). Single-resource access is verified via an $O(1)$ bit test over the resulting off-heap BitSet (`toBitSet().get((int) targetDenseId)`) without heap allocations. !!! note "Benchmark Context" Sub-microsecond query latencies (`0.026 µs – 0.552 µs`) were measured in empirical microbenchmarks (`JsonVsCsrBenchmarkRunner`) evaluating multi-hop CSR traversals over a simulated directory corpus of 600,000 users with realistic group/role hierarchies (compared directly against Jackson JSON serialization cost). === "Java 25 (Fluent API)" ```java // 1. Check if 'usr_alice' has transitive access to 'doc_quarterly_report' long targetDocId = snap.domain("Resource").toDenseId("doc_quarterly_report"); boolean isAllowed = snap.domain("User") .fromKey("usr_alice") // Walk direct and nested group memberships until fixed-point .out("MEMBER_OF") .repeatUntilStable("PARENT_GROUP") .out("HAS_ROLE") .out("GRANTS_ACCESS_TO") .toBitSet() .get((int) targetDocId); // 2. Or retrieve the full BitSet of all accessible resources in one pass // to filter a search result list in-process in nanoseconds: ImpulseBitSet accessibleResources = snap.domain("User") .fromKey("usr_alice") .out("MEMBER_OF") .repeatUntilStable("PARENT_GROUP") .out("HAS_ROLE") .out("GRANTS_ACCESS_TO") .toBitSet(); ``` === "ImpLog (Declarative Datalog)" ```prolog // Transitive group membership and resource authorization in ImpLog (.implog) in_group(U, G) :- member_of(U, G). in_group(U, ParentG) :- in_group(U, ChildG), group_parent(ChildG, ParentG). can_access(U, R) :- in_group(U, G), has_role(G, Role), grants_access(Role, R). ``` --- ## 3. Keeping Permissions Fresh: Periodic Rebuild & Atomic Swap How do permission changes propagate without introducing reader locks? 1. Administrative permission updates write to your system-of-record database (e.g., PostgreSQL). 2. A background worker periodically compiles a fresh `.imps` authorization snapshot in seconds from your primary database (e.g. via JDBC or CDC Kafka stream) and publishes it to blob storage or local NVMe. 3. Application pods `mmap` the new `.imps` file in `< 1 ms` and perform a **zero-downtime Blue/Green atomic pointer swap** (see [Changing Data & Live Updates](../getting-started/handling-mutations.md)). Active API requests continue running with **zero locks** and **zero GC pauses**. ================================================================================ FILE: docs/showcase/aml.md | URL: https://www.impulsegraph.org/showcase/aml/ ================================================================================ # Showcase: Anti-Money Laundering (AML) & Fraud Rings The **Anti-Money Laundering (AML)** showcase demonstrates how Impulse Graph detects deep circular transaction loops ("layering" fraud rings) and enables interactive **"what-if" link analysis** that traditional relational databases struggle to run at scale. !!! note "Algorithmic Walkthrough" This showcase demonstrates an algorithmic query pattern using the native Impulse Java 25 Fluent API and CEL filter predicates; no external or custom database server is required. --- ## 1. The Real-World Problem In financial crime and money laundering, illicit funds are rarely sent in a single transfer. Instead, fraudsters split and route funds through a complex web of mule accounts and shell entities—often forming a **circular loop**: $$\text{Account } A \to B \to C \to D \to \dots \to \text{Account } A$$ In a relational database (`SELECT ... FROM transfers JOIN transfers ...`), every additional hop multiplies the intermediate rows (`multi-set` path explosion). By hop 5 or 6 on a high-volume transaction network, the query runs out of memory or takes minutes. --- ## 2. How Impulse Graph Solves It Impulse Graph makes deep multi-hop cycle detection and flow aggregation fast enough for interactive investigations: 1. **Set-Based Fixed-Point Reachability (`repeatUntilStable`)**: Instead of generating millions of duplicate path rows, `ImpulseVM` represents the active frontier of reachable accounts as an off-heap **BitSet**. Even if accounts $B$ and $C$ transact back and forth 500 times, converging paths are collapsed into a single bit per account at every step. 2. **Monoidic Flow Reduction (`SUM` / `MIN` / `MAX`)**: When investigators want to track the minimum bottleneck transfer or cumulative flow along a path over the `amount` edge attribute, converging values are reduced in place at each hop. === "Java 25 (Circular Fraud Ring Detection)" ```java // Step 1 hop out from suspectAccountId first (.out), then compute the transitive closure // (.repeatUntilStable) to obtain the positive closure (R+, >= 1 hop). // Note: calling repeatUntilStable directly on the seed computes the reflexive closure (R*, >= 0 hops), // which always includes the starting node itself. ImpulseBitSet reachableAccounts = snap.domain("Account") .from(suspectAccountId) .out("TRANSFERRED_TO") .repeatUntilStable("TRANSFERRED_TO") .toBitSet(); // If the suspect account is in its own >= 1-hop downstream reachable set, a circular ring exists boolean isPartOfFraudRing = reachableAccounts.get((int) suspectAccountId); ``` --- ## 3. What Speed Unlocks: Interactive "What-If" Intermediary Exclusion Because a full multi-hop closure runs in sub-milliseconds to milliseconds over memory-mapped CSR arrays, compliance analysts can ask interactive **"what-if" counterfactual questions** on the fly—without mutating the graph: * *"If we freeze or exclude Intermediary Account $B$, does the circular path back to Account $A$ break, or do alternate mule paths still complete the ring?"* * *"What if we only follow transfers where `edge.amount >= 10000.0`?"* === "Java 25 ('What-If' Node & Edge Exclusion)" ```java // Test whether excluding intermediary 'accountB_Id' and transfers under $10,000 breaks the loop boolean cyclePersists = snap.domain("Account") .from(suspectAccountId) .out("TRANSFERRED_TO", "node.id != @excludedId && edge.amount >= 10000.0") .repeatUntilStable("TRANSFERRED_TO", "node.id != @excludedId && edge.amount >= 10000.0") .withParam("@excludedId", accountB_Id) .toBitSet() .get((int) suspectAccountId); if (!cyclePersists) { System.out.println("Account B is a critical cut-vertex for this fraud ring."); } ``` Because the `.imps` snapshot is read-only and queries execute lock-free across CPU threads, an automated screening job can evaluate candidate cut-vertices concurrently across CPU cores without lock contention or thread synchronization overhead. ================================================================================ FILE: docs/showcase/powergrid.md | URL: https://www.impulsegraph.org/showcase/powergrid/ ================================================================================ # Showcase: Power Grid Real-Time $N-1$ & $N-2$ Contingency Simulator The **`impulse-powergrid`** showcase illustrates how a 100x–300x leap in graph traversal speed doesn't just optimize an existing workflow—it makes an **entirely new operational capability practical in real time**. !!! important **LEGAL & OPERATIONAL DISCLAIMER — RESEARCH & ILLUSTRATIVE USE ONLY**: `impulse-powergrid` is provided **strictly for academic research, software architecture benchmarking, and performance evaluation purposes**. The Pan-European PEGASE test cases contain synthetic, fictitious data. This software is **NOT** certified, designed, or intended for real-time electrical grid operations, physical power dispatch, critical infrastructure control, safety-critical decision making, or live transmission system outage planning. The authors and contributors assume **NO LIABILITY OR RESPONSIBILITY** for any direct, indirect, incidental, special, or consequential damages arising from the use of or reliance upon this software. --- ## 1. The Real-World Problem: Combinatorial $N-2$ Grid Outages An electrical transmission grid is a graph where **Buses** (substations, generators, load centers) are nodes and **Branches** (transmission lines and transformers) are edges. Grid operators are required (under standards like NERC TPL-001 and ENTSO-E security codes) to verify that equipment failures will not split the grid into disconnected "islands" or trigger cascading blackouts: * **$N-1$ Contingency**: What happens if any **1** transmission line trips? ($E$ scenarios) * **$N-2$ Contingency**: What happens if any **2** independent transmission lines fail simultaneously during a storm or wildfire? ($\frac{E(E-1)}{2}$ scenarios) On a regional grid with $E = 4,582$ transmission branches (the Pan-European PEGASE 2869 benchmark), there are **10,495,071 distinct $N-2$ outage pairs**. Using standard Python/NetworkX tools (`PYPOWER`), evaluating all 10.5 million pairs takes **over 3 hours**—making full $N-2$ topology screening an offline planning study rather than a live operational monitor. --- ## 2. How Impulse Graph Turns a 3-Hour Batch Study into a 24-Second Sweep By compiling the grid topology (`Bus` domain and `Branch` CSR arrays + electrical parameters) into a 128-byte-aligned `.imps` binary snapshot, `impulse-powergrid` evaluates $N-2$ contingencies with zero heap allocations: 1. **Instant `< 30 µs` `mmap` Startup**: The entire grid topology and bus/branch attribute vectors (`baseKV`, `Pd`, `Qd`, resistance $r$, reactance $x$, MVA rating) are mapped directly into CPU cache. 2. **In-Place Edge Masking (Zero Graph Copies)**: Instead of cloning a graph object 10.5 million times to remove two edges, each worker thread runs a SIMD-vectorized BFS island check over the *same* immutable `.imps` CSR array, skipping the two tripped branch IDs in hardware registers (`ARM NEON` / `AVX2`) and tracking visited buses in a stack-allocated 64-bit bitset. 3. **Extreme Multi-Core Concurrency**: Because the `.imps` snapshot is read-only and every thread's BFS bitset fits in L1 cache with zero heap allocations, throughput scales linearly across all CPU cores. === "C++20 SIMD Vectorized Island Detector" ```cpp #include #include "powergrid.hpp" // SIMD 4-wide NEON loop checking branch outage matches without mutating the CSR graph uint32x4_t v_tripped = vdupq_n_u32(static_cast(tripped_branch_id)); for (uint64_t e = start; e + 4 <= end; e += 4) { uint32x4_t v_branches = vld1q_u32(&edge_branch_ids[e]); uint32x4_t v_match = vceqq_u32(v_branches, v_tripped); // Extract 128-bit SIMD comparison mask in a single hardware cycle uint64x2_t v_cast = vreinterpretq_u64_u32(v_match); uint64_t m0 = vgetq_lane_u64(v_cast, 0); uint64_t m1 = vgetq_lane_u64(v_cast, 1); // Propagate surviving connected buses in a stack-allocated 64-bit BitSet ... } ``` --- ## 3. Empirical Benchmark Results vs. PYPOWER / NetworkX ### $N-2$ Contingency Screening Comparison (`case1354pegase`, 10 CPU Cores) | Engine Configuration | Pairs Evaluated | Wall Time | Simulation Throughput | Latency / $N-2$ Pair | Relative Speedup | | :--- | :--- | :--- | :--- | :--- | :--- | | **1. PYPOWER / NetworkX (Single-Thread)** | 20,000 pairs | 95,073.19 ms (95.1 s) | 210 pairs/sec | 4,753 $\mu\text{s}$ | **1.0x Baseline** | | **2. PYPOWER / NetworkX (Multi-Thread 10C)** | 20,000 pairs | 20,231.41 ms (20.2 s) | 989 pairs/sec | 1,011 $\mu\text{s}$ | **4.7x Faster** | | **3. Impulse SIMD C++20 (Multi-Thread 10C)** | **378,100 pairs** *(Top 200 $\times E$)* | **263.06 ms (0.26 s)** | **1,437,286 pairs/sec** | **0.69 $\mu\text{s}$** (`0.6957 µs`) | **1,453x vs 10C PYPOWER** (`6,833x` vs 1C baseline; `361.4x` less wall time for `18.9x` more pairs) | !!! note "Throughput vs. Wall-Clock Speedup" In the comparison above, the PYPOWER baseline was capped at `20,000` $N-2$ pairs due to execution time (`95.1 s` single-thread, `20.2 s` on 10 cores), whereas the Impulse C++20 10-core run evaluated all `378,100` top-branch $N-2$ pairs in **`263.06 ms`**—completing **`18.9x` more contingency pairs** in **`361.4x` less total wall-clock time**, representing a **`6,833x` per-pair throughput speedup** (`1,437,286 pairs/sec` vs. `210 pairs/sec`, or **`1,453x`** vs. 10-core PYPOWER). ### 100% Exhaustive $N-2$ Full Grid Sweeps | European Grid Dataset | Buses | Branches | Total $N-2$ Pairs | PYPOWER Multi-Thread Time | Impulse SIMD C++ Time | $N-2$ Throughput | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | **PEGASE 1354 EU Grid** | 1,354 | 1,991 | **1,981,045 pairs** | ~33.6 minutes | **1.96 seconds** | **1,010,250 pairs/s** | | **PEGASE 2869 EU Grid** | 2,869 | 4,582 | **10,495,071 pairs** | ~3.1 hours | **24.49 seconds** | **428,595 pairs/s** | Every simulation output was verified against independent third-party **PYPOWER** and **NetworkX** (`networkx.bridges()`) runs, achieving a **100.00% exact topological match** (`561` islanding outages on PEGASE 1354 and `778` on PEGASE 2869). ### 64-Way Bit-Sliced Multi-Lane Contingency Screening (v0.10.0: `0xC0..0xC7`) While the `v0.10.0` SIMD island detector evaluates one contingency per BFS pass, the **`v0.10.0` Multi-Lane Bit-Sliced Execution** extension (`0xC0..0xC9`) packs **64 independent $N-1$ or $N-2$ branch outage scenarios** into a single 64-bit word per bus (`TYPE_LANE_FRONTIER` = `0x10`, where bit $b \in [0..63]$ represents scenario $b$): 1. **`OP_LANE_INIT_SEEDS` (`0xC0`) & `OP_LANE_SET_EDGE_MASK` (`0xC2`)**: Seeds the baseline component root bus(es) with `active_mask = 0xFFFFFFFFFFFFFFFF` across all 64 lanes and populates `branch_trip_mask[br]` (setting bit $b = 1$ if branch `br` is tripped in scenario $b$, or setting both `branch_trip_mask[i] = active_mask` and `branch_trip_mask[j_base + b] = (1ULL << b)` for 64 simultaneous $N-2$ pairs $(i, j_0 \dots j_{63})$). 2. **`OP_LANE_CSR_WALK` (`0xC3`)**: Advances all 64 contingency wavefronts in lockstep during a **single CSR adjacency scan** via `uint64_t new_bits = (u_mask & ~trip_mask[br]) & ~visited[v]`, amortizing CSR memory reads and branch prediction overhead by up to $64\times$. 3. **`OP_LANE_REDUCE_AND` (`0xC7`)**: Fuses the end-of-wave bitwise `AND` reduction (`all_reached &= visited[u]`) and scratch zeroing pass into a single linear sweep, returning a 64-bit islanding bitmask `active_mask & ~all_reached` where bit $b = 1$ iff contingency lane $b$ disconnected the grid. Empirical results from [`poc_64way_bench.cpp`](https://github.com/impulse-graph/impulse-powergrid/blob/feat/poc-64way-bit-parallel-bench/src/poc_64way_bench.cpp) on `case1354pegase.imps` ($|V| = 1,354$ buses, $|E| = 1,991$ branches, 100% bitwise parity with baseline): | Workload (`case1354pegase.imps`) | Execution Mode | 1-Way Zero-Alloc BFS | 64-Way Bit-Parallel (`0xC0..0xC7`) | 64-Way Throughput | Speedup & Verification | | :--- | :--- | :--- | :--- | :--- | :--- | | **Workload 1: $N-1$ Single-Line Outages** (`1,991` contingencies) | 1 Thread | `7.270 ms` (`273,873 /s`) | **`0.274 ms`** | **`7,259,799 contingencies/s`** | **`26.51x`** vs. Zero-Alloc (**`35.54x`** vs. Baseline; `561` critical branches) | | **Workload 2: $N-2$ Double-Line Outages** (`378,100` pairs, Top-200) | 1 Thread | `1,354.52 ms` (`279,139 pairs/s`) | **`30.41 ms`** | **`12,434,824 pairs/s`** | **`44.55x`** vs. 1-Thread Zero-Alloc (`194,329` critical pairs) | | **Workload 2: $N-2$ Double-Line Outages** (`378,100` pairs, Top-200) | 10 Threads | `258.84 ms` (`1,460,735 pairs/s`) | **`6.11 ms`** | **`61,857,691 pairs/s`** | **`42.35x`** vs. Zero-Alloc (**`53.77x`** vs. Baseline; **`279,595x`** vs. 1T PYPOWER) | | **Workload 4A: 6-Hop Substation Zone MS-BFS** (`1,354` seed buses) | 1 Thread | `1.860 ms` (`727,957 sources/s`) | **`0.533 ms`** | **`2,540,338 sources/s`** | **`3.49x`** (`108,828` zone pairs) | | **Workload 4B: Unbounded All-Pairs MS-BFS** (`1,354` seed buses) | 1 Thread | `10.344 ms` (`130,897 sources/s`) | **`1.655 ms`** | **`818,127 sources/s`** | **`6.25x`** (`1,833,316` reachable pairs) | --- ## 4. Beyond Power Grids: Where Else Does This Pattern Apply? The exact same **"fast exhaustive counterfactual simulation over an immutable `.imps` snapshot"** pattern applies directly to: * **Global Container Shipping & Logistics**: When a port closes or a vessel is delayed, recalculating all valid empty-container repositioning moves and multi-leg transshipment options across thousands of depots in seconds. * **Airline Disruption Recovery**: Evaluating millions of aircraft and crew re-pairing combinations after a hub weather event. * **Telecommunications & Cloud Routing**: Simulating dual-fiber-cut ($N-2$) reachability and latency impact across backbone BGP/MPLS topologies. * **Systems Biology & Pharmacology**: Perturbing combinations of gene knockouts or protein targets across metabolic and signaling pathway graphs to identify synthetic lethality or drug interactions. ================================================================================ FILE: docs/showcase/gnn.md | URL: https://www.impulsegraph.org/showcase/gnn/ ================================================================================ # Showcase: PyTorch & Graph Neural Networks (`impulse-gnn`) Using `.imps` as a storage format for PyTorch removes the decompression, ID-hashing, and multi-worker copy-on-write overhead of loading graphs from Parquet—and exposes native C-ABI neighborhood sampling directly inside Python. --- ## 1. `.imps` vs. `Parquet -> PyTorch` | Capability | `Parquet -> PyTorch` | `Impulse (.imps) -> PyTorch` | | :--- | :--- | :--- | | **Startup** | Seconds to minutes (decompress, hash string keys, sort edges) | Direct `mmap` (`< 1 ms`); dense IDs and CSR/CSC are pre-compiled by `impulse build` | | **Topology Footprint** | `16 bytes/edge` (`[2, E]` `int64` PyG `edge_index`) | `~4 bytes/edge` (`uint32` CSR `col_indices` + `row_offsets`) | | **Multi-Worker `DataLoader`** | Forked workers trigger Python CoW page duplication | Workers share the same read-only OS page cache (`0 bytes` duplicated) | | **Larger-Than-RAM Graphs** | Requires manual chunking (compressed pages cannot be pointer-indexed) | OS demand-pages 4KB blocks from NVMe automatically | !!! note "Showcase Package (`impulse-gnn`)" `impulse_gnn` lives in the [impulse-gnn](https://github.com/impulse-graph/impulse-gnn) showcase repository (not published on PyPI). Install it from a local clone with `pip install -e .`. ```python from impulse_gnn import ImpulseGnnDataset # Compile once via CLI: impulse build --manifest manifest.json -o graph.imps with ImpulseGnnDataset("graph.imps", relation_index=0) as dataset: row_offsets = dataset.row_offsets # torch.Tensor backed by mmap col_indices = dataset.col_indices # torch.Tensor backed by mmap ``` --- ## 2. Native Sampling & Sparse Ops With the snapshot mapped, `impulse-gnn` delegates sampling and sparse exports to the C-ABI kernel: * **$k$-Hop Neighborhood Sampling (`ImpulseNeighborSampler`)**: Calls `snapshot.sample_neighbors` in C++ over the CSR arrays rather than Python loops. * **Subgraph Filtering (Planned)**: `OP_CSR_WALK_STREAM` supports CEL edge/node predicates in `ImpulseVM`; exposing it directly on `ImpulseNeighborSampler` is planned. * **Structural Features**: Compute reachability, degrees, connected components, or `ImpK` features in `ImpulseVM` and pass the result straight into PyTorch. * **GPU Sliced ELLPACK (`0x05`)**: `create_sliced_ellpack_matrix` packs CSR into 2D tiles for coalesced GPU reads on power-law graphs. ```python from impulse_gnn import ImpulseGnnDataset, ImpulseNeighborSampler with ImpulseGnnDataset("graph.imps", relation_index=0) as dataset: sampler = ImpulseNeighborSampler(dataset, sizes=[25, 10]) subgraphs = sampler.sample(target_nodes=[42, 100, 256]) csr_mat = dataset.to_scipy_csr() ``` --- ## 3. Empirical Benchmarks (Apple M5 GPU / Metal) ### Sparse Matrix Multiplication (`SpMM` — 100K Nodes, 1M Edges, 128-Dim Features) | Implementation & Format | Layout & Device | Open Latency | `SpMM` Latency (p50) | Speedup | | :--- | :--- | :--- | :--- | :--- | | **SciPy Baseline (`csr_matrix`)** | In-RAM CSR (CPU) | `0.327 ms` | `40.860 ms` | `1.0x` | | **PyTorch CPU CSR** | PyTorch CSR (CPU) | `0.571 ms` | `16.515 ms` | `2.5x` | | **Impulse CSR (`RAW_UINT32`)** | Mapped CSR (GPU) | **`0.224 ms`** | **`4.435 ms`** | **9.2x** | | **Impulse Sliced ELLPACK (`0x05`)** | 2D Slice Tiles (GPU) | **`0.247 ms`** | **`0.005 ms` (5 µs)\*** | **8,417x (Launch)\*** | *\*The 5 µs figure reflects CPU command-buffer dispatch on Apple MPS without synchronization. With `torch.mps.synchronize()`, full GPU completion takes ~0.8–1.2 ms (~35x–50x faster than SciPy CPU).* ### Routing Topology Mounting (Qwen 1.5 MoE Router Index) | Engine | Disk Size | Open Latency | Router Evaluation (TTFT) | Heap Copy | | :--- | :--- | :--- | :--- | :--- | | **Standard `safetensors`** | `3.72 GB` | `16.433 ms` | `305.788 ms` | `~3.72 GB` | | **Impulse (`.imps`)** | **`0.01 MB (Topology Index)`** | **`0.400 ms`** | **`0.402 ms`** | **`0 Bytes`** | --- ## 4. Reproducing Locally ```bash git clone https://github.com/impulse-graph/impulse-gnn.git cd impulse-gnn python3 -m venv venv && source venv/bin/activate pip install pybind11 pytest numpy scipy torch pip install --no-build-isolation -e ../impulse-graph-core/impulse-python pip install --no-build-isolation -e . python examples/qwen_moe_real_ttft_benchmark.py ``` ================================================================================ FILE: docs/getting-started/index.md | URL: https://www.impulsegraph.org/getting-started/ ================================================================================ # Getting Started Impulse Graph executes read-only graph queries directly over memory-mapped `.imps` snapshot files across pluggable execution runtimes—including the **Pure JVM Engine** (Java 21 LTS / 25, Kotlin, Scala 3, Clojure) and the **Native C++20 / C-ABI Engine** (C/C++, Rust, Python, Go, .NET, Node.js). 1. **Build an `.imps` snapshot** containing typed node domains, CSR/CSC adjacency arrays, and columnar SoA attributes. 2. **Mount the file** directly from disk via `mmap` without running a database server. 3. **Query in-process** via schema-generated AOT builders, the Fluent Traversal API, read-only openCypher, ImpLog, or ImpK. --- ## Choose Your Entrypoint Start with the architectural guide or ecosystem hub that matches your workload: | Your Goal or Stack | Problem-First Guide | Ecosystem Hub | | :--- | :--- | :--- | | **Python Data Science, Parquet & GNNs** | **[From NetworkX & Parquet to `.imps`](from-networkx-and-parquet.md)** — Replace slow `dict` deserialization and full-RAM CSR copies with shared `mmap` snapshots. | **[Python & PyTorch Hub](../ecosystems/python/index.md)** | | **Java / JVM Microservices & ReBAC** | **[Embedded `.imps` vs. Networked Graph DB](embedded-vs-graph-db.md)** — Eliminate network/JSON serialization overhead with in-process FFM snapshots and CQRS read projections. | **[Java & JVM Hub](../ecosystems/java/index.md)** | | **Cross-Team Data + Service + ML Pipelines** | **[Polyglot "Parquet for Graphs" Workflow](polyglot-workflow.md)** — Compile `.imps` once from Parquet/Spark and mount the identical file in Java 25 and Python/PyTorch. | **[Native, Rust & Polyglot Hub](../ecosystems/native/index.md)** | --- ## How Queries Work: The Two Core Mechanics Before writing your first query, it helps to understand two mechanics that make Impulse Graph fundamentally different from relational SQL joins and traditional graph databases: ### 1. Start in One Domain, Walk 0..N Edges, Finish in One Target Domain Every query in Impulse Graph is a **directional pipeline that moves an active frontier of nodes from one Domain to another**: ```mermaid flowchart LR D0["1. Start Domain (e.g. User)\nSeed: 'usr_alice' or [1, 2, 3]\nOptional .filter('node.age >= 21')"] -->|".out('PLACED')"| D1["2. Intermediate Domain (Order)\nActive Order Frontier\nOptional .filter(...) / .project(...)"] D1 -->|".out('CONTAINS')"| D2["3. Target Domain (Product)\nReturns Surviving Product Nodes:\n• IDs / Business Keys\n• Target Attributes\n• Projected State / Aggregates"] ``` * **Start with a Single Domain**: You anchor the traversal to one starting domain (e.g., `snap.domain("User")`) and choose your starting nodes (a single node, a list of IDs/keys, a bitset, or all nodes in the domain). * **Walk Zero or More Edges**: * Walking **0 edges** simply filters or projects attributes within that starting domain (`User` $\to$ `User`). * Each `.out(...)` or `.in(...)` step transitions the active frontier across a directed relation into the next domain (`User` $\to$ `Order` $\to$ `Product`). * **Finish in a Single Target Domain**: Unlike a SQL `JOIN` that returns a wide Cartesian table of columns from every intermediate hop at once, an Impulse traversal finishes at a **single target domain** (e.g., `Product`) and returns the surviving nodes in that domain—their **Dense IDs**, **External Business Keys**, **target domain attributes**, or **projected/aggregated state** carried along the walk. ### 2. Set Behavior (Not Multi-Sets) & Collapsing Intermediate Results Most databases (SQL `JOIN`s, standard Cypher, Gremlin) operate on **multi-sets (bags of paths)**. If you start from 100 users who placed 5,000 orders that all point to the same 10 popular products, a traditional engine produces **5,000 duplicate intermediate rows**—and on the next hop (`Product -> Category`), it walks out of those same 10 products **5,000 separate times** ("path explosion"). **Impulse Graph operates on Sets, not Multi-Sets.** At every step, intermediate results converging on the same node are immediately **collapsed (reduced) together** before the next hop begins: * **Pure Reachability (Set Union)**: The active frontier in a domain is a **BitSet** (1 bit per node). If 500 different edges land on `Product #42` during a hop, bit `42` is simply set to `1` via bitwise `OR`. On the next hop, Impulse walks out of `Product #42` **exactly once**. * **Carrying Computed Values Across Hops (Monoidic Reduction)**: What if each incoming path carries a number—like an order `amount`, a hop `distance`, or a `risk_score`—and multiple paths land on the same target node? You specify a simple reduction rule (**a monoid**) that tells the engine how to collapse converging values into a single value per target node: * **`SUM` (`+`)**: Add converging values together (e.g., total money transferred into an account, or PageRank weight). * **`MIN`**: Keep the smallest value (e.g., shortest path distance or earliest timestamp). * **`MAX`**: Keep the largest value (e.g., maximum transaction size or highest confidence score). * **`ANY` / `OR`**: Boolean reachability. Because intermediate results are collapsed into a fixed-size per-domain set at every hop, **queries never suffer from exponential path explosion**, and the engine knows the **exact memory required for the query before it even runs**. --- ## Step-by-Step Guide 1. **[Installation](installation.md)**: Add the Pure Java Maven/Gradle dependencies, C/C++ CMake package, Python wheel, or standalone CLI (`impulse-graph` / `impulse-j`). 2. **[Quickstart](quickstart.md)**: Build an `.imps` file (from CSVs with `impulse build` or in Java) and run your first traversal in `< 20` lines of code. 3. **[Core Concepts & Glossary](core-concepts.md)**: A visual primer on CSR/CSC matrices, per-domain dense IDs ($0 \dots N_d-1$), domain-to-domain set reduction, and SoA attributes. 4. **[Building Snapshots (Java)](../ecosystems/java/building-snapshots.md)**: Step-by-step tutorial building `.imps` snapshots programmatically in Java and streaming from relational databases via JDBC. 5. **[Building Snapshots (CLI, CSV/Parquet & Python/PyTorch)](../ecosystems/python/snapshots-from-parquet-csv.md)**: Compile `.imps` snapshots from Apache Parquet and CSV files using the `impulse` CLI and query/train on them in Python and PyTorch. 6. **[Changing Data & Live Updates](handling-mutations.md)**: `< 5 min` near-real-time rebuilds, S3/GCS distribution, and zero-downtime Blue/Green swaps. 7. **[Querying & DSLs Decision Matrix](../query-api/index.md)**: Choose the right query interface (Fluent/AOT API, CEL, openCypher, ImpLog, or ImpK) for your application. ================================================================================ FILE: docs/getting-started/from-networkx-and-parquet.md | URL: https://www.impulsegraph.org/getting-started/from-networkx-and-parquet/ ================================================================================ # From NetworkX & Apache Parquet to `.imps` Snapshots Python graph workflows typically start cleanly in DuckDB, Polars, or Pandas over Apache Parquet files—and then hit a wall the moment edges are loaded into memory for multi-hop traversal or GNN sampling: 1. **NetworkX Object Overhead (`MemoryError` & Multi-Second Reloads)**: `nx.from_pandas_edgelist(...)` materializes every vertex and edge as nested Python `dict`-of-`dict` heap objects (`PyObject` headers + hash table slots). A graph of a few million edges expands to gigabytes of RAM, takes seconds or minutes to reconstruct on every notebook restart, and executes multi-hop traversals in Python interpreter loops. 2. **In-Memory CSR Duplication Across Workers (SciPy / PyTorch Geometric)**: Converting Parquet tables into `scipy.sparse.csr_matrix` or PyG `Data` tensors eliminates `dict` overhead, but still decodes the entire graph into process-private RAM on startup—and under `torch.utils.data.DataLoader(num_workers=N)` (`spawn`), each worker process often pays a separate deserialization or copy penalty. **Impulse Graph Engine** (`pip install impulse-graph`) solves this by treating `.imps` as a **compiled, memory-mapped companion to Apache Parquet**: you compile your Parquet/CSV node and edge tables once into a 128-byte-aligned `.imps` file, and every Python script, Jupyter kernel, or `DataLoader` worker mounts it directly from the OS page cache via `mmap`. --- ## 1. Architectural Comparison: Deserialized Python Graph vs. `.imps` `mmap` ```mermaid flowchart TB subgraph Legacy["Standard Python Workflow (Every Script / Worker Run)"] P1["Parquet / CSV Files"] -->|"Decode Columns"| DF["Pandas / Polars DataFrame"] DF -->|"Allocate Dicts / Tensors\n(Seconds–Minutes, GBs of Heap)"| NX["NetworkX DiGraph / PyG CSR in RAM"] NX -->|"Python Loop or Tensor Copy"| OUT1["Traversal Result"] end subgraph Impulse["Impulse Graph Workflow (Compile Once, Mount Anywhere)"] P2["Parquet / CSV Files\n+ manifest.json"] -->|"impulse build\n(One-Time Build)"| IMPS["graph.imps\n(128B-Aligned CSR/CSC + SoA)"] IMPS -->|"OS mmap (38 µs)\nShared Page Cache"| SNAP["Snapshot('graph.imps')"] SNAP -->|"C++20 ImpulseVM + SIMD\nor Zero-Copy NumPy/PyTorch Views"| OUT2["Set-Reduced Frontier / Tensor"] end ``` ### Empirical Baseline: Hetionet & `twitter-2010` Measured on Apple Silicon ARM64 (Python 3.11, NetworkX 3.2.1, PyTorch Geometric 2.4.0; full methodology in **[Benchmarks](../benchmarks.md)**): | Workload & Metric | Python NetworkX (`dict`-of-`dict`) | PyTorch Geometric (In-RAM CSR) | Impulse Graph Python (`Snapshot` `mmap`) | | :--- | :---: | :---: | :---: | | **Hetionet Cold Load** (`47K` nodes, `2.25M` edges) | `1,850 ms` | `450 ms` | **`0.038 ms` (`38 µs`)** (`mmap` open) | | **Hetionet 4-Hop Drug-Repurposing Query** (`1,317` compounds) | `42,100.0 µs` (`42.1 ms`) | `850.0 µs` (`0.85 ms`) | **`24.2 µs`** (`18.4 µs` C++20 + `5.8 µs` `pybind11`) | | **`twitter-2010` Cold Open** (`6.04 GB`, `41.65M` nodes, `1.47B` edges) | *OOM on standard workstations* | *Requires full CSR RAM decode* | **`0.038 ms` (`38 µs`)** (vs. `612.31 ms` Arrow IPC) | | **`twitter-2010` Full-Graph 10-Thread BFS** (`1.47B` edges) | — | — | **`145.00 ms`** (Native C++20 / C-ABI kernel) | --- ## 2. End-to-End Workflow: DuckDB / Parquet $\to$ `impulse build` $\to$ Python ### Step 1: Export Node & Edge Parquet Tables (DuckDB / Polars / PyArrow) Keep tabular cleaning, joins, and feature engineering in DuckDB, Polars, or PyArrow, and write standard `.parquet` files—including scalar columns and fixed-width embedding vectors: ```python import duckdb con = duckdb.connect() con.execute(""" COPY ( SELECT user_id, age::INTEGER AS age, risk_score::FLOAT AS risk_score FROM 'raw_users/*.parquet' ) TO 'data/users.parquet' (FORMAT PARQUET); COPY ( SELECT src_user_id, dst_user_id, weight::FLOAT AS weight FROM 'raw_interactions/*.parquet' ) TO 'data/interactions.parquet' (FORMAT PARQUET); """) ``` ### Step 2: Declare Domains & Relations in `manifest.json` Every node domain (`User`, `Product`, `Paper`) gets an independent 0-indexed dense ID space ($0 \dots N_d - 1$). Create `data/manifest.json`: ```json { "domains": [ { "id": 0, "name": "User", "key_type": "string", "file": "users.parquet", "format": "parquet", "id_column": "user_id", "attributes": [ { "name": "age", "column": "age", "type": "int32" }, { "name": "risk_score", "column": "risk_score", "type": "float32" } ] } ], "relations": [ { "name": "INTERACTED_WITH", "src_domain": 0, "tgt_domain": 0, "file": "interactions.parquet", "format": "parquet", "src_column": "src_user_id", "tgt_column": "dst_user_id", "include_csc": true, "attributes": [ { "name": "weight", "column": "weight", "type": "float32" } ] } ] } ``` Compile and validate the `.imps` snapshot once with the standalone `impulse` CLI (see [Installation](installation.md#developer-cli-toolchains-impulse-graph-impulse-j)): ```bash impulse build --manifest data/manifest.json -o interactions.imps impulse snapshot validate interactions.imps --strict-alignment ``` `impulse build` assigns dense IDs $0 \dots N - 1$, embeds a Minimal Perfect Hash index for `"user_id"` strings, sorts edges into forward CSR and reverse CSC (`"include_csc": true`), reorders `weight` in lockstep, and pads every array to 128-byte boundaries. ### Step 3: Traverse & Slice Tensors Zero-Copy in Python Mount `interactions.imps` via `Snapshot`. Every traversal executes inside the embedded C++20 `ImpulseVM` using set-reduced bitset frontiers—never allocating Python dicts per hop: ```python import numpy as np import torch from impulse_graph import Snapshot with Snapshot("interactions.imps") as snap: # 1. Multi-hop set-reduced fluent traversal (forward CSR -> reverse CSC) two_hop_peers = ( snap.traverse(start_node=0, catalog={"INTERACTED_WITH": 0}) .out("INTERACTED_WITH") .in_("INTERACTED_WITH") .to_list() ) # 2. Declarative parameterized openCypher direct_neighbors = snap.cypher( "MATCH (u:User)-[:INTERACTED_WITH]->(v:User) WHERE u.id = $uid RETURN v", params={"uid": 0}, catalog={"INTERACTED_WITH": 0}, ) # 3. Zero-copy NumPy & PyTorch views directly over the mmap page cache row_offsets = snap.get_row_offsets_array(0) # np.ndarray[uint32], zero-copy col_indices = snap.get_col_indices_array(0) # np.ndarray[uint32], zero-copy csr_tensor = snap.to_torch_csr(0) # torch.sparse_csr_tensor # 4. Native SIMD neighborhood sampling for GNN mini-batches seeds = np.array([0, 1, 2], dtype=np.uint64) sampled_src, sampled_tgt = snap.sample_neighbors( relation_index=0, nodes=seeds, k_samples=15, seed=42 ) ``` !!! warning "Avoid Imperative Node-by-Node Python Loops" Do not write Python `for node in frontier:` loops calling point lookups on `snap`. Express multi-hop walks, CEL filters, and fixed-point loops directly through `snap.traverse(...)`, `snap.domain(...)`, `snap.cypher(...)`, or `impulse_graph.vm.QueryBuilder` so the entire pipeline executes inside `ImpulseVM` in a single C-ABI call. --- ## 3. When to Stay in NetworkX vs. Switch to Impulse Graph | Scenario | Recommended Tool | Why | | :--- | :--- | :--- | | **Small (`< 10k` edges) interactive graph editing** (`G.add_edge`, `G.remove_node` inside an algorithm loop) | **NetworkX** | `.imps` snapshots are immutable; NetworkX excels at ad-hoc in-memory structural mutation on tiny graphs. *(Tip: `snap.to_networkx(rel_idx)` exports small relations when needed.)* | | **Repeated notebook/job runs over Parquet or CSV exports** (`100k – 1B+` edges) | **Impulse Graph** | Compile `.imps` once; reopen in `38 µs` across kernel restarts without re-parsing Parquet or exhausting RAM. | | **Multi-worker PyTorch `DataLoader` GNN training** | **Impulse Graph** | `N` worker processes `mmap` the same `.imps` file read-only (`MAP_SHARED`), sharing a single copy in the OS page cache. | | **Productionizing a Python research graph into a Java/Rust/Go microservice** | **Impulse Graph** | Ship the exact `.imps` artifact to production services with bitwise-identical query results ([Polyglot Workflow](polyglot-workflow.md)). | --- ## Next Steps * **[Python & PyTorch Ecosystem Hub](../ecosystems/python/index.md)**: Complete overview of Python installation, APIs, and ML integrations. * **[Building Snapshots from Parquet & CSV](../ecosystems/python/snapshots-from-parquet-csv.md)**: Full `manifest.json` reference, fixed-size embedding columns, and Reverse Cuthill-McKee (`--rcm`) cache optimization. * **[GNN Training & Vamana Vector Search](../ecosystems/python/gnn-and-vector-search.md)**: Multi-million-node neighborhood sampling and hybrid graph + ANN search (`0x08`, `0xCA`..`0xCB`). * **[Python SDK Reference](../reference/python-api.md)**: Complete method signatures for `Snapshot`, `Traversal`, `vm.QueryBuilder`, and `Writer`. ================================================================================ FILE: docs/getting-started/embedded-vs-graph-db.md | URL: https://www.impulsegraph.org/getting-started/embedded-vs-graph-db/ ================================================================================ # Embedded `.imps` Runtime vs. Networked Graph Databases Backend and JVM platform teams building **fine-grained authorization (ReBAC / Zanzibar)**, **payment fraud rings**, **bill-of-materials (BOM) dependency trees**, or **catalog hierarchies** commonly reach for a networked graph database (Neo4j, Amazon Neptune, OpenFGA, or RedisGraph)—only to discover two operational and latency bottlenecks: 1. **The Network & Serialization Tax Exceeds the Traversal**: Even when a remote graph server evaluates a 3-hop permission check quickly in its internal cache, your microservice still pays for connection-pool checkout, TCP/TLS/Bolt/gRPC framing, and JSON/Protobuf serialization on every request. 2. **Stateful Cluster Operations & Multi-Set Path Explosion**: Scaling read throughput requires operating a stateful distributed database cluster, tuning remote page caches, and guarding Cypher/Gremlin queries against exponential intermediate row explosion on dense hub nodes. **Impulse Graph Engine** takes the SQLite / Apache Arrow approach instead: keep transactional OLTP writes in PostgreSQL or MySQL, compile read-optimized `.imps` snapshots on a periodic or near-real-time cadence, and **execute multi-hop traversals directly inside your stateless application pods via off-heap `mmap`**. --- ## 1. Request Path Comparison: Networked Graph DB vs. Embedded Impulse ```mermaid flowchart TB subgraph Remote["Networked Mutable Graph DB (Stateful Cluster)"] APP1["Java / Go Microservice Pod"] -->|"1. Serialize Params + TCP/Bolt/gRPC\n(~200 µs – 2 ms RTT)"| GDB["Graph DB Cluster\n(Locks + Pointer Stores + Multi-Set Rows)"] GDB -->|"2. Serialize JSON / Protobuf\n(1.91 – 2.56 µs CPU alone)"| APP1 end subgraph Embedded["Embedded Impulse Runtime (Stateless Pods + S3/GCS)"] S3["S3 / GCS Bucket\ngraph-v42.imps"] -.->|"Async Pull + Atomic RCU Swap\n(< 10 ms Leyden AOT mmap)"| APP2["Java 21/25 Microservice Pod\nOff-Heap MemorySegment + Set BitSets"] APP2 -->|"In-Process Traversal\n(0.026 – 0.552 µs, 0 Bytes Heap Alloc)"| APP2 end ``` ### Empirical Evidence: JFR Profiling on a 600k-User Enterprise Directory In a 100,000-request Java Flight Recorder (JFR) benchmark (`JsonVsCsrBenchmarkRunner`) over an enterprise ReBAC directory of 600,000 users, in-process Java 25 multi-hop CSR evaluation was measured directly against Jackson (`ObjectMapper`) JSON serialization to `/dev/null`—**before any socket or network hop** (see **[Benchmarks §3](../benchmarks.md#3-enterprise-service-reality-json-serialization-is-slower-than-the-graph-query)**): | Operation (In-Process Java 25, Apple Silicon ARM64) | Mean Latency | Relative CPU Cost vs. `large` Traversal | | :--- | :---: | :--- | | **Impulse Java 25 Multi-Hop CSR Query (`small`, ~1.8k users)** | **`0.026 µs` (`26 ns`)** | `0.047x` (**`73.4x` faster than JSON stream**) | | **Impulse Java 25 Multi-Hop CSR Query (`medium`, ~48k users)** | **`0.088 µs` (`88 ns`)** | `0.159x` (**`21.7x` faster than JSON stream**) | | **Impulse Java 25 Multi-Hop CSR Query (`large`, 600k users)** | **`0.552 µs` (`552 ns`)** | **`1.00x` Baseline** | | **Jackson Streaming JSON Serialization (`/dev/null`)** | **`1.908 µs` (`1,908 ns`)** | **`3.46x` more CPU than the graph query** | | **Jackson JSON String + UTF-8 Byte Output (`/dev/null`)** | **`2.558 µs` (`2,558 ns`)** | **`4.63x` more CPU than the graph query** | Even on the 6.04 GB, 1.47-billion-edge `twitter-2010.imps` graph, Pure Java 25 with JDK 25 Leyden AOT (`-XX:AOTCache`) maps the snapshot cold in **`9.748 ms`** (`14.557 ms` standard cold JVM) and executes targeted C2-warmed multi-hop BFS queries in **`4.13 µs`**—with **zero `java.lang.Object` allocations** in the hot loop and **zero JNI native libraries** in the container image. --- ## 2. Architectural Trade-Off Matrix | Dimension | Networked Mutable Graph DB (Neo4j / Neptune / OpenFGA) | Embedded Impulse Graph (`.imps` + Pure Java / C-ABI) | | :--- | :--- | :--- | | **Write Freshness** | **Immediate (`< 10 ms` ACID read-your-own-writes)** | **Eventual / Micro-Batch (`5s – 5 min` rebuild + atomic swap)** | | **Multi-Hop Read Latency** | `0.5 ms – 20+ ms` (network RTT + serialization + lock/cache overhead) | **`0.026 µs – 25 µs` in-process** (L1/L2/DRAM bandwidth speed) | | **Intermediate Evaluation** | Multi-set path bags (vulnerable to hub-node path explosion) | **Set-reduced BitSets & monoids** (bounded memory known at `prepare` time) | | **JVM GC & Heap Impact** | DTO deserialization & connection-pool buffers per request | **Zero hot-loop heap allocations** (`MemorySegment` off-heap `mmap`) | | **Horizontal Scaling** | Stateful read replicas, cluster consensus, connection limits | **Stateless pods** pulling immutable `.imps` artifacts from S3/GCS | | **Supply-Chain & CVE Surface** | Database driver + transitive networking/serialization dependencies | **Zero third-party runtime dependencies** in `impulse-core` / `impulse-vm` | | **Point-in-Time Audit & Repro** | Requires backup restore or temporal audit tables | Every `.imps` generation is an immutable, SHA-256-checksummed artifact | --- ## 3. Recommended Production Pattern: Relational OLTP + Impulse Read Projection (CQRS) Impulse Graph is **not** a replacement for your transactional system of record—it replaces the complex cache, recursive SQL CTE, or auxiliary graph cluster sitting beside it: 1. **System of Record (PostgreSQL / MySQL / CockroachDB)**: Handles point writes, ACID constraints, billing, and strict read-your-own-writes lookups on the mutating actor's immediate row. 2. **Periodic or CDC Snapshot Builder (`5s – 5 min`)**: Streams normalized tables or CDC compaction state through `SnapshotBuilder` (JDBC) or `impulse build` (Parquet) in $O(\text{chunk})$ RAM and uploads `authz-v104.imps` to S3/GCS. 3. **In-Process Stateless Service Pods**: Each Kubernetes pod polls S3/GCS, maps the new `.imps` file into a fresh Java `Arena` in milliseconds, atomically swaps the active pointer, and drains in-flight readers on the prior generation with zero locks: ```java // Pure Java 21/25 in-process ReBAC check: zero network hop, zero JNI, zero hot-loop GC boolean canAccess = snap.domain("User") .fromKey(request.userId()) .out("MEMBER_OF") .repeatUntilStable("PARENT_GROUP") .out("GRANTED_ON", "edge.permission == 'READ'") .toBitSet() .get(targetResourceDenseId); ``` !!! tip "Hybrid Instant-Local-Write + Snapshot Pattern" If the mutating user needs immediate `< 10 ms` visibility of a single edge they *just* created before the next 30-second `.imps` swap arrives, evaluate the multi-hop graph check in Impulse (`< 1 µs`) and `OR` the result with a lightweight short-TTL session/outbox check for the caller's recent writes. --- ## Next Steps * **[Java & JVM Ecosystem Hub](../ecosystems/java/index.md)**: Maven BOM (`v0.11`), JDK 21 vs. JDK 25 setup, Kotlin/Scala/Clojure DSLs, and Spring Boot integration. * **[Kubernetes & Snapshot Lifecycle (`SnapshotLifecycleManager`)](../ecosystems/java/kubernetes-and-lifecycle.md)**: Production S3/GCS hot-reload, readiness probes, and safe `Arena` unmapping. * **[Schema-First AOT Code Generation](../ecosystems/java/aot-codegen.md)**: Generate compile-time-checked Java traversal builders from `.imps.schema.yaml`. * **[Changing Data & Live Updates](handling-mutations.md)** & **[Authorization (ReBAC) Showcase](../showcase/authz.md)**. ================================================================================ FILE: docs/getting-started/polyglot-workflow.md | URL: https://www.impulsegraph.org/getting-started/polyglot-workflow/ ================================================================================ # Polyglot "Parquet for Graphs" Workflow In many organizations, graph data crosses three distinct engineering stacks: 1. **Data Engineering** curates entity and event tables in Apache Spark, DuckDB, Snowflake, or Iceberg and exports **Apache Parquet**. 2. **Backend Platform Teams** serve high-QPS permission, fraud, or recommendation APIs in **Java 21/25 (Spring Boot)**, **Rust**, or **Go**. 3. **ML & Data Science Teams** train Graph Neural Networks (GNNs), compute embeddings, and run exploratory notebooks in **Python & PyTorch**. Without a shared binary graph format, each team re-ingests the same Parquet tables into incompatible systems (a networked graph DB for production services, custom SciPy/PyG tensors for ML), causing schema drift and divergent traversal semantics. With **Impulse Graph Engine**, `.imps` acts as the **portable binary contract** across all three stacks: compile the graph once from Parquet, publish to S3/GCS, and mount the exact same `.imps` file in both Pure Java 21/25 and Python/PyTorch with guaranteed bitwise-identical `ImpulseVM` results. ```mermaid flowchart LR SCHEMA["1. Shared Contract\ncommerce.imps.schema.yaml\n+ manifest.json"] --> BUILD["2. Data Engineering\nDuckDB / Spark Parquet\n──► impulse build"] BUILD --> S3["commerce.imps\n(S3 / GCS Artifact\n128B-Aligned + SHA-256)"] S3 --> JAVA["3. Java 21/25 Service\nPure JVM FFM + AOT Codegen\nZero JNI • Sub-µs Reads"] S3 --> PY["4. Python & PyTorch ML\nZero-Copy Tensors, GNN\nSampler & Vamana ANN"] ``` --- ## Step 1: Define the Shared Schema Contract Check a declarative schema contract (`commerce.imps.schema.yaml`, `v0.11` schema-first workflow; see [Schema & Manifest Spec](../reference/spec/schema-specification.md)) into version control alongside your ingestion `manifest.json`. * **Per-Domain Dense IDs ($0 \dots N_d - 1$)**: `User` (`domain 0`) and `Product` (`domain 1`) maintain independent 0-indexed dense ID spaces. * **Name-Based Evolution**: Queries and AOT-generated builders bind by domain, relation, and attribute **names** in Section 2, so adding attributes or running Reverse Cuthill-McKee (`--rcm`) node reordering never breaks downstream consumers. === "`commerce.imps.schema.yaml` (Shared Contract & Codegen Input)" ```yaml graphName: CommerceGraph package: com.acme.commerce.graph domains: User: denseId: uint32 key: string attributes: segment: "Int16" active: "UInt8" Product: denseId: uint32 key: string attributes: price: "Float32" in_stock: "UInt8" embedding: "Float32[128]" relations: PURCHASED: source: User target: Product direction: [out, in] cardinality: many_to_many attributes: amount: "Float32" ``` === "`manifest.json` (Parquet Ingestion Mapping)" ```json { "domains": [ { "id": 0, "name": "User", "key_type": "string", "file": "users.parquet", "format": "parquet", "id_column": "user_id", "attributes": [ { "name": "segment", "column": "segment", "type": "int16" }, { "name": "active", "column": "active", "type": "uint8" } ] }, { "id": 1, "name": "Product", "key_type": "string", "file": "products.parquet", "format": "parquet", "id_column": "product_id", "attributes": [ { "name": "price", "column": "price", "type": "float32" }, { "name": "in_stock", "column": "in_stock", "type": "uint8" }, { "name": "embedding", "column": "embedding", "type": "float32", "dimension": 128 } ] } ], "relations": [ { "name": "PURCHASED", "src_domain": 0, "tgt_domain": 1, "file": "purchases.parquet", "format": "parquet", "src_column": "user_id", "tgt_column": "product_id", "include_csc": true, "attributes": [ { "name": "amount", "column": "amount", "type": "float32" } ] } ] } ``` --- ## Step 2: Build, Index & Publish `.imps` (Data Engineering) In your Airflow, Dagster, dbt, or Spark job, export `users.parquet`, `products.parquet`, and `purchases.parquet`, compile `commerce.imps` with the standalone `impulse` CLI (including an optional Section 2.6 `IMP_INDEX_VAMANA_ANN` vector index over `Product.embedding`), verify alignment and checksums, and upload to object storage: ```bash # 1. Compile Parquet tables + embedded SQ8 Vamana ANN index into a 128-byte-aligned .imps file impulse build --manifest manifest.json -o commerce.imps \ --vector-index "Product.embedding:R=32:L=64:alpha=1.2:metric=cosine:quant=sq8" # 2. Validate 128-byte alignment, CSR/CSC monotonicity, and SHA-256 footer integrity impulse snapshot validate commerce.imps --strict-alignment # 3. Publish immutable generation to S3 / GCS aws s3 cp commerce.imps s3://acme-graphs/commerce/commerce-2026-11-22T21-00Z.imps ``` --- ## Step 3: Mount in a Pure Java 21/25 Enterprise Microservice Your Java service pulls `commerce.imps` onto local NVMe and memory-maps it via `BinarySnapshotLoader` (or hot-reloads generations automatically via `SnapshotLifecycleManager`; see [Kubernetes & Lifecycle](../ecosystems/java/kubernetes-and-lifecycle.md)). No native `.so`/`.dylib` libraries are loaded—the Pure JVM runtime reads the exact same 128-byte-aligned CSR/CSC and SoA segments via `java.lang.foreign.MemorySegment`: ```java import org.impulsegraph.api.ImpulseGraphSnapshot; import org.impulsegraph.storage.csr.BinarySnapshotLoader; import java.lang.foreign.Arena; import java.nio.file.Path; import java.util.List; try (Arena arena = Arena.ofShared()) { ImpulseGraphSnapshot snap = BinarySnapshotLoader .loadSnapshot(Path.of("/var/lib/impulse/commerce.imps"), arena) .getGraph(); // Collaborative filtering: User -> out(PURCHASED) -> in(PURCHASED) -> out(PURCHASED) // Set semantics collapse duplicate co-purchasers at every hop automatically List recommendedSkus = snap.domain("User") .fromKey("usr_90412") .out("PURCHASED") .in("PURCHASED") .out("PURCHASED", "tgt.in_stock == 1 && tgt.price <= 150.0") .toKeyList(); } ``` With `impulse-codegen` (`impulse-maven-plugin`, `v0.11`), `commerce.imps.schema.yaml` also generates compile-time-checked builders (`UserQueryBuilder`, `ProductQueryBuilder`) so misspelled relation or attribute names fail at `mvn compile` time rather than runtime (see [AOT Code Generation](../ecosystems/java/aot-codegen.md)). --- ## Step 4: Mount the Identical File in Python & PyTorch (ML / Research) Your ML engineers pull the **exact same `commerce.imps` artifact** into Python (`pip install impulse-graph`) for training, offline evaluation, and hybrid graph + vector retrieval: ```python import numpy as np import torch from impulse_graph import Snapshot with Snapshot("commerce.imps") as snap: # 1. Bitwise-identical multi-hop traversal via embedded C++20 ImpulseVM candidate_product_ids = ( snap.traverse(start_node=42, catalog={"PURCHASED": 0}) .out("PURCHASED") .in_("PURCHASED") .out("PURCHASED") .to_list() ) # 2. Zero-copy CSR topology & SIMD mini-batch neighborhood sampling for PyTorch purchases_csr: torch.Tensor = snap.to_torch_csr(0) seed_users = np.array([42, 108, 512], dtype=np.uint64) sampled_src, sampled_tgt = snap.sample_neighbors( relation_index=0, nodes=seed_users, k_samples=20, seed=7 ) # 3. Hybrid Vamana ANN vector search + exact SIMD dot-product reranking (v0.10.0) query_vec = np.random.default_rng(0).standard_normal(128, dtype=np.float32) nearest_products = ( snap.domain("Product") .vector_search("embedding", query_vec, k=50, ef_search=128) .rerank("embedding", query_vec, top_k=10) .to_list() ) ``` Because both the Pure JVM runtime and the Python/C++20 runtime are continuously verified against the [Four-Way Polyglot Validation Suite](../contributing/polyglot-validation.md) (`531` `.impas` vectors across `166/166` opcodes), feature logic developed in Python notebooks behaves identically when promoted to Java or Rust production services. --- ## Next Steps * **[Java & JVM Ecosystem Hub](../ecosystems/java/index.md)** & **[AOT Code Generation](../ecosystems/java/aot-codegen.md)** * **[Python & PyTorch Ecosystem Hub](../ecosystems/python/index.md)** & **[GNN & Vector Search](../ecosystems/python/gnn-and-vector-search.md)** * **[Native, Rust & Polyglot Hub](../ecosystems/native/index.md)** & **[Native CLI Reference](../ecosystems/native/cli-reference.md)** * **[Schema & Manifest Specification (`.yaml`)](../reference/spec/schema-specification.md)** ================================================================================ FILE: docs/getting-started/installation.md | URL: https://www.impulsegraph.org/getting-started/installation/ ================================================================================ # Installation Impulse Graph Engine provides pluggable, zero-dependency execution runtimes over the portable `.imps` binary snapshot format and `impOps` bytecode ISA: * **Pure JVM Runtime (`org.impulsegraph`)**: 100% pure Java 21 LTS / 25 implementation (FFM off-heap memory segments, Vector API, and `MethodHandle` JIT) distributed on Maven Central—powering Java, Kotlin, Scala 3, and Clojure with zero JNI `.so`/`.dylib`/`.dll` libraries. * **Native C++20 / C-ABI Runtime (`impulse-graph`)**: Native C-ABI kernel (`libimpulse_graph`) and SDK bindings for C/C++20, Rust, Python, Go, .NET/C# (P/Invoke), and Node.js. Choose your language ecosystem below: === "Java 21 LTS / 25 (Maven / Gradle)" The pure JVM runtime is packaged under groupId `org.impulsegraph`. The core engine (`impulse-spec`, `impulse-api`, `impulse-storage`, `impulse-vm`, `impulse-compiler`) has **zero third-party runtime dependencies**. !!! note "Maven Central (`0.10.0`)" `org.impulsegraph:*:0.10.0` is published on Maven Central (release JARs are also on [GitHub Releases](https://github.com/impulse-graph/impulse-graph-java/releases/tag/v0.10.0)). To install a local snapshot from source: ```bash git clone https://github.com/impulse-graph/impulse-graph-java.git cd impulse-graph-java && mvn clean install -DskipTests ``` !!! info "Upcoming in `v0.11`: `impulse-bom`, AOT Codegen & `impulse-j`" `v0.11` introduces **`org.impulsegraph:impulse-bom`** for single-version dependency management, **`impulse-maven-plugin` / `impulse-codegen`** for schema-first `.imps.schema.yaml` AOT Java code generation, **`SnapshotLifecycleManager`** for S3/Kubernetes hot-reload, and **`impulse-j`** (a pure-Java CLI requiring no native binaries). See the **[Java & JVM Ecosystem Hub](../ecosystems/java/index.md)**, **[Maven & Build Tooling](../ecosystems/java/maven-and-build-tooling.md)**, and **[AOT Code Generation](../ecosystems/java/aot-codegen.md)**. **Maven (`pom.xml` — `0.10.0`)**: ```xml org.impulsegraph impulse-api 0.10.0 org.impulsegraph impulse-storage 0.10.0 org.impulsegraph impulse-vm 0.10.0 org.impulsegraph impulse-compiler 0.10.0 org.impulsegraph impulse-builder 0.10.0 ``` **Gradle (`build.gradle.kts` — `0.10.0`)**: ```kotlin dependencies { implementation("org.impulsegraph:impulse-api:0.10.0") implementation("org.impulsegraph:impulse-storage:0.10.0") implementation("org.impulsegraph:impulse-vm:0.10.0") implementation("org.impulsegraph:impulse-compiler:0.10.0") implementation("org.impulsegraph:impulse-builder:0.10.0") } ``` === "C / C++20 (CMake)" The C-ABI and C++20 engine (`impulse-graph-core/impulse-cpp`) has zero external runtime dependencies and can be integrated via CMake: **Via Git Submodule / `add_subdirectory`**: ```cmake add_subdirectory(impulse-graph-core/impulse-cpp) target_link_libraries(your_target PRIVATE impulse_graph_static) ``` **Or via CMake `find_package` (after `cmake --install`)**: ```cmake find_package(impulse-graph CONFIG REQUIRED) target_link_libraries(your_target PRIVATE impulse-graph::impulse-graph) ``` *(Official `vcpkg` and Conan port manifests are in progress for upcoming releases; see the [Native, Rust & Polyglot Hub](../ecosystems/native/index.md).)* === "Python" Install pre-built wheels directly from PyPI: ```bash pip install impulse-graph ``` Or compile from source: ```bash git clone https://github.com/impulse-graph/impulse-graph-core.git cd impulse-graph-core/impulse-python && pip install . ``` *(See the [Python & PyTorch Hub](../ecosystems/python/index.md) for Parquet snapshot building and GNN sampling.)* === "Rust" Add the self-contained crate from crates.io: ```bash cargo add impulse-graph ``` ## Developer CLI Toolchains (`impulse-graph` & `impulse-j`) Impulse Graph provides two CLI distributions for building (`build`), inspecting (`snapshot inspect`), validating (`snapshot validate`), optimizing (`snapshot optimize`), and running (`compile` / `run`) `.imps` snapshots: 1. **Native CLI (`impulse-graph`, aliased as `impulse`)**: Standalone native binary in `impulse-graph-core/impulse-cli` with zero JVM dependency—recommended for Python, C/C++, Rust, data engineering, and CI containers (see [Native CLI Reference](../ecosystems/native/cli-reference.md)). 2. **Pure-Java CLI (`impulse-j`, `v0.11`)**: 100% JVM CLI in `impulse-graph-java/impulse-cli` for locked-down enterprise Java environments where native executables are prohibited (see [Pure-Java CLI (`impulse-j`)](../ecosystems/java/cli-impulse-j.md)). ```bash # Option A: Run the native CLI via Docker docker pull ghcr.io/impulse-graph/impulse-tools:latest docker run --rm -v $(pwd):/data ghcr.io/impulse-graph/impulse-tools:latest impulse snapshot inspect /data/snapshot.imps # Option B: Build and install the native CLI from source (Rust 1.80+) git clone https://github.com/impulse-graph/impulse-graph-core.git cargo install --path impulse-graph-core/impulse-cli # The native binary is named 'impulse-graph'. Create a shell alias if desired: alias impulse="impulse-graph" ``` ================================================================================ FILE: docs/getting-started/quickstart.md | URL: https://www.impulsegraph.org/getting-started/quickstart/ ================================================================================ # Quickstart This guide walks you through **building** an immutable `.imps` binary snapshot and **querying** it across **Pure Java 25**, **C / C++20 (C-ABI)**, and **Python**. --- ## 1. Build Your First `.imps` Snapshot You can compile an `.imps` file in two ways: * **Rust CLI Builder (`impulse build`)**: Compiles CSV, TSV, or Parquet files + a JSON manifest directly into an `.imps` file—a fast, standalone option with **no JVM required** (ideal for Python, C/C++, Go, C#, and Node.js users). * **Java `SnapshotBuilder`**: Streams data directly from Java collections, JDBC databases, or custom `RelationDataSource` iterators. === "Rust CLI Builder (CSV / Parquet -> `.imps`)" Create two CSV files (`users.csv` and `follows.csv`) and a `manifest.json`: **`users.csv`** (Node keys and attributes): ```csv id,age,active usr_alice,30,true usr_bob,24,true usr_charlie,19,false ``` **`follows.csv`** (Directed edges): ```csv src,tgt usr_alice,usr_bob usr_alice,usr_charlie usr_bob,usr_charlie ``` **`manifest.json`**: ```json { "domains": [ { "id": 0, "name": "User", "key_type": "string", "file": "users.csv", "id_column": "id", "attributes": [ { "name": "age", "column": "age", "type": "int32" }, { "name": "active", "column": "active", "type": "uint8" } ] } ], "relations": [ { "name": "FOLLOWS", "src_domain": 0, "tgt_domain": 0, "file": "follows.csv", "src_column": "src", "tgt_column": "tgt", "include_csc": true } ] } ``` Compile the `.imps` snapshot and inspect its 128-byte-aligned sections (using `impulse-graph` or the `impulse` alias; see [Building Snapshots from Parquet & CSV](../ecosystems/python/snapshots-from-parquet-csv.md)): ```bash impulse-graph build --manifest manifest.json -o social.imps impulse-graph snapshot inspect social.imps ``` === "Java 25 (`SnapshotBuilder`)" For JVM applications or streaming JDBC pipelines, use `org.impulsegraph.builder.api.SnapshotBuilder` (see the full [Building Snapshots Walkthrough](../ecosystems/java/building-snapshots.md)): ```java import org.impulsegraph.builder.api.*; import java.nio.file.Path; // 1. Define the User domain (3 nodes: dense IDs 0, 1, 2) DomainDefinition userDomain = DomainDefinition.builder(3) .idWidth(PrimitiveWidth.UINT32) .build(); // 2. Define the FOLLOWS relation (User -> User, CSR + CSC) RelationDefinition followsRel = RelationDefinition.builder("User", "User") .addTopology(Topology.CSR, CompressionScheme.RAW) .addTopology(Topology.CSC, CompressionScheme.RAW) .dataSource(followsDataSource) // Streams (0->1), (0->2), (1->2) .build(); // 3. Stream-write the 128-byte-aligned .imps file SnapshotBuilder.create() .addDomain("User", userDomain) .addRelation("FOLLOWS", followsRel) .writeTo(Path.of("social.imps")); ``` --- ## 2. Mount `social.imps` & Traverse Edges Impulse Graph maps `.imps` files directly from disk into virtual memory via `mmap`. Every traversal follows two core mechanics: 1. **Domain-to-Domain Pipeline**: You start in a single domain (e.g., `User`), walk zero or more directed relations (e.g., `.out("FOLLOWS")`), and finish in a single target domain, returning the surviving nodes, target attributes, or projected state from that final domain. 2. **Set Semantics & Collapsed Frontiers**: Intermediate results are stored as a **Set** (an off-heap BitSet), not a multi-set of duplicate paths. Converging paths are immediately collapsed into a single entry per node at each step (via Bitwise `OR` for reachability, or a monoid like `SUM`/`MIN`/`MAX` when projecting numeric state)—so the next hop never repeats work. === "Java 25 (Pure Java Engine)" ```java import org.impulsegraph.api.ImpulseGraphSnapshot; import org.impulsegraph.storage.csr.BinarySnapshotLoader; import java.lang.foreign.Arena; import java.nio.file.Path; import java.util.List; public class Quickstart { public static void main(String[] args) throws Exception { // 1. Manage off-heap memory lifecycle deterministically with a shared Arena try (Arena arena = Arena.ofShared()) { // 2. Memory-map the .imps binary snapshot off-heap (zero heap allocation) var loaded = BinarySnapshotLoader.loadSnapshot(Path.of("social.imps"), arena); ImpulseGraphSnapshot snap = loaded.getGraph(); // 3. Execute a domain-anchored traversal (Dense ID 0 -> out("FOLLOWS")) List friends = snap.domain("User") .from(0L) .out("FOLLOWS") .toList(); System.out.println("User 0 follows Dense IDs: " + friends); } } } ``` === "C / C++20 (C-ABI & Fluent VM)" ```cpp #include "impulse_graph.h" #include "impulse_vm_fluent.hpp" #include int main() { // 1. Memory-map the .imps binary snapshot via C-ABI impulse_status_t status = IMPULSE_OK; impulse_snapshot_t* snap = impulse_snapshot_open("social.imps", &status); if (status != IMPULSE_OK || !snap) return 1; // 2. Compile a bytecode traversal query using the C++20 Fluent Builder using namespace impulse::vm; CompiledQuery query = QueryBuilder() .inputNode(0) // Seed node ID in R0 .walkEdge(0) // CSR forward walk on relation 0 (FOLLOWS) .collectBitset() // Materialize off-heap bitset handle .compile(); // 3. Execute on ImpulseVM impulse_vm_context_t* ctx = nullptr; QueryResult res = query.execute(snap, 0 /* seed node */, &ctx); if (res.isOk()) { std::cout << "Node 1 reachable: " << res.testBitset(ctx, 1) << "\n"; } if (ctx) impulse_vm_context_destroy(ctx); impulse_snapshot_close(snap); return 0; } ``` === "Python" ```python from impulse_graph import Snapshot # 1. Memory-map the .imps binary snapshot off-heap with Snapshot("social.imps") as snap: # 2. Execute a fluent traversal on relation 0 (FOLLOWS) friends = ( snap.traverse(start_node=0, catalog={"FOLLOWS": 0}) .out("FOLLOWS") .to_list() ) print("User 0 follows:", friends) ``` --- ## 3. Filtered Traversals & Prepared Statements Both the Pure Java 25 engine and the C++20 / C-ABI kernel include an in-kernel compiler for **Google CEL** predicates and **openCypher** pattern matching: === "Java 25" ```java // 1. Fluent traversal with vectorized CEL attribute filtering List activeFriends = snap.domain("User") .fromKey("usr_alice") .out("FOLLOWS") .filter("node.age >= 21 && node.active == true") .toList(); // 2. Parameterized SQLite-style prepared statement try (var stmt = snap.prepare( "MATCH (u:User)-[:FOLLOWS]->(f:User) WHERE u.id = $uid AND f.age >= $minAge RETURN f.id")) { stmt.bindNode("uid", 0L).bindLong("minAge", 21L); try (var rows = stmt.execute()) { while (rows.next()) { System.out.println("Matched friend ID: " + rows.getNodeId(0)); } } } ``` === "C-ABI (`impulse_stmt_t`)" ```c #include "impulse_vm.h" #include impulse_stmt_t* stmt = NULL; impulse_stmt_prepare( snap, "MATCH (u:User)-[:FOLLOWS]->(f:User) WHERE u.id = $uid AND f.age >= $minAge RETURN f.id", &stmt ); impulse_stmt_bind_node(stmt, "uid", 0); impulse_stmt_bind_int(stmt, "minAge", 21); // Exact scratch + result footprint is known at prepare time; caller supplies pre-allocated buffer size_t buf_size = impulse_stmt_buffer_size(stmt); void* buf = malloc(buf_size); impulse_stmt_execute(stmt, buf, buf_size); size_t rows = impulse_stmt_row_count(stmt); const uint64_t* col0 = (const uint64_t*)impulse_stmt_column_data(stmt, 0); free(buf); impulse_stmt_finalize(stmt); ``` === "Python" ```python from impulse_graph import Snapshot with Snapshot("social.imps") as snap: # 1. Fluent traversal with node attribute filter active_friends = ( snap.traverse(start_node=0, catalog={"FOLLOWS": 0}) .out("FOLLOWS") .filter(prefix="active") .to_list() ) # 2. Parameterized openCypher query execution matched_ids = snap.cypher( "MATCH (u:User)-[:FOLLOWS]->(f:User) WHERE u.id = $uid RETURN f", params={"uid": 0}, catalog={"FOLLOWS": 0}, ) print("Matched friend IDs:", matched_ids) ``` --- ## Next Steps * **[Querying & DSLs Decision Matrix](../query-api/index.md)**: Compare AOT/Fluent builders, Google CEL, openCypher, ImpLog, and ImpK. * **[Ecosystem Hubs](../ecosystems/index.md)**: Deep dives for [Java & JVM](../ecosystems/java/index.md), [Python & PyTorch](../ecosystems/python/index.md), and [C++ / Rust / Polyglot](../ecosystems/native/index.md). * **[Changing Data & Live Updates](handling-mutations.md)**: Out-of-band snapshot rebuilds and lock-free Blue/Green swaps. ================================================================================ FILE: docs/getting-started/core-concepts.md | URL: https://www.impulsegraph.org/getting-started/core-concepts/ ================================================================================ # Core Concepts & Architecture Primer Getting started with the **Impulse Graph Engine** does not require a background in sparse linear algebra or compiler design. Understanding four structural choices—**CSR/CSC adjacency arrays**, **per-domain dense IDs**, **set-reduced traversals**, and **Structure-of-Arrays (SoA) columns**—explains how every runtime executes queries directly over `.imps` files. Whether you are using the Pure JVM runtime (Java, Kotlin, Scala, Clojure) or the Native C-ABI runtime (C++, Rust, Python, Go, .NET, Node.js), the exact same data layout and execution model apply. --- ## 1. Why Graph Analytics Needs a Different Approach In traditional application development, graphs are usually modeled in one of two ways: 1. **Object Pointers**: In-memory objects where a `Node` has a list of references to other nodes (`List neighbors`). 2. **Relational Database Tables**: A `nodes` table and an `edges` join table containing `(source_id, target_id)`. Both approaches hit severe bottlenecks when analytics scale to millions or billions of edges: * **Object pointer-chasing** causes constant CPU cache misses. In languages with managed memory (like Java), millions of edge objects cause heavy garbage collection (GC) thrashing and high heap overhead. * **Relational `JOIN` queries** require expensive disk I/O, hash-join tables, and index lookups for every traversal hop. **Impulse Graph solves this by treating the graph as a Sparse Matrix** stored in a contiguous, zero-copy, memory-mapped binary format (`.imps`). --- ## 2. Sparse Matrices for Graph Topology Imagine a graph where rows represent **Source Nodes** and columns represent **Target Nodes**. An edge between Node $A$ and Node $B$ is represented by a `1` at coordinate $(A, B)$. This is an **Adjacency Matrix**. ``` Target User 0 1 2 3 Src 0 ┌ 0 1 1 0 ┐ --> User 0 follows User 1 and User 2 User 1 │ 0 0 1 0 │ --> User 1 follows User 2 2 │ 0 0 0 0 │ --> User 2 follows nobody 3 └ 1 1 1 0 ┘ --> User 3 follows User 0, 1, and 2 ``` ### The Problem with Dense 2D Matrices If you have 1,000,000 users and each user has 50 friends: * A standard 2D matrix would require $1,000,000 \times 1,000,000 = 1,000,000,000,000$ (1 Trillion) cells! * That would consume **~1 Terabyte of RAM**, where **99.995% of the cells are empty zeros**. Graphs in the real world are almost always **sparse**—most possible connections do not exist. Therefore, we store only the actual connections using **Compressed Sparse Row (CSR)** and **Compressed Sparse Column (CSC)**. --- ## 3. Compressed Sparse Row (CSR): The Forward Topology **CSR (Compressed Sparse Row)** is the industry standard format for representing sparse matrices and graph adjacencies. It compresses the 2D grid into **two flat, contiguous integer arrays**: 1. **`row_offsets`**: Points to where each source node's target list begins and ends. 2. **`column_targets`**: Contains the actual target node IDs packed contiguously. ### Concrete Example Let's look at the 4-node graph from above: * **Node 0** links to: `1, 2` (2 edges) * **Node 1** links to: `2` (1 edge) * **Node 2** links to: `(none)` (0 edges) * **Node 3** links to: `0, 1, 2` (3 edges) Total edges: $2 + 1 + 0 + 3 = 6$. In CSR format, this entire graph is stored in two compact arrays: ``` row_offsets: [ 0, 2, 3, 3, 6 ] │ │ │ │ │ Node Index: 0 1 2 3 (end) column_targets: [ 1, 2, │ 2, │ (none), │ 0, 1, 2 ] ────── ─── ─────────── Node 0 Node 1 Node 3 ``` ### How an Edge Lookup Works in $O(1)$ To find the outgoing edges for **Node 0**: 1. Read offset range: `start = row_offsets[0]` ($0$), `end = row_offsets[1]` ($2$). 2. Slice `column_targets[0..2]`: `[1, 2]`. To find the outgoing edges for **Node 2**: 1. Read offset range: `start = row_offsets[2]` ($3$), `end = row_offsets[3]` ($3$). 2. Because `start == end`, Node 2 has **0 outgoing edges**. ### CSR Memory Locality and Hardware Prefetch Mechanics * **Instant Degree Calculation**: The degree (edge count) of Node $u$ is simply `row_offsets[u + 1] - row_offsets[u]`—an instant scalar subtraction requiring zero edge traversals. * **CPU Cache Perfection**: All neighbors of a node sit side-by-side in contiguous memory. The CPU prefetcher loads them into L1 cache in a single memory cycle. * **Vector SIMD Friendly**: CPU vector registers (AVX-512, ARM Neon) can process 8 to 16 neighbor IDs simultaneously. * **Primary Use**: Forward traversals (`.out("FOLLOWS")`, BFS, PageRank push). --- ## 4. Compressed Sparse Column (CSC): The Reverse Topology While CSR makes asking *"Who does User 0 follow?"* instant, asking the reverse—*"Who follows User 2?"*—would require scanning every row in the CSR matrix. To make incoming traversals just as fast, Impulse Graph supports **CSC (Compressed Sparse Column)**. * **CSC is the exact transpose of CSR**. * In CSC, the offsets array points to **Target Nodes**, and the targets array stores the **Source Nodes** that point to them. * In our example above, looking up the incoming edges for Node 2 in CSC yields: `[0, 1, 3]` in $O(1)$ time. * **Primary Use**: Incoming traversals (`.in("FOLLOWS")`, reverse reachability, PageRank pull). !!! tip When building general-purpose relations with `SnapshotBuilder`, CSR is the standard forward topology required for `.out(...)` walks, and you can optionally include CSC with a single method call (`.addTopology(Topology.CSC, CompressionScheme.RAW)`). If your edge stream is sorted by source ID, the Impulse builder automatically stages and inverts the stream into CSC using external sort. (At the `.imps` binary specification level, all topology sections—`CSR`, `CSC`, and `COO`—are independently optional to support specialized `M:1` / `1:1` direct-lookup arrays, CSC-only relations, or virtual relations, probed at runtime via `OP_HAS_CSR` / `OP_HAS_CSC`.) --- ## 5. Universal Node Architecture: Domains & Dense IDs One of the most important architectural rules in Impulse Graph is **Per-Domain Dense ID Independence**: ### There is NO Global Flattened ID Space In many graph databases, every node in the entire database is assigned a synthetic global 64-bit ID (e.g., node 1000 is a User, node 1001 is a Product, node 1002 is a Store). Impulse Graph does not use global IDs. Instead, **each Node Domain possesses its own independent, zero-indexed dense integer space ($0 \dots N_d - 1$)**: ``` ┌─────────────────────────┐ ┌─────────────────────────┐ │ User Domain │ │ Account Domain │ │ Cardinality: 10,000 │ │ Cardinality: 50,000 │ ├─────────────────────────┤ ├─────────────────────────┤ │ Dense IDs: 0 .. 9,999 │ │ Dense IDs: 0 .. 49,999 │ │ User 0 ≠ Account 0 │ │ Account 0 ≠ User 0 │ └─────────────────────────┘ └─────────────────────────┘ ``` ### Why Independent Dense IDs? 1. **Direct Array Indexing**: If the `User` domain has 10,000 nodes, its `row_offsets` array has exactly 10,001 entries. Looking up User ID `42` is a direct array access (`offsets[42]`), requiring zero hash tables or ID translation. 2. **Compact Integer Widths**: - Small domains (e.g., categories, states, roles) with $< 65,536$ entities can use 16-bit integers (`PrimitiveWidth.UINT16`), cutting memory usage in half. - Standard domains use 32-bit integers (`PrimitiveWidth.UINT32`), supporting up to 4.29 billion nodes. - Hyperscale domains use 64-bit integers (`PrimitiveWidth.UINT64`). 3. **Domain-Bound Traversals**: Every traversal begins by binding an explicit domain context: ```java snap.domain("User").from(42).out("OWNS").toList(); ``` --- ## 6. How Traversals Execute: Domain Pipelines & Collapsing Intermediate Results Understanding how Impulse Graph evaluates a multi-hop query requires knowing two core execution rules that set it apart from SQL `JOIN`s and traditional Cypher/Gremlin engines: ### Rule 1: Start in One Domain, Walk 0..N Edges, Finish in One Target Domain Every traversal in Impulse Graph is a pipeline that steps from one **Node Domain** to the next: 1. **Anchor to a Single Starting Domain**: You start in one domain (e.g., `User`) with an initial frontier of nodes (one node, a list of nodes, a bitset, or the entire domain). 2. **Step Across 0 or More Directed Relations**: * If you walk **0 edges** (e.g., `snap.domain("User").all().filter("node.age >= 21").toList()`), you stay in `User` and return matching `User` nodes. * Each edge walk transitions the active frontier from the relation's **Source Domain** to its **Target Domain**: $$\text{User} \xrightarrow{\text{PLACED}} \text{Order} \xrightarrow{\text{CONTAINS}} \text{Product}$$ * Any `.filter(...)` or `.project(...)` step along the way operates on the attributes of whichever domain (or edge relation) is currently active at that step. 3. **Materialize from the Single Final Target Domain**: The query finishes in a single target domain (above, `Product`) and returns results from that domain's surviving frontier: * **Target Node IDs or Business Keys** (`toList()`, `toKeyList()`, `toBitSet()`) * **Target Domain Attributes** (e.g., `product.price`, `product.category`) * **Projected State** carried forward along the walk, or a scalar aggregate (`count()`, `sum()`, `max()`). ### Rule 2: Set Semantics (Not Multi-Sets) & Monoidic Reduction (Collapsing Paths) Most query engines (relational SQL `JOIN`s, Neo4j Cypher, Gremlin) use **multi-set (bag-of-paths)** semantics. If User `0` and User `1` both follow User `2`, and User `2` follows 1,000 people, a multi-set engine produces **two duplicate rows** for User `2` at hop 1, and walks all 1,000 of User `2`'s outgoing edges **twice** at hop 2. Over 4 or 5 hops, duplicate paths multiply into millions of redundant intermediate rows. **Impulse Graph uses Set semantics at every step, collapsing converging paths into a single entry per node immediately:** ```text Multi-Set Engine (SQL JOIN / Standard Cypher) — Duplicate Paths Multiply: User 0 ──┐ ┌──► User 2 (Row 1) ──► walks User 2's 1,000 edges ├──► User 2 ───► │ User 1 ──┘ └──► User 2 (Row 2) ──► walks User 2's 1,000 edges AGAIN! Impulse Graph (Set Semantics / Monoidic Reduction) — Collapsed at Every Step: User 0 ──┐ ├──► BitSet[User 2] = 1 ───► walks User 2's 1,000 edges ONCE! User 1 ──┘ ``` * **When Walking Without State (Bitset Union)**: The intermediate frontier is an off-heap **BitSet** with one bit per node in the current domain. Whether 1 edge or 10,000 edges land on `User 2`, bit `2` is simply set to `1` (`OR`). Duplicates are eliminated automatically in $O(1)$ time with zero hash-table overhead. * **When Carrying Calculated State Across Hops (Monoidic Reduction)**: What if each path carries a calculated value (such as transaction `amount`, path `distance`, or `score`) and multiple incoming edges converge on the same target node? Impulse **collapses (reduces)** the converging values into a single value for that target node using an associative reduction operator (**a monoid**): | Reduction Rule (Monoid) | How Converging Values $(v_1, v_2, \dots)$ Are Collapsed | Typical Graph Use Case | | :--- | :--- | :--- | | **Bitwise `OR` (Default)** | $\text{true} \lor \text{true} = \text{true}$ (Set Union) | Multi-hop reachability, ReBAC authorization, filtering | | **`SUM` (`+`)** | $v_1 + v_2 + \dots$ | Total cash flow, path counting, PageRank / Markov walks | | **`MIN`** | $\min(v_1, v_2, \dots)$ | Shortest paths, earliest transaction timestamp | | **`MAX`** | $\max(v_1, v_2, \dots)$ | Maximum bottleneck capacity, highest risk/confidence score | Because every step collapses its output into at most $N_d$ unique entries (one bit—and optionally one state value—per node in the target domain), **intermediate memory never explodes**, even on dense or cyclic graphs. --- ## 7. Business Keys vs. Dense IDs (Primary Key Index) In production databases, entities rarely have continuous 0-indexed integer IDs. You usually have: * **UUIDs**: `"550e8400-e29b-41d4-a716-446655440000"` * **String Business Keys**: `"USR-98421"`, `"alice@example.com"` * **Sparse Relational IDs**: `102, 594, 100024, 8847192` ### How Key Mapping Works When compiling snapshots from CSV/Parquet manifests with the standalone `impulse-graph build` CLI, the compiler builds a compact Section 4 hash index mapping external string/UUID keys to dense IDs ($0 \dots N_d-1$). In Java ingestion pipelines, external database keys are translated during stream generation using an `IdMapper`: ```java // Map external database keys (e.g. Long, String, UUID) to continuous 0..N-1 dense IDs: IdMapper userMapper = new StringIdMapper("User"); long aliceDenseId = userMapper.getOrAssignId("alice@example.com"); // 0 ``` * **At Ingestion Time**: External keys are mapped to continuous $0 \dots N_d-1$ integers. * **During Traversal**: All multi-hop vector traversals execute entirely on fast primitive integers. * **At Result Materialization**: You map target Dense IDs back to external business keys when returning results to your API callers. --- ## 8. Columnar Attributes: Structure of Arrays (SoA) Traditional graph databases store node and edge properties as key-value property maps inside the node object. Impulse Graph stores attributes using a **Structure of Arrays (SoA)** columnar layout: ``` Row-Oriented (Traditional): [ { id: 0, age: 30, score: 9.5 }, { id: 1, age: 24, score: 7.2 }, ... ] Columnar SoA (Impulse Graph): age[]: [ 30, 24, 45, 19, 62, ... ] <-- Contiguous 32-bit integers score[]: [ 9.5, 7.2, 8.8, 6.1, 9.0, ... ] <-- Contiguous 32-bit floats ``` ### Why SoA Matters for Filtering When evaluating a traversal filter like `.filter("node.age >= 21")`: * The CPU loads **only** the `age` vector directly into AVX-512 SIMD registers. * The CPU never reads `score`, names, or edge pointers from disk/RAM. * A single vector instruction evaluates 16 node filters simultaneously, producing a bitmask in nanoseconds. --- ## 9. The Impulse Binary Snapshot (`.imps`) All of the above primitives—CSR matrices, CSC matrices, domain catalogs, string pools, and columnar attributes—are serialized into a single immutable file ending with `.imps` ([Binary Snapshot Specification](../reference/spec/format-specification.md)). * **Page 0 (4KB)**: Fixed header with magic bytes `0x494D5053` (`IMPS`), version `0x000A`, and hardware flags. * **128-Byte Hardware Alignment**: All sections, matrices, and attribute arrays are strictly aligned to 128-byte boundaries. This matches AVX-512 cache lines and GPU warp memory coalescing (NVIDIA GPUDirect Storage `cuFile`). * **Memory-Mapped (`mmap`)**: When your application starts, the operating system maps the `.imps` file into virtual memory in $O(1)$ time without copying data onto the JVM heap or user-space object graphs. --- ## 10. Conceptual Glossary Summary | Term | Canonical Definition | Role in Impulse Graph | | :--- | :--- | :--- | | **`.imps`** | Impulse Binary Snapshot File. | Immutable, 128-byte-aligned binary file format. | | **Node Domain** | A distinct entity namespace (e.g., `User`, `Account`). | Defines an independent dense ID space $0 \dots N_d - 1$. | | **Dense ID** | A zero-indexed primitive integer ($0 \dots N-1$). | Direct index into CSR offsets and columnar attribute arrays. | | **Relation** | A directed edge type connecting a source domain to a target domain. | Encodes graph connections (e.g., `User -[:OWNS]-> Account`). | | **CSR** | Compressed Sparse Row matrix format. | Contiguous `row_offsets` + `column_targets` for fast forward walks (`out`). | | **CSC** | Compressed Sparse Column matrix format. | Transpose of CSR for fast reverse/incoming walks (`in`). | | **COO** | Coordinate format (`src, tgt` pairs). | Stream ingestion format used before CSR/CSC compaction. | | **Primary Key Index** | Reverse index mapping external keys (UUID, String) to Dense IDs. | Translates external business identifiers to dense integer coordinates. | | **SoA Attributes** | Structure of Arrays columnar property storage. | Contiguous primitive vectors enabling SIMD filtering. | | **`SnapshotBuilder`** | Fluent Java builder (`org.impulsegraph:impulse-builder`). | Single-pass streaming generator that builds `.imps` files direct to disk or S3. | --- ## Next Steps Now that you understand the foundational architecture, dive into the hands-on walkthroughs: * **[Building Snapshots Walkthrough (Java)](../ecosystems/java/building-snapshots.md)**: Step-by-step tutorial building an `.imps` snapshot incrementally and streaming from JDBC relational databases. * **[Building Snapshots from Parquet & CSV (CLI & Python)](../ecosystems/python/snapshots-from-parquet-csv.md)**: Compile `.imps` files declaratively from Parquet/CSV tables. * **[Quickstart](quickstart.md)**: Load `.imps` files and execute fluent traversals and prepared statements. ================================================================================ FILE: docs/getting-started/handling-mutations.md | URL: https://www.impulsegraph.org/getting-started/handling-mutations/ ================================================================================ # Changing Data & Live Updates Impulse Graph executes over immutable, read-only `.imps` snapshots. Whether that fits your system depends on your freshness requirement: | Freshness Requirement | Fit? | Recommended Pattern | | :--- | :---: | :--- | | **Strict Real-Time OLTP (< 10 ms read-your-writes)** | Not as-shipped | Keep transactional writes in Postgres/MySQL/RocksDB; optionally pair with Impulse for heavy read traversals. | | **Near Real-Time (5s – 5 min intervals)** | Yes | Periodically rebuild `.imps` from your DB or CDC stream, publish to blob storage, and swap in memory. | | **Periodic Batch (Hourly / Nightly / Per-Deploy)** | Yes | Compile `.imps` in ETL or CI/CD, upload to S3/GCS, and mount across stateless pods. | | **Static Reference & Simulation Graphs** | Yes | Compile once and mount directly from disk. | --- ## 1. Periodic Rebuild $\to$ Blob Storage $\to$ Blue/Green Swap Because an `.imps` file is a set of flat primitive arrays (`row_offsets[]`, `col_indices[]`, and SoA columns) streamed in a single pass with no B-tree rebalancing or random disk seeks, graphs with millions of nodes and tens of millions of edges rebuild in seconds. ```mermaid flowchart LR DB["1. Source of Truth\nPostgres / Lakehouse / CDC"] -->|"Periodic Build\n(e.g. 1–5 min)"| BUILD["2. SnapshotBuilder / CLI\nSingle-pass build\nO(chunk) RAM"] BUILD -->|"Upload"| BLOB["3. Blob Storage (S3 / GCS)\ngraph-v42.imps"] BLOB -->|"Pull & Mount"| POD1["App Pod 1\nAtomic Swap"] BLOB -->|"Pull & Mount"| POD2["App Pod 2\nAtomic Swap"] ``` * **Offload multi-hop reads from OLTP**: Your relational database handles writes and sequential exports; Impulse handles traversals in-process. * **Stateless horizontal scaling**: Scaling from 1 pod to 50 pods is downloading a single `.imps` file—no cluster consensus or cross-node hops. * **Instant rollbacks & local repro**: Each snapshot is an immutable, SHA-256-verified file. Rolling back is swapping back to `graph-v41.imps`. --- ## 2. Zero-Downtime Blue/Green Swaps Swapping to a new snapshot uses an atomic pointer swap plus RCU draining—no `ReadWriteLock` on reader threads: ```text Updater Thread Concurrent Reader Threads ────────────── ───────────────────────── 1. Download new .imps from S3 / NVMe • Core 0: Reading Snapshot A (lock-free) 2. Open in a new Arena • Core 1: Reading Snapshot A (lock-free) 3. AtomicReference.getAndSet(Snap B) ───► • New queries route to Snapshot B 4. Drain in-flight queries on Snap A • In-flight queries on Snap A finish, and close Snapshot A's Arena then Snapshot A is unmapped ``` ```java import org.impulsegraph.api.ImpulseGraphSnapshot; import org.impulsegraph.storage.csr.BinarySnapshotLoader; import java.lang.foreign.Arena; import java.nio.file.Path; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class GraphSnapshotManager implements AutoCloseable { private final AtomicReference currentSnapshot = new AtomicReference<>(); public void swapToNewSnapshot(Path snapshotPath) throws Exception { Arena newArena = Arena.ofShared(); ImpulseGraphSnapshot newSnapshot = BinarySnapshotLoader.loadSnapshot(snapshotPath, newArena).getGraph(); ImpulseGraphSnapshot oldSnapshot = currentSnapshot.getAndSet(newSnapshot); if (oldSnapshot != null) { CompletableFuture.runAsync(() -> { try { oldSnapshot.drainAndClose(30, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); oldSnapshot.close(); } }); } } public ImpulseGraphSnapshot getActiveSnapshot() { return currentSnapshot.get(); } @Override public void close() { ImpulseGraphSnapshot snap = currentSnapshot.getAndSet(null); if (snap != null) snap.close(); } } ``` !!! tip "Production Lifecycle Management (`SnapshotLifecycleManager`)" For production Spring Boot and Kubernetes services requiring background S3/GCS ETag polling, SHA-256 verification before mounting, readiness probes, and automated `Arena` draining, see **[Kubernetes & Snapshot Lifecycle](../ecosystems/java/kubernetes-and-lifecycle.md)**. --- ## 3. Building Snapshots: Rust CLI vs. Java `SnapshotBuilder` | Tool | Best For | Inputs | Runtime | | :--- | :--- | :--- | :--- | | **Rust CLI (`impulse build`)** | Python, C/C++, Go, Node.js, C#, and shell/Airflow pipelines | CSV, TSV, Parquet + `manifest.json` | Native binary (no JVM) | | **Java `SnapshotBuilder`** | JVM services & streaming JDBC ETL | Java collections, JDBC `ResultSet`, `RelationDataSource` | Java 21/25 (`org.impulsegraph:impulse-builder`) | ### Rust CLI (`impulse build`) ```bash impulse build --manifest manifest.json -o graph-v42.imps impulse snapshot validate graph-v42.imps --strict-alignment impulse snapshot inspect graph-v42.imps ``` *(See [Quickstart](quickstart.md#1-build-your-first-imps-snapshot) and [CLI Reference](../reference/cli.md).)* ### Java `SnapshotBuilder` (Bounded Memory Streaming) `SnapshotBuilder` computes section offsets upfront from declared cardinalities and streams the file sequentially to a `FileChannel` or S3/GCS stream within a bounded staging RAM budget (`withStagingMemoryLimit`, default `64 MB`). If reverse (`CSC`) indices are enabled on source-sorted inputs, it automatically runs an external NVMe merge-sort within that budget. Watermarks (Kafka offsets, DB LSNs) can be embedded in footer metadata: ```java try (FileChannel channel = FileChannel.open(outputPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { SnapshotBuilder.create() .withStagingDirectory(Path.of("/tmp/impulse-staging")) .withStagingMemoryLimit(256 * 1024 * 1024L) .addDomain("User", userDomain) .addDomain("Account", accountDomain) .addRelation("OWNS", ownsRelation) .addFooterMetadata("sys.source.watermark_ts", "2026-10-24T20:00:00Z") .writeTo(channel); } ``` --- ## Next Steps * **[Kubernetes & Snapshot Lifecycle (`SnapshotLifecycleManager`)](../ecosystems/java/kubernetes-and-lifecycle.md)** — Production S3/GCS polling, checksum verification, and automated Arena draining in JVM microservices. * **[Building Snapshots (Java)](../ecosystems/java/building-snapshots.md)** — Full runnable JDBC/collection builder walkthrough. * **[Building Snapshots (CLI & Python)](../ecosystems/python/snapshots-from-parquet-csv.md)** — CSV/Parquet manifest reference. * **[Dynamic Service Deployment](../deployment/dynamic-service.md)** — Production Blue/Green swap patterns. ================================================================================ FILE: docs/concepts/why-impulse.md | URL: https://www.impulsegraph.org/concepts/why-impulse/ ================================================================================ # Why Impulse Graph? The Story & Architecture > **"How fast can you traverse a graph?"** > > Turns out, very fast—once you drop in-place mutability, locking, and per-hop heap allocations. --- ## 1. Rethinking Joins, Pointer Chasing, and Immutability Relational databases and mutable graph databases rely on B-trees, heap-linked `Node` objects, or row-oriented `(source, target)` edge tables (COO) to support in-place writes. Every hop pays for pointer chasing, lock acquisition, and heap allocation. Making the graph **immutable and read-only** unlocks **Compressed Sparse Row (CSR)** and **Compressed Sparse Column (CSC)** adjacency layouts, where a node's neighbors sit contiguously in CPU cache lines. An early in-memory CSR prototype—without locks or dynamic allocations—was fast enough to justify building a reusable format and bytecode specification around it. --- ## 2. Filling a Real Open-Source Format Gap To persist multi-domain property graphs without paying a load/deserialization tax, the on-disk format needed: 1. Multiple typed node domains, directed relations, and node/edge attribute columns. 2. Hardware-aligned sections (128-byte boundaries) so applications can `mmap` the file and query immediately. Existing formats did not quite fit: | Format | Single On-Disk File? | Memory-Aligned (`mmap`)? | Multi-Domain CSR/CSC? | Trade-off | | :--- | :---: | :---: | :---: | :--- | | **Apache Parquet** | Yes | No | No | Compressed columnar pages require decoding into RAM before traversal. | | **Apache Arrow (IPC)** | Stream / Batches | Yes | No | Built for tabular data; lacks multi-domain CSR/CSC directories and graph key catalogs. | | **Mutable Graph DBs (Neo4j, etc.)** | Store Files | No | No | Pointer-linked mutable record stores requiring a server process, page cache, and locks. | | **Impulse Snapshot (`.imps`)** | **Yes** | **Yes** | **Yes** | Single immutable file mapped directly into virtual memory by any compliant runtime. | --- ## 3. Enterprise Java First, Zero Dependencies, and Pluggable Runtimes Impulse Graph started for **Enterprise Java** services that needed an in-process graph API without running an external database or pulling in third-party runtime dependencies (and their CVEs) or JNI `.so`/`.dylib` binaries. Supporting **Python** (NumPy, SciPy, PyTorch) and systems languages alongside pure Java meant multiple execution runtimes had to evaluate the same graphs identically. Rather than duplicating high-level query evaluators in each language, the architecture separates the **portable data and bytecode contract** (`.imps` + `impOps`) from **pluggable execution runtimes** across four layers: ```mermaid flowchart LR FE["1. Frontends\nFluent API / openCypher\nImpK / ImpLog"] --> IR["2. Compiler IR\nImpScheme (.impscm)\nOptimization Passes"] IR --> OPS["3. 64-Bit Bytecode\nimpOps (.impb)"] OPS --> VM["4. Pluggable Runtimes\nImpulseVM (R0..R63)\nJVM • C++20/C-ABI • OCaml"] ``` Cross-language compatibility reduces to one testable contract: given the same `.imps` file and `impOps` bytecode, every runtime—currently the **Pure JVM Engine** (`impulse-graph-java`), the **Native C++20 / C-ABI Engine** (`impulse-graph-core`), and the **OCaml Reference Oracle** (`impulse-ocaml`), with a clean specification boundary for future pure managed `.NET` or `WebAssembly` targets—produces bitwise-identical register values and status flags. ### "Isn't Java Inherently Slower Than C++?" Java graph libraries were historically slow because they allocated millions of `Node`, `Edge`, and `HashMap` objects on the heap, triggering cache misses and GC pauses. Once `impulse-graph-java` scans the same off-heap CSR/CSC arrays via FFM `MemorySegment`, the Vector API, and `MethodHandle` JIT chains: 1. **Memory Bandwidth Dominates**: Traversal over contiguous integer arrays has low arithmetic intensity, so DRAM bandwidth and cache-line transfers dominate in both C++ and Java. 2. **The `1.65x` C++ Edge**: On a 10-thread full-graph BFS over the 1.47-billion-edge `twitter-2010` snapshot, C++20 finishes in **`145.00 ms`** and warmed Java 25 in **`240.29 ms`** (`1.65x`, confirmed allocation-free via JFR). The delta comes from `MemorySegment` bounds checks, JVM safepoint polls, and `ForkJoinPool` vs. OpenMP scheduling. 3. **JSON Serialization Costs More Than the Query**: On a 600k-user enterprise directory ReBAC benchmark (100,000 multi-hop permission checks), JFR profiling shows traversal takes **`0.026 µs – 0.552 µs`**, while serializing the response with Jackson takes **`1.908 µs – 2.558 µs` (`3.46x–73.4x` slower)**: | Operation (100,000-Request Benchmark) | Avg Latency | Relative CPU Cost vs. `large` Query | | :--- | :---: | :--- | | **Impulse Java 25 Query (`small`, ~1.8k users)** | **`0.026 µs`** | `0.047x` | | **Impulse Java 25 Query (`medium`, ~48k users)** | **`0.088 µs`** | `0.159x` | | **Impulse Java 25 Query (`large`, 600k users)** | **`0.552 µs`** | `1.00x` Baseline | | **Jackson Streaming JSON (`/dev/null`)** | **`1.908 µs`** | **`3.46x` slower** | | **Jackson JSON String + UTF-8 Bytes** | **`2.558 µs`** | **`4.63x` slower** | *(600k refers to the user corpus size in the directory snapshot, not concurrent network clients.)* --- ## 4. Extensibility Without Rewriting the Core Once the `.imps` layout and `ImpScheme` → `impOps` pipeline existed, additional capabilities mapped cleanly onto the same primitives: * **Datalog (`ImpLog`)**: Compiles recursive rules down to the VM's fixed-point bitset and CSR walk loops. * **GraphBLAS (`ImpK`)**: Maps sparse matrix-vector ops (`OP_MXV`) directly onto CSR/CSC arrays. * **Read-Only openCypher**: Compiles parameterized `MATCH ... WHERE ... RETURN` queries into the same IR. * **Language Ecosystems**: One C-ABI (`impulse_graph.h`) powers Python, Rust, Go, .NET (P/Invoke), Node.js, and C++; one pure JVM core powers Java, Kotlin, Scala 3, and Clojure—and new standalone runtimes only need to implement the 64-register `ImpulseVM` specification. * **Multi-Lane Bit-Sliced Execution (`v0.10.0`, `0xC0`..`0xC9`)**: Generalizes 1-bit frontiers to 8/16/32/64-bit `TYPE_LANE_FRONTIER` buffers for batched seeds and $N-1$ contingency walks without altering the 640-byte VM frame. * **Embedded Vamana ANN (`v0.10.0`, `0x08`, `0xCA`..`0xCB`)**: Adds a Section 2.6 Vamana index with `BQ1`/`SQ8`/`FP16` routing codes and two VM opcodes (`OP_VECTOR_ANN_SEARCH`, `OP_VECTOR_RERANK_DOT`) for hybrid graph-vector search. --- ## 5. Design Inspirations: SQLite and Lua * **SQLite**: Inspired the single-file embedded model, bytecode VM pipeline, `prepare` / `bind` / `execute` / `finalize` C-ABI lifecycle (with caller-allocated buffers sized via `impulse_stmt_buffer_size`), and test-first rigor (spec assembly vectors, 100% opcode coverage, and [Polyglot Validation](../contributing/polyglot-validation.md)). * **Lua 5+ / LuaJIT**: Inspired the 64-register VM (`R0`..`R63`) with fixed 64-bit instructions (`OP_CSR_WALK R5, R4, REL_0`), avoiding stack `PUSH`/`POP` traffic and keeping execution state inside a 640-byte register frame (`impulse_vm_state_t`). --- ## Next Steps * **[Data-Oriented Design](data-oriented-design.md)**: Dense IDs, CSR/CSC locality, SoA columns, bitset frontiers, and `MethodHandle` JIT fusion. * **[Binary Snapshots (`.imps`)](snapshots.md)**: Physical layout, `.imps.schema.yaml` contracts, and Blue/Green snapshot rotation. * **[Mathematical & Categorical Foundations](../academic.md)** & **[Research Literature & Design Lineage](../academic/literature-and-influences.md)**: Formal semiring/Kleisli algebra, CIDR '22 `mmap` analysis, Vamana vs. HNSW trade-offs, and the 29-entry annotated bibliography. ================================================================================ FILE: docs/concepts/data-oriented-design.md | URL: https://www.impulsegraph.org/concepts/data-oriented-design/ ================================================================================ # Data-Oriented Design: Hardware-Native Graph Execution > **Design the physical memory layout first around how the CPU transforms data, and build the abstractions around that layout.** For architectural motivation and design inspirations, see **[Why Impulse Graph?](why-impulse.md)**. This page covers the **memory layout and CPU execution mechanics** behind Impulse Graph. --- ## 1. Why Object-Oriented Graphs Hit a Memory Wall Traditional graph libraries and databases model graphs using **Object-Oriented Design (OOD)** or **Array of Structures (AoS)**: * Every vertex is a heap-allocated `Node` object with an object header, vtable pointer, external ID (`String` or `UUID`), a `Map` of properties, and a `List` of neighbor references. * Traversing an edge means dereferencing a pointer to an arbitrary address in heap memory. On a modern CPU: * **L1 Cache Access**: ~1 nanosecond (~4 cycles) * **Main DRAM Access (Cache Miss)**: ~80–100 nanoseconds (300+ cycles) When a graph is stored as heap-allocated objects connected by pointers, every hop is a random memory access that misses the CPU cache and stalls the instruction pipeline for hundreds of cycles. Worse, in managed runtimes like the JVM, millions of small `Node` and `Edge` objects trigger continuous garbage collection (GC) pauses. --- ## 2. Summary: The Six Data-Oriented Transformations Impulse Graph eliminates pointer chasing, heap allocations, and interpreter overhead through six concrete Data-Oriented Design (DOD) transformations: | Traditional Object-Oriented Approach | Impulse Data-Oriented Design (DOD) | Hardware Impact | | :--- | :--- | :--- | | **1. Pointer References & Global UUIDs**
64-bit heap pointers or hash-table lookups per hop | **Per-Domain Dense IDs ($0 \dots N_d-1$)**
Configurable `uint16`, `uint32`, or `uint64` indices per domain | Node ID *is* the array index ($O(1)$ lookup, zero hashing, up to 4x smaller cache footprint) | | **2. Adjacency Lists of Object Pointers**
`List` scattered across the heap | **Contiguous CSR & CSC Arrays**
128-byte-aligned `row_offsets[]` and `col_indices[]` in `.imps` | All neighbors of a node sit contiguously in L1 cache lines; hardware prefetcher streams ahead | | **3. Array of Structures (AoS) Properties**
`Map` attached to each node | **Structure of Arrays (SoA) Columns**
128-byte-aligned primitive vectors (`age[]`, `score[]`) | Filtering `.filter("node.age >= 21")` loads only `age[]` into SIMD registers; zero wasted bandwidth | | **4. Object Queues & Hash-Set Deduplication**
`Queue` and `HashSet` per BFS hop | **Off-Heap Bitset & Multi-Lane Frontiers**
$\lceil N_d / 64 \rceil$ 64-bit words, Roaring Bitmaps, or 8/16/32/64-bit `TYPE_LANE_FRONTIER` (`v0.10.0`) | 64 nodes tested/merged per CPU instruction (or 64 independent walks fused in one CSR pass); automatic path deduplication | | **5. Dynamic Heap Allocations per Query**
Resizing lists, hash tables, and boxed objects | **Pre-Determined, Caller-Allocated Buffers**
Exact scratch + result size known at `prepare` time | Zero allocations (`malloc`/`new`) in the hot query path; lock-free, GC-free extreme concurrency | | **6. AST Interpreter / Stack Machine**
Polymorphic `Step.next()` or `PUSH`/`POP` stack traffic | **640-Byte Register VM & `MethodHandle` JIT**
64-bit instructions over `R0`..`R63` (`impulse_vm_state_t`) | Entire VM state fits in 10 L1 cache lines; Java 25 C2 JIT fuses shaders into native machine code | --- ## 3. Transformation 1: Per-Domain Dense IDs ($0 \dots N_d - 1$) Instead of assigning 64-bit memory pointers or global UUIDs to every vertex, every **Node Domain** (`User`, `Account`, `Resource`) in an `.imps` snapshot has its own independent, 0-indexed dense integer space $0 \dots N_d - 1$: * **The ID Is the Offset**: Looking up node `k`'s outgoing edges or attribute value requires zero hashing and zero B-tree searches—it is a direct $O(1)$ array read at index `k`. * **Configurable Integer Widths**: Each domain configures its physical integer width based on cardinality (`uint16` up to 65K nodes, `uint32` up to 4.29B nodes, or `uint64`), packing up to 4x more target IDs into every 64-byte CPU cache line. * **Boundary Key Resolution**: External business keys (`UUID`, `String`, `int64`) are resolved to Dense IDs once at the start of the query (`fromKey` / `OP_MAP_KEYS_TO_DENSE`) and mapped back at materialization (`toKeyList` / `OP_MAP_DENSE_TO_KEYS`), keeping the entire traversal loop on dense integers. --- ## 4. Transformation 2: Contiguous CSR & CSC Adjacency Matrices In an `.imps` snapshot, every directed relation $R: D_{\text{src}} \to D_{\text{tgt}}$ is stored as a **128-byte-aligned Compressed Sparse Row (CSR)** matrix (and optional **Compressed Sparse Column (CSC)** transpose for reverse traversals): ```text CSR Layout in .imps (128-Byte Aligned Off-Heap Memory): row_offsets[]: [ 0 | 3 | 5 | ... ] ◄── Node 0's neighbors are at indices [0..3) │ └────────────── Node 1's neighbors are at indices [3..5) ▼ col_indices[]: [ 12 | 47 | 109 | 8 | 47 | ... ] └─────┴─────┘ └───┴──► Contiguous in L1 cache; hardware prefetcher streams ahead ``` * **Zero Pointer Chasing**: Walking all outgoing edges of node `u` reads `start = row_offsets[u]` and `end = row_offsets[u + 1]`, then scans the contiguous slice `col_indices[start..end]`. * **"Mmap and Go"**: Because `row_offsets[]` and `col_indices[]` sit at 128-byte-aligned offsets inside the `.imps` file, mounting the graph is a single OS `mmap` call. --- ## 5. Transformation 3: Structure of Arrays (SoA) vs. Array of Structures (AoS) Consider evaluating `.filter("node.age >= 21")` across 10,000,000 `User` nodes where each user has an `id`, `name`, `email`, `age`, and `created_at`: ```text Traditional Array of Structures (AoS) / Object Heap: ┌──────────────────────────────────────────┐ ┌──────────────────────────────────────────┐ │ Object Header (16B) | id | name* | age │ ──► │ Object Header (16B) | id | name* | age │ └──────────────────────────────────────────┘ └──────────────────────────────────────────┘ ▲ Every 64-byte CPU cache line pulls in headers, pointers, and unused fields. Impulse Structure of Arrays (SoA) in .imps (128-Byte Aligned): age[]: [ 30 | 24 | 45 | 19 | 62 | 28 | 33 | 41 | 50 | 18 | 29 | 37 | 44 | 22 | 31 | 26 ] └─── Single 64-byte cache line holds 16 contiguous int32 values (100% utilization) ``` 1. A single 64-byte cache line holds **16 contiguous 32-bit `age` integers** (or 32 `uint16` values). 2. A single AVX-512 or Java 25 Vector API instruction compares all 16 values against `21` in one clock cycle and writes the surviving bitmask directly into an off-heap bitset word. 3. Unreferenced attributes (`name`, `email`, `created_at`) are never paged in from disk or loaded into CPU cache. --- ## 6. Transformation 4: Bitset Frontiers & Push/Pull Direction Optimization In a textbook Breadth-First Search (BFS) or multi-hop database join, active vertices are pushed and popped from a `Queue` or `HashSet`, allocating objects and computing hashes on every hop. In `ImpulseVM`, an active frontier over a domain of $N_d$ nodes is represented as a contiguous off-heap **BitSet** ($\lceil N_d / 64 \rceil$ 64-bit `uint64_t` words) or compressed Roaring Bitmap: * **64 Nodes per Register Word**: Testing, uniting (`OR`), intersecting (`AND`), or differencing (`AND NOT`) 64 nodes takes a single bitwise CPU instruction—or 512 nodes per instruction with AVX-512. * **Zero Duplicate Work**: Converging paths across high-fanout graphs automatically coalesce via bitwise `OR` without hash-set deduplication overhead. * **Direction-Optimizing Push/Pull**: When the frontier is sparse, `ImpulseVM` walks outgoing CSR slices (**Push**); when the frontier becomes dense, it can switch to scanning incoming CSC slices (**Pull**) and terminate early as soon as a parent bit is found. ### 6.1 Multi-Lane Bit-Sliced Frontiers (Planned `v0.10.0`: `0xC0`..`0xC9`) When a workload evaluates up to 64 independent seed queries, concept-group expansions, or counterfactual $N-1$ edge-outage contingencies over the same graph, running 64 separate 1-bit BFS passes streams `row_offsets[]` and `col_indices[]` from DRAM 64 times. In `v0.10.0`, `TYPE_LANE_FRONTIER` (`0x10`) transposes the frontier layout into a **bit-sliced array** (`uint8_t[N]`, `uint16_t[N]`, `uint32_t[N]`, or `uint64_t[N]`), assigning each concurrent walk or contingency to bit position $b \in [0, 63]$: ```c // Single-pass 64-lane CSR propagation with per-edge counterfactual trip masks (OP_LANE_CSR_WALK 0xC3) uint64_t u_lanes = current_lanes[u] & active_mask; if (u_lanes != 0) { for (uint64_t e = row_offsets[u]; e < row_offsets[u + 1]; ++e) { uint32_t v = col_indices[e]; next_lanes[v] |= (u_lanes & ~edge_trip_mask[e]); } } ``` * **64 Walks per CSR Read**: Because `row_offsets[u]` and `col_indices[e]` are fetched once from memory and shared across all 64 bitwise lanes, memory bandwidth is amortized across up to 64 simultaneous traversals. In the Pure Java 25 `MultiLaneVmBenchmarkTest` (`50,000` nodes, `500,000` edges, 2-hop walk), wall-clock latency remains nearly flat at **`~0.23 ms`** from $L=1$ to $L=64$ lanes, scaling effective throughput from **`2,229.5 Effective Lane-MTEPS`** ($L=1$) to **`138,979.4 Effective Lane-MTEPS`** ($L=64$, a **`62.3x`** throughput multiplier over sequential single-lane execution). * **Locality-Preserving Node Reordering (`--vamana-locality`)**: For hybrid vector-graph workloads using Section 2.6 `IMP_INDEX_VAMANA_ANN` (`0x08`, `v0.10.0`), running `impulse opt --vamana-locality` reorders dense Node IDs by a BFS traversal from the Vamana medoid $m^*$, permuting the CSR/CSC arrays, `[N, D]` `FLOAT32` embeddings, and Vamana adjacency/quantized slabs in lockstep so neighbor expansions during greedy beam search (`OP_VECTOR_ANN_SEARCH` `0xCA`) hit adjacent cache lines. --- ## 7. Transformation 5: Pre-Determined Query Memory & Zero-Allocation Hot Path A foundational design rule of Impulse Graph is **zero memory allocations in the hot query path**: 1. **Deterministic Footprint at `prepare` Time**: Because an `.imps` snapshot is immutable and every domain's cardinality $N_d$ is fixed, the exact workspace memory required to execute a query—its 640-byte `impulse_vm_state_t` register frame, its scratch bitsets ($4 \times \lceil N_d / 64 \rceil \times 8\text{ bytes}$), and its output column projection area—is **explicitly calculated when the query is prepared** (`impulse_stmt_buffer_size(stmt)`, enforced in bytecode via `OP_ALLOC_SCRATCH` and `OP_ASSERT_SCRATCH_BYTES`). 2. **Pre-Allocated & Passed In by the Caller**: * **C / C++20 C-ABI**: The caller queries `impulse_stmt_buffer_size(stmt)` once, pre-allocates a reusable buffer (thread-local, stack, or arena), and passes it into `impulse_stmt_execute(stmt, buffer, buffer_size)` (see [Zero-Alloc Buffers & Projections](key-mapping-and-projections.md)). * **Pure Java 25**: `ImpulseVmInterpreter.execute(programSeg, instructionCount, snapshot, input, arena)` and `ImpulseStatement.execute()` operate over off-heap `MemorySegment` slices (`VmStateLayout.VM_STATE_LAYOUT` and `OffHeapBitSet`), recycling bitset handles (`acquireBitset()` / `releaseBitset()`) and ping-ponging frontiers in place via `OP_SWAP_REG`. 3. **Lock-Free Concurrency**: Because `.imps` snapshots are read-only and each query runs in its own caller-supplied workspace and 640-byte register frame, OS threads or Java Virtual Threads execute concurrently over the same snapshot without locks or GC pauses. --- ## 8. Transformation 6: The 640-Byte Register VM & Java 25 `MethodHandle` JIT Once the graph layout is contiguous and cache-aligned, the execution engine itself must not become the bottleneck: * **640-Byte Cache-Aligned Register Frame (`impulse_vm_state_t`)**: Inspired by the Lua VM, `ImpulseVM` uses 64 general-purpose registers (`R0`..`R63`) and fixed 64-bit `impOps` instructions (`opcode[8] | flags[8] | dst_reg[16] | payload[32]`). The entire VM execution state is exactly **640 bytes** (10 CPU cache lines), staying hot in L1 cache throughout execution. * **Java 25 `MethodHandle` Combinator JIT (`ImpulseMethodHandleCompiler` & `ShaderCompiler`)**: Instead of interpreting bytecode in a `switch` loop at query time, the Pure Java 25 engine compiles `impOps` programs and stream-walk filter/projection shaders (`OP_CSR_WALK_STREAM`, `OP_CSC_WALK_STREAM`) into trees of `java.lang.invoke.MethodHandle` combinators using `MethodHandles.insertArguments` and `MethodHandles.foldArguments`. When invoked, the JVM's **C2 JIT compiler** constant-folds the register offsets and inlines the entire chain of shader operations into a single contiguous block of native machine code with **zero interpreter dispatch overhead**. ================================================================================ FILE: docs/concepts/snapshots.md | URL: https://www.impulsegraph.org/concepts/snapshots/ ================================================================================ # Binary Snapshots, Domains & Schema (`.imps`) An **Impulse Binary Snapshot (`.imps`)** is a single, read-only file whose on-disk byte layout matches the in-memory data structures. Sections are padded to **128-byte boundaries** so applications can `mmap` the file and query immediately without deserialization. --- ## 1. The Typed Graph Schema: Domains, Dense IDs & Relations Every `.imps` snapshot is governed by an explicit, strongly-typed schema—authored as a shared **`.imps.schema.yaml`** contract (for [schema-first validation and AOT code generation](../ecosystems/java/aot-codegen.md); see [Schema & Manifest Spec](../reference/spec/schema-specification.md)), a declarative `manifest.json` ingestion file (for the [CLI & Python Parquet/CSV Builder](../ecosystems/python/snapshots-from-parquet-csv.md)), or programmatically via [Java `SnapshotBuilder`](../ecosystems/java/building-snapshots.md). ```mermaid flowchart LR subgraph D0 ["Domain 0: User (N = 10,000, uint16)"] U_KEY["Key Index (MPHF)\n'usr_101' → Dense ID 0"] U_SOA["SoA Columns (128B Aligned)\nage[0..N] | risk_score[0..N]"] end subgraph REL ["Relation: OWNS (User → Account)"] CSR["CSR Forward: row_offsets[] + col_indices[]"] CSC["CSC Reverse: col_offsets[] + row_indices[]"] end subgraph D1 ["Domain 1: Account (N = 250,000, uint32)"] A_KEY["Key Index (MPHF)\n'acc_5001' → Dense ID 42"] A_SOA["SoA Columns (128B Aligned)\nbalance[0..N]"] end D0 --> REL --> D1 ``` ### 1.1 Independent Per-Domain Dense IDs ($0 \dots N_d - 1$) Unlike graph databases that assign a global 64-bit ID across all vertices, **every Node Domain (`User`, `Account`, `Product`) has its own independent, 0-indexed dense integer space ($0 \dots N_d - 1$)**: * **Disjoint ID Spaces**: Dense ID `0` in `User` and Dense ID `0` in `Account` are distinct entities in separate namespaces. * **Direct Array Indexing**: Because IDs are contiguous from $0$ to $N_d - 1$, a node's Dense ID *is* its array index ($O(1)$ offset lookup) into CSR `row_offsets[]` and Structure-of-Arrays (SoA) attribute columns. * **Configurable Integer Widths**: Each domain configures its physical integer width based on cardinality (`uint16` up to 65,536 nodes, `uint32` up to 4.29B nodes, or `uint64`), minimizing CPU cache footprint. ### 1.2 External Business Keys & Boundary Resolution Applications identify entities using external primary keys (`String`, `UUID`, or integer/float keys). Each domain optionally embeds a **Minimal Perfect Hash (`_domain_index`)** or sorted permutation index inside the `.imps` file: 1. **Input Resolution (`fromKey` / `impulse_snapshot_resolve_key`)**: Resolves external keys (e.g., `"usr_101"`) to internal Dense IDs once at the start of a query in $O(1)$ or $O(\log N)$ time. 2. **Dense Traversal**: All multi-hop walks, bitset operations, and SIMD attribute filters execute strictly on primitive Dense IDs. 3. **Output Materialization (`toKeyList` / `impulse_snapshot_resolve_dense_id`)**: Maps surviving target Dense IDs back to external business keys via zero-copy `mmap` pointers. ### 1.3 Directed Relations & Columnar Attributes * **Directed Relations (`SrcDomain` $\to$ `TgtDomain`)**: Each relation is stored as its own isolated **CSR** (forward `.out(...)`) matrix and optional **CSC** (reverse `.in(...)`) transpose. During snapshot compilation and Stage 2 query binding, human-readable names (`"User"`, `"OWNS"`, `"age"`) resolve to compact **16-bit catalog IDs** encoded directly in the 64-bit `impOps` instruction word. * **Node & Edge Attributes (SoA)**: Stored as contiguous, 128-byte-aligned primitive vectors (`int8`..`int64`, `float16`..`float64`, timestamps, strings, or fixed-width `[N, D]` vector embeddings) with optional Arrow-compatible validity bitmaps. --- ## 2. Physical `.imps` File Layout An `.imps` file is written sequentially in five hardware-aligned sections: ```text ┌────────────────────────────────────────────────────────────────────────────┐ │ Section 1: Page 0 Header (Fixed 4 KB, 64-byte active baseline) │ │ Magic: 0x494D5053 ("IMPS") | DataOffset: 4096 | Counts, UUID & Flags │ ├────────────────────────────────────────────────────────────────────────────┤ │ Section 2: Shared String Table, Domain Catalog & Relation Directory │ │ Global UTF-8 string pool, Domain descriptors (N_d, width), Relation IDs │ ├────────────────────────────────────────────────────────────────────────────┤ │ Section 3: Relation Topology & Edge Attribute Blocks (128-Byte Aligned) │ │ Per-relation CSR (row_offsets[], col_indices[]), CSC & edge attributes │ ├────────────────────────────────────────────────────────────────────────────┤ │ Section 4: Node SoA Attribute & Key Index Blocks (128-Byte Aligned) │ │ Contiguous scalar columns, [N, D] vector tensors, Key Catalog & Indices │ ├────────────────────────────────────────────────────────────────────────────┤ │ Section 5: Footer & Integrity Block (EOF) │ │ Key-value build metadata, SHA-256 payload checksum, 16-byte "IMPS" Magic │ └────────────────────────────────────────────────────────────────────────────┘ ``` * **128-Byte Hardware Alignment**: Every topology and attribute array starts on a 128-byte offset (2 CPU cache lines), enabling unpenalized AVX-512 / ARM Neon vector loads and direct NVIDIA GPUDirect Storage (`cuFile`) warp coalescing. * **Single-Pass Sequential Streaming**: Because sections are written sequentially without backward file seeks, both `impulse build -o -` and Java `SnapshotBuilder` can stream `.imps` files directly to Amazon S3 or Google Cloud Storage in $O(\text{chunk})$ RAM. --- ## 3. Specification Limits & Supported Data Types ### 3.1 Structural Capacity Limits | Snapshot Component | Header / Descriptor Field | Maximum Limit | Notes | | :--- | :--- | :--- | :--- | | **Node Domains per Snapshot** | `DomainCount` (`uint16_t`) | **`65,536` (`2^16`)** | `DomainID` ranges from `0` to `65,535`. | | **Relations per Snapshot** | `RelationCount` (`uint16_t`) | **`65,536` (`2^16`)** | `RelationID` ranges from `0` to `65,535`. | | **Nodes per Domain ($N_d$)** | `NodeIDWidth` (`2`, `4`, or `8` bytes) | • `uint16`: **`65,536`**
• `uint32`: **`4,294,967,296` (~4.29B)**
• `uint64`: **`2^64 - 1` (~1.84 × 10^19)** | Configured independently per domain to minimize cache footprint. | | **Edges per Relation ($E$)** | `EdgeIndexWidth` (`4` or `8` bytes) | • `uint32` offsets: **`4,294,967,295` (~4.29B)**
• `uint64` offsets: **`2^64 - 1`** | Controls the byte width of `csrRowOffsets[]` and `cscRowOffsets[]`. | | **Attributes per Domain / Relation** | `AttrCount` (`uint16_t`) | **`65,536` (`2^16`)** | Applies independently to each domain and each relation. | | **Shared String Table (`Section 2`)** | `StringTableBytes` (`uint32_t`) | **`4 GB` (`2^32 - 1` bytes)** | Stores schema and catalog identifier names (domain, relation, and attribute names; `NameOffset` is `uint32_t`). | | **Total Snapshot File Size** | 64-bit Section Offsets (`uint64_t`) | **Multi-Terabyte (`2^64 - 1` bytes)** | All topology and attribute `DataOffset` and `DataBytes` fields are 64-bit unsigned integers. | ### 3.2 Attribute & Key Data Types (`impulse_attribute_descriptor_t`) Every node or edge attribute is described by a 44-byte descriptor (`TypeCode`, `Dimension`, 64-bit `DataOffset` / `DataBytes`, and optional `OffsetsOffset`). Bit 7 (`0x80`) of `TypeCode` is the **Nullability Flag**: * **Non-Nullable (`Bit 7 == 0`)**: 0 bytes of bitmap overhead; 100% of space is contiguous values. * **Nullable (`Bit 7 == 1`)**: Prepends an aligned **Arrow Validity Bitmap** ($\lceil K / 64 \rceil \times 8$ bytes, 1 bit per element: `1` = valid, `0` = null) before the value array. | Type Code | Base Type | Element Width | Vector Dimension (`D`) | Physical Layout & Size Limits | | :---: | :--- | :--- | :---: | :--- | | `0x01` | `INT8` / `UINT8` | `1 Byte` | $D \ge 1$ | Contiguous $K \times D$ bytes (`1` = scalar, $D > 1$ = quantized `int8` embedding). Unlimited 64-bit column size. | | `0x02` | `INT16` / `UINT16` | `2 Bytes` | $D \ge 1$ | Contiguous $K \times D \times 2$ bytes. Unlimited 64-bit column size. | | `0x03` | `INT32` / `UINT32` | `4 Bytes` | $D \ge 1$ | Contiguous $K \times D \times 4$ bytes. Unlimited 64-bit column size. | | `0x04` | `INT64` / `UINT64` | `8 Bytes` | $D \ge 1$ | Contiguous $K \times D \times 8$ bytes. Unlimited 64-bit column size. | | `0x05` | `FLOAT16` | `2 Bytes` | $D \ge 1$ | Contiguous $K \times D \times 2$ bytes (`fp16` / `bfloat16` scalar or vector tensor). Unlimited 64-bit column size. | | `0x06` | `FLOAT32` | `4 Bytes` | $D \ge 1$ | Contiguous $K \times D \times 4$ bytes (IEEE-754 float scalar, edge weights, or `[K, D]` embedding tensor). | | `0x07` | `FLOAT64` | `8 Bytes` | $D \ge 1$ | Contiguous $K \times D \times 8$ bytes (IEEE-754 double). Unlimited 64-bit column size. | | `0x08` | `TIMESTAMP_MS` | `8 Bytes` | $D \ge 1$ | 64-bit Unix epoch milliseconds (`uint64_t`). | | `0x09` | `TIMESTAMP_NS` | `8 Bytes` | $D \ge 1$ | 64-bit Unix epoch nanoseconds (`uint64_t`). | | `0x0A` | `FIXED_BYTES` | `D Bytes` | $D \ge 1$ | Fixed-width binary value per row (e.g. `D = 16` for 128-bit `UUID`, `D = 32` for `SHA-256`). | | `0x0B` | `VAR_STRING` | Variable | `0` | Per-column `uint32_t offsets[K + 1]` + contiguous UTF-8 byte blob (up to **`4 GB`** payload per column). | | `0x0C` | `VAR_BYTES` | Variable | `0` | Variable-length binary column stored as `uint32_t offsets[K + 1]` + contiguous byte blob (up to **`4 GB`** payload per column). | | `0x0D` | `INTERVAL_SEC_32` | `8 Bytes` | $D \ge 1$ | Packed temporal validity interval (`uint32_t start_sec`, `uint32_t duration_sec`). | | `0x0E` | `INTERVAL_MS_64` | `16 Bytes` | $D \ge 1$ | Packed temporal validity interval (`uint64_t start_ms`, `uint64_t duration_ms`). | --- ## 4. Lock-Free `GraphView` & Atomic Blue/Green Swaps At runtime, an `ImpulseGraphSnapshot` (or `GraphView`) wraps the read-only `mmap` region. Because the mapped file is strictly immutable: * **Zero Reader Locks**: Thousands of threads can traverse the same snapshot simultaneously without mutexes or `ReadWriteLock` cache-line bouncing. * **Zero-Downtime Updates**: When upstream data changes, an out-of-band builder compiles a new `.imps` generation (`B`), maps it in `< 1 ms`, and atomically swaps the active snapshot pointer while in-flight queries on generation `A` drain cleanly (see **[Changing Data & Live Updates](../getting-started/handling-mutations.md)**). --- ## Next Steps * **[Zero-Allocation Execution & Buffers](key-mapping-and-projections.md)**: See how fixed domain cardinalities allow Impulse to pre-calculate exact query memory before a query runs. * **[Compiler Pipeline & ImpulseVM](compiler-architecture.md)**: Explore how queries compile into 64-bit `impOps` bytecode and execute on `ImpulseVM`. * **[Normative Binary Snapshot Specification](../reference/spec/format-specification.md)**: Byte-level struct definitions and protocol tables. ================================================================================ FILE: docs/concepts/key-mapping-and-projections.md | URL: https://www.impulsegraph.org/concepts/key-mapping-and-projections/ ================================================================================ # Zero-Allocation Execution & Caller Buffers A defining guarantee of **Impulse Graph Engine** is **zero dynamic memory allocations (`malloc` / `new`) in the hot query path**. In a traditional database, a multi-hop query allocates and resizes hash tables, lists, and intermediate row objects as it runs—Because the engine cannot predict how many duplicate paths will fan out, memory grows unpredictably and triggers garbage collection (GC) or allocator contention. Because Impulse Graph operates over **immutable `.imps` snapshots** with **set-based monoidic reduction**, the exact memory required for any query is **100% deterministic before the query ever executes**. --- ## 1. Why Query Memory Is Deterministic at `prepare` Time When a query is compiled against an `.imps` snapshot: 1. **Domain Cardinalities ($N_d$) Are Fixed**: Every node domain's exact size $N_d$ is stored in the Section 2 Domain Catalog. 2. **Frontiers Are Bounded by $N_d$**: Because intermediate results are [collapsed into sets at every hop](../getting-started/index.md#how-queries-work-the-two-core-mechanics), a reachability frontier over domain $D$ never exceeds $\lceil N_d / 64 \rceil$ 64-bit words, and a scalar state vector never exceeds $N_d \times \text{sizeof}(\text{state})$. 3. **Static Register & Scratch Accounting**: During compilation, the compiler emits `OP_ALLOC_SCRATCH` and `OP_ASSERT_SCRATCH_BYTES` instructions, computing the exact byte count needed for both intermediate VM scratch space and final columnar output projections. --- ## 2. The SQLite-Style Prepared Statement Lifecycle In the C/C++20 C-ABI (`impulse_stmt_*`) and all language bindings built on it, the caller queries the required buffer size once at `prepare` time, allocates or reuses a memory block (on the stack, in a thread-local buffer, or in a custom arena), and passes it into `execute`: ```text 1. Prepare (Microsecond) impulse_stmt_prepare(snap, query_str, &stmt) └─ Compiles AST -> impOps bytecode & computes workspace bounds 2. Query Required Size size_t buf_len = impulse_stmt_buffer_size(stmt) └─ Exact byte count for Scratch Area + Columnar Return Area 3. Supply Reusable Buffer void* buf = thread_local_arena(buf_len); // Allocated once per thread 4. Bind Parameters impulse_stmt_bind_str(stmt, "$user", "usr_101"); impulse_stmt_bind_float(stmt, "$min_amt", 1000.0); 5. Execute (0 Allocations) impulse_stmt_execute(stmt, buf, buf_len); └─ Runs entirely inside the 640B VM register frame + caller buffer 6. Read Columnar Results const void* col0 = impulse_stmt_column_data(stmt, 0); └─ Zero-copy Arrow-compatible typed arrays & validity bitmaps ``` In the **Pure Java 25 Engine**, `ImpulseVmInterpreter.execute(programSeg, instructionCount, snapshot, input, arena)` and `ImpulseStatement.execute()` follow the exact same off-heap discipline over reusable `java.lang.foreign.MemorySegment` slices (`VmStateLayout` + `OffHeapBitSet` handle pools), ping-ponging intermediate frontiers in place via `OP_SWAP_REG` with zero heap object creation. --- ## 3. Inside the Caller-Provided Memory Buffer When `impulse_stmt_execute(stmt, buf, buf_len)` runs, the engine partitions the caller's contiguous buffer into 128-byte-aligned regions: ```text Caller-Provided Memory Buffer (buf, buf_len): ┌─────────────────────────┬─────────────────────────┬─────────────────────────┬─────────────────────────┐ │ Section A: Scratch Area │ Section B: Col 0 Data │ Section C: Col 1 Data │ Section D: Null Bitmaps │ │ Internal VM Bitsets & │ Contiguous Typed Array │ Contiguous Typed Array │ Arrow Validity Bitmaps │ │ State Vector Registers │ (e.g. uint32_t IDs or │ (e.g. float64_t scores │ (1 bit per row: │ │ (128-Byte Aligned) │ const char* pointers) │ or projected totals) │ 1 = valid, 0 = NULL) │ └─────────────────────────┴─────────────────────────┴─────────────────────────┴─────────────────────────┘ ``` * **No String Copies on Projection**: Variable-length string attributes and string domain keys (`VAR_STRING` `0x0B`) are stored in Section 4 as per-column `uint32_t offsets[K+1]` arrays paired with a contiguous UTF-8 byte blob (while Section 2 stores schema/catalog names). Projecting strings slices `(offsets[id], offsets[id + 1])` directly inside the mapped blob without copying characters to the heap. * **Arrow-Compatible Null Bitmaps**: Non-nullable columns (`NullCount == 0`) omit the bitmap (`null_bitmap == NULL`). Nullable columns emit an aligned validity bitmap (`bit i == 1` valid, `bit i == 0` null) that maps directly to Arrow / PyArrow arrays. * **Boundary Key Resolution**: External business keys (`String`, `UUID`, `int64`) are resolved to dense `0..N_d-1` IDs within the anchored domain once at the start of execution (`OP_MAP_KEYS_TO_DENSE` / `fromKey`) and projected back to external keys only for surviving output rows in the target domain (`OP_MAP_DENSE_TO_KEYS` / `toKeyList`). --- ## Next Steps * **[Compiler Pipeline & ImpulseVM](compiler-architecture.md)**: See how queries are optimized using snapshot metadata and executed on the 64-register VM. * **[C-ABI Kernel & VM Reference](../reference/c-abi.md)**: Full struct and function signatures for `impulse_stmt_*` and `impulse_snapshot_*`. ================================================================================ FILE: docs/concepts/compiler-architecture.md | URL: https://www.impulsegraph.org/concepts/compiler-architecture/ ================================================================================ # Compiler Pipeline & ImpulseVM Execution Every query in **Impulse Graph Engine**—whether written in the Fluent API, openCypher, Google CEL, ImpLog (Datalog), or ImpK (GraphBLAS)—compiles through a single multi-pass pipeline into **64-bit `impOps` bytecode** and executes on **`ImpulseVM`**. ```mermaid flowchart LR FE["1. Query Frontends\nFluent API • openCypher\nCEL • ImpLog • ImpK"] --> IR["2. ImpScheme IR (.impscm)\nHomoiconic S-Expr AST"] IR --> S1["3. Stage 1 Optimizer\nSnapshot-Agnostic\nConstant Folding & Algebra"] S1 --> S2["4. Stage 2 Optimizer\nSnapshot-Bound\nZone Maps, Fusion, Push/Pull"] S2 --> VM["5. ImpulseVM (R0..R63)\n64-Bit impOps (.impb)\nJava 25 JIT & C++20 SIMD"] ``` --- ## 1. The Immutable Snapshot Optimization Thesis In traditional relational and graph databases, query optimizers operate under **probabilistic uncertainty**: because the database is mutating concurrently, the planner relies on sampled histograms and must compile conservative execution plans. > **Because an `.imps` snapshot is 100% immutable, every structural statistic—domain cardinalities ($N_d$), degree bounds, relation multiplicities ($1:1, 1:N, N:1$), null counts, and per-attribute `[min, max]` Zone Maps—is exact.** Binding a query AST to an `.imps` snapshot turns heuristic query planning into **deterministic algebraic simplification**. ### Two-Stage Optimization Pipeline To support sub-microsecond plan caching across Blue/Green snapshot swaps, optimization is split into two stages: | Stage | When It Runs | Key Optimization Passes | Concrete Impact | | :--- | :--- | :--- | :--- | | **Stage 1: Snapshot-Agnostic** | Once when a query is registered or parsed | • **AstNormalizationPass & ParameterBindingPass**
• **PreBindValidator & CelPredicateFlatteningPass**
• **ConstantFoldingPass & MonotonicHomomorphismPass**
• **ZoneMapPruningPass & AlgebraicTypeInferencePass** | • Flattens and normalizes CEL ASTs into canonical forms.
• Folds constant math and inverts monotonic expressions ($\sqrt{x} < c \implies x < c^2$).
• Commutes monotonic functions across reductions ($\max(f(X)) \to f(\max(X))$).
• Evaluates constant predicates and zone-map bounds when snapshot statistics are supplied. | | **Stage 2: Snapshot-Bound** | When binding a query to a specific `.imps` file (`< 2 µs`) | • **BindTimeValidator & DirectionSelectionPass**
• **FilterPushdownPass & InjectiveDeduplicationBypassPass**
• **KernelFusionPass (`OP_CSR_WALK_2HOP`)**
• **VirtualRelationDecompositionPass**
• **PhysicalBindingPass & RegisterAllocationPass** | • Decomposes virtual relations and prunes non-matching partitions.
• Validates relation schema and chooses traversal direction (CSR vs. CSC).
• Pushes edge and node filters directly into traversal walk shaders.
• Bypasses deduplication on $1:N$ injective relations (`isInjective()`).
• Fuses low-multiplicity 2-hop CSR walks into `OP_CSR_WALK_2HOP`.
• Assigns 640-byte VM register frames (`R0`..`R63`). | ### Inspecting Bytecode Disassembly (`.impas`) Any compiled query can be disassembled into canonical human-readable **ImpAsm (`.impas`)** text assembly (via `ImpAsmDisassembler.disassemble(program)` in Java or `impulse disassemble` in the CLI): ```impas .version 0.10.0 .instructions 4 0x0000: OP_CSC_WALK flags=0x03, dst=R1, payload=0x00240000 ; Walk src=R0 -> dst=R1 via rel[36] [seed-inlined] 0x0001: OP_CSR_WALK flags=0x01, dst=R0, payload=0x00080001 ; Walk src=R1 -> dst=R0 via rel[8] [early-exit] 0x0002: OP_COLLECT_BITSET flags=0x00, dst=R0, payload=0x00000000 ; Materialize surviving bitset in R0 0x0003: OP_HALT flags=0x00, dst=R0, payload=0x00000000 ; Execution complete ``` --- ## 2. Inside `ImpulseVM`: Registers, JIT & Parallelism Once emitted as fixed 8-byte `impOps` instructions (`opcode[8] | flags[8] | dst_reg[16] | payload[32]`), the program executes on **`ImpulseVM`**: ### 2.1 640-Byte Cache-Aligned Register Frame (`R0`..`R63`) Inspired by Lua 5+ and LuaJIT, `ImpulseVM` is a **register-based virtual machine** rather than a stack machine. Source and destination registers (`R0`..`R63`) are encoded directly in each 64-bit instruction word, eliminating `PUSH`/`POP` traffic and keeping the entire VM execution state (`impulse_vm_state_t`) inside a single **640-byte frame (10 CPU cache lines)** that stays resident in L1 cache. ### 2.2 Pure Java 25 `MethodHandle` JIT Combinators In the Pure Java 25 engine (`impulse-graph-java`), queries do not sit inside a slow bytecode `switch` loop when evaluating per-edge or per-node filter/projection shaders (`OP_CSR_WALK_STREAM`, `OP_CSC_WALK_STREAM`): * `ImpulseMethodHandleCompiler` and `ShaderCompiler` translate `impOps` instructions and CEL predicates into composable trees of `java.lang.invoke.MethodHandle` combinators (`MethodHandles.insertArguments`, `foldArguments`, `guardWithTest`). * The JVM's **C2 JIT compiler** constant-folds the register offsets and inlines the entire chain of shader operations into a single contiguous block of native machine code with **zero virtual method or interpreter dispatch overhead**. * Two-stage AST optimization and `MethodHandle` JIT tree generation complete in microsecond latencies on modern server hardware with zero runtime bytecode switch interpretation. ### 2.3 Single-Threaded (High-QPS) vs. Multi-Threaded (Batch Analytics) Execution `ImpulseVM` supports two complementary concurrency modes depending on your workload: 1. **Inter-Query Concurrency (Default for Microservices & APIs)**: * Each query executes single-threaded (`threads = 1`) in its own isolated 640-byte register frame and caller buffer over the shared `mmap` snapshot. * Because `threads == 1` is checked once outside the inner opcode loop, the VM executes non-atomic bitset writes (`w_dst |= mask`), avoiding hardware `LOCK` prefix overhead while allowing thousands of concurrent gRPC/HTTP requests to scale linearly across all CPU cores. 2. **Intra-Instruction Parallelism (For Massive Batch Analytics & GNNs)**: * For analytical workloads over multi-billion-edge graphs (PageRank, Connected Components, full-graph BFS), configuring `OP_SET_MAX_DOP` (`0x75`) or the `IMPULSE_MAX_DOP` environment variable parallelizes individual `impOps` kernels across cores using OpenMP (`#pragma omp parallel for`) in C++20 and parallel vector partitions in Java 25. --- ## Next Steps * **[Mathematical, Categorical & GraphBLAS Foundations](../academic.md)**: Formal semiring algebra, Grothendieck fibrations, $1:1 / 1:N / N:1$ multiplicity proofs, and the CSR/CSC/COO analytical cost model. * **[Research Literature & Design Lineage](../academic/literature-and-influences.md)**: Peer-reviewed papers behind register VMs, partial-evaluation JITs, direction-optimizing BFS, Afforest, and DiskANN/Vamana. * **[ImpulseVM & `impOps` ISA Specification](../reference/spec/vm-specification.md)**: Normative bytecode instruction set reference (`0x00`..`0xCB`). ================================================================================ FILE: docs/academic.md | URL: https://www.impulsegraph.org/academic/ ================================================================================ # Mathematical, Categorical & GraphBLAS Foundations This page formalizes the mathematical foundation of the **Impulse Graph Engine** query and execution model—connecting **Semiring-Weighted Kleisli Algebras**, **Grothendieck Fibrations**, **GraphBLAS Sparse Linear Algebra**, and **Substructural Linear Types** directly to physical `.imps` memory layouts and `ImpulseVM` bytecode optimizations. For the peer-reviewed computer science papers behind each subsystem, see **[Research Literature, Annotated Bibliography & Design Lineage](academic/literature-and-influences.md)**. --- ## 1. The Unifying Systems & Algebraic Thesis Traditional relational and property-graph databases optimize under **runtime uncertainty**: because tables and adjacency lists mutate concurrently in place, the query planner relies on sampled cardinality estimates and evaluates multi-hop traversals as **multiset (bag) joins** that dynamically allocate intermediate tuples on the heap. Impulse Graph rests on the opposite structural premise: !!! important "Core Algebraic Thesis" **An immutable, schema-typed binary graph snapshot (`.imps`) with exact catalog cardinalities ($N_d$), degree bounds, and relational multiplicity invariants ($1:1, 1:N, N:1$) transforms graph query execution from runtime bag-join heuristics into a statically verifiable Kleisli semiring algebra—eliminating dynamic heap allocation, intermediate path explosion, and redundant synchronization.** --- ## 2. Semiring-Weighted Set Monad ($\mathcal{W}_R$) vs. Multiset Bag Monad ($\mathcal{M}$) ### 2.1 Why Bag-Based Path Engines Explode Relational SQL joins, standard Cypher, and Gremlin evaluate traversals in the **Multiset (Bag) Monad** $\mathcal{M}(X) = X \to \mathbb{N}$, whose monadic flatten $\mu_{\mathcal{M}}$ preserves duplicate path multiplicities: $$\mu_{\mathcal{M}}(F)(x) = \sum_{f \in \mathcal{M}(X)} F(f) \cdot f(x)$$ If a destination node $d$ is reachable via $k$ distinct paths of length $m$, a bag-based engine materializes $k$ intermediate path tuples. On scale-free graphs with average hub out-degree $\hat{d}$, intermediate state grows as $O(\hat{d}^m)$ ("path explosion"), requiring resizing hash tables (`DISTINCT`) and per-hop heap allocations. ### 2.2 The Semiring-Weighted Distribution Monad Impulse Graph evaluates traversals in the **Semiring-Weighted Set Monad** $\mathcal{W}_R(X) = X \to R$ over a semiring $(R, \oplus, \otimes, \mathbf{0}, \mathbf{1})$: * **Unit ($\eta$)**: Embeds a seed node $x \in \mathcal{V}_D$ as a Dirac basis indicator vector $\eta(x)(y) = \mathbf{1}$ if $y = x$, else $\mathbf{0}$. * **Monadic Flatten ($\mu$)**: Collapses nested weighted frontiers at every hop using semiring addition ($\oplus$) and multiplication ($\otimes$): $$\mu(F)(y) = \bigoplus_{f \in \mathcal{W}_R(X)} F(f) \otimes f(y)$$ ```text Traditional Bag Engines (SQL / Cypher) Impulse Graph Engine (.imps) ────────────────────────────────────── ──────────────────────────── • Multiset (Bag) Monad: M(X) = X → ℕ • Semiring-Weighted Set: W_R(X) = X → R • Frontier cardinality: O(d^m) [Path Explosion] • Frontier Bound: |S| ≤ |V_target| = N_Dst • Explicit DISTINCT hash-table deduplication • Automatic Monoidal Fold (⊕) at every hop • Dynamic heap allocations per path tuple • Pre-allocated off-heap arrays & BitSets ``` ### 2.3 The Frontier Bounding Invariant Because every domain $D$ in an `.imps` snapshot possesses an independent, contiguous dense integer space $\mathcal{V}_D = \{0, 1, \dots, N_D - 1\}$ and converging paths fold immediately by target dense ID, intermediate frontier cardinality is strictly bounded above by target domain cardinality: $$\forall \tau: \mathcal{V}_{\text{Src}} \to \mathcal{V}_{\text{Dst}}, \quad |\tau(\mathcal{S}_{\text{Src}})| \le |\mathcal{V}_{\text{Dst}}| = N_{\text{Dst}}$$ Consequently, exponential path explosion is impossible by construction, and the exact scratch and result buffer byte size (`impulse_stmt_buffer_size`) is known statically at `prepare` time before execution begins. ### 2.4 Kleisli Composition $\equiv$ GraphBLAS Matrix Multiplication In the **Kleisli Category** $\mathbf{Kl}(\mathcal{W}_R)$, objects are typed node domains $\mathcal{V}_A, \mathcal{V}_B$ and morphisms are transition kernels $f: \mathcal{V}_A \to \mathcal{W}_R(\mathcal{V}_B)$. Composing two hops $f: \mathcal{V}_A \to \mathcal{W}_R(\mathcal{V}_B)$ and $g: \mathcal{V}_B \to \mathcal{W}_R(\mathcal{V}_C)$ yields: $$(g \odot f)(a)(c) = (f(a) \gg= g)(c) = \bigoplus_{b \in \mathcal{V}_B} f(a)(b) \otimes g(b)(c)$$ Kleisli composition $g \odot f$ is algebraically identical to **GraphBLAS sparse matrix-matrix multiplication** ($\mathbf{A}_{R_1} \otimes_R \mathbf{A}_{R_2}$), and monadic bind ($\mathbf{v} \gg= f$) is sparse **vector-matrix multiplication** ($\mathbf{v}^T \otimes_R \mathbf{A}_R$, executed by `OP_VXM` / `OP_MXV`): | Graph Workload | Frontier State $\mathbf{v}$ | Semiring $(R, \oplus, \otimes, \mathbf{0}, \mathbf{1})$ | Impulse Transition $\phi$ & Monoid $\oplus$ | | :--- | :--- | :--- | :--- | | **Boolean Reachability / ReBAC** | `OffHeapBitSet` ($\lceil N_d/64 \rceil$ words) | $(\mathbb{B}, \lor, \land, \text{false}, \text{true})$ | $\phi = \text{true}, \quad \oplus = \lor$ (Bitwise `OR`) | | **Batched / $N-1$ Multi-Lane ($W \le 64$)** | `TYPE_LANE_FRONTIER` ($N_d \times W$-bit words) | $(\mathbb{B}^W, \lor_W, \land_W, \mathbf{0}_W, \mathbf{1}_W)$ | Word-parallel bitwise `OR` & edge mask `AND` (`0xC0`..`0xC9`) | | **Shortest Path (BFS / Min-Plus)** | Distance vector (`float32`/`int64`) | $(\mathbb{R}_{\ge 0} \cup \{\infty\}, \min, +, \infty, 0)$ | $\phi = \sigma_s + e.\text{weight}, \quad \oplus = \min$ | | **Widest Path / Bottleneck Capacity** | Capacity vector (`float64`) | $(\mathbb{R}_{\ge 0} \cup \{\infty\}, \max, \min, 0, \infty)$ | $\phi = \min(\sigma_s, e.\text{cap}), \quad \oplus = \max$ | | **PageRank / Financial Exposure** | Score vector (`float64`) | $(\mathbb{R}, +, \times, 0, 1)$ | $\phi = \sigma_s \times e.\text{weight}, \quad \oplus = +$ (`SUM`) | | **Transitive Datalog Closure ($\tau^*$)** | BitSet / state vector | Idempotent Kleene Algebra ($\sigma \oplus \sigma = \sigma$) | Least fixed point $\mu X.\; (\mathcal{S}_0 \oplus \tau(X))$ (`repeatUntilStable`) | ### 2.5 Expressiveness Boundary: Set Algebra vs. ISO GQL Path Modes & Cyclic Joins Stating exact expressiveness boundaries clarifies how Impulse relates to ISO/IEC 39075 **GQL** and **SQL:2023 (SQL/PGQ)**: 1. **Reachability, Aggregation & Fixed Points (In-Algebra, $O(N_d)$ Space)**: Any query whose observable output depends on target node reachability, aggregated path weights over a semiring, bounded-hop neighborhoods, or monotonic Datalog recursion lowers directly into $\mathbf{Kl}(\mathcal{W}_R)$ with zero dynamic allocation. 2. **Explicit Path-History Enumeration (`TRAIL` / `ACYCLIC` Simple Paths)**: Queries that must enumerate every distinct simple path $p = (v_0, e_1, v_1, \dots, v_k)$ without repeated vertices require per-path history state in $\mathcal{M}(\mathcal{V}^*)$ rather than node-indexed state in $\mathcal{W}_R(\mathcal{V})$. Such path-bag queries cannot be evaluated in fixed $O(N_d)$ frontier memory without truncation or external path materialization. 3. **Cyclic Motif & Triangle Queries (Binary Joins vs. Worst-Case Optimal Joins)**: Sequential binary Kleisli steps evaluate acyclic chains and trees optimally in $O(|\text{active edges}|)$. On cyclic patterns such as triangle listing $A(x, y) \land B(y, z) \land C(x, z)$, pure binary join sequences can incur $O(m^{3/2})$ intermediate work compared to $O(m^{3/2})$-optimal multi-way **Worst-Case Optimal Join (WCOJ)** intersection (Ngo et al., PODS '12). Because `.imps` sorts CSR target slices monotonically per source row, cyclic closures intersect sorted neighbor lists directly via bitset/galloping set intersection (`OP_BITSET_AND`). --- ## 3. Property Graphs as Grothendieck Fibrations & Functional Optics Pure GraphBLAS engines represent graphs as homogeneous scalar matrices $\mathbf{A} \in R^{N \times N}$, which creates friction on enterprise **labeled property graphs** containing dozens of heterogeneous node/edge columns (strings, timestamps, nullable numerics, `[N, D]` float32 embeddings) and dynamic filter predicates. ### 3.1 Separation of Base Topology and Attribute Sheaves Category theory resolves this cleanly by modeling a typed property graph as a **Grothendieck Fibration** $\mathcal{P}: \mathbf{E} \to \mathbf{B}$: * **Base Category $\mathbf{B}$ (Pure Topology)**: Objects are dense node ID spaces $\mathcal{V}_D = \{0 \dots N_D - 1\}$; generating morphisms are directed relations $\mathcal{E}_R: \mathcal{V}_{\text{Src}} \to \mathcal{V}_{\text{Dst}}$ stored physically as contiguous 128-byte-aligned **CSR (`row_offsets`, `col_targets`)** and **CSC (`csc_offsets`, `csc_sources`)** integer arrays. * **Attribute Fibers $\mathcal{P}^{-1}(v), \mathcal{P}^{-1}(e)$ (Columnar Sheaves)**: Each node $v \in \mathcal{V}_D$ and edge index $e \in \{0 \dots M_R - 1\}$ carries a typed attribute record stored physically in separate **Structure-of-Arrays (SoA)** columns and Arrow-compatible validity bitmaps. Traversals navigate the base category $\mathbf{B}$ at integer cache-line speed and project into attribute fibers $\mathbf{E}$ only when a filter or projection demands a specific column (**late materialization**). ### 3.2 Zero-Copy Functional Optics over `mmap` Segments Attribute operations in `ImpScheme` and Google CEL lower directly into zero-allocation **Functional Optics**: * **Indexed Lenses ($L: S \to A$) $\to$ SoA Pointer Arithmetic**: Reading `node.age` or `edge.amount` compiles to a direct `MemorySegment` / C-pointer base-plus-index load (`base_ptr + idx * sizeof(T)`), touching only the single requested column's cache lines. * **Prisms ($P: S \to \mathrm{Option}\langle A \rangle$) $\to$ Zone-Map Partition Skipping**: Section 2 `[min, max]` attribute synopses act as prisms in `ZoneMapPruningPass`; if a predicate range `[low, high]` is disjoint from `[min, max]`, the entire relation or block short-circuits to $\mathbf{0}$ without scanning edges. * **Guarded Kleisli Arrows $\to$ Functorial Predicate Pushdown**: Filtering at a target domain satisfies the pullback identity: $$\mathrm{filter}(p) \circ \mathrm{walk}(R) = \mathrm{walk}(R \vert_p)$$ `FilterPushdownPass` fuses target and edge CEL predicates directly into the inner CSR/CSC neighbor loop (`OP_CSR_WALK_STREAM` / SIMD vector mask), discarding non-matching edges before state writeback. --- ## 4. Multiplicity-Driven Bytecode Simplification & Deforestation Because an `.imps` snapshot is immutable, its Section 2 catalog records exact out-degree and in-degree bounds for every relation. The Stage 2 compiler exploits **relational multiplicity** to eliminate runtime synchronization and intermediate buffers that mutable graph engines must execute unconditionally: | Multiplicity Class | Categorical / Degree Invariant | Matrix Structure | Compiler & `ImpulseVM` Optimization | | :--- | :--- | :--- | :--- | | **Injective ($1:N$)** | Monic inbound fiber: $\forall d,\; |\pi_2^{-1}(d)| \le 1$ (e.g., `Order -> LineItem`) | At most one `1` per column | **Monoid & Atomic Elimination (`InjectiveDeduplicationBypassPass`)**: Two active sources can never collide on the same target $d$. The monoid fold $\bigoplus_{i=1}^1 x = x$ degenerates to a direct unsynchronized store. | | **Functional ($N:1$)** | $\forall s,\; \text{deg}^+(s) \le 1$ (e.g., `Account -> PrimaryOwner`) | At most one `1` per row | **Bounded-Degree Walk & Deforestation**: Guarantees at most one outgoing neighbor per active source; enables register-resident 2-hop fusion (`OP_CSR_WALK_2HOP`). | | **Bijective ($1:1$)** | Isomorphism: $\text{deg}^+(s) \le 1 \land \text{deg}^-(d) \le 1$ | Partial permutation matrix $\mathbf{P}$ | **Distributivity over $\cap$ & Lossless Inverse**: $\tau(A \cap B) = \tau(A) \cap \tau(B)$ and $\tau^{-1}(\tau(\mathcal{S})) = \mathcal{S}$, allowing algebraic cancellation of round-trip hops. | | **General ($M:N$)** | Unbounded $\text{deg}^+(s), \text{deg}^-(d)$ | General sparse CSR / CSC matrix $\mathbf{A}$ | Adaptive Push/Pull selection (`DirectionSelectionPass`) with full SIMD scan and monoidal reduction $\bigoplus$. | ### Wadler Deforestation Across Multi-Hop Chains Applying Philip Wadler's deforestation theorem ($\mathrm{map}(f) \circ \mathrm{map}(g) = \mathrm{map}(f \circ g)$) to low-multiplicity relation pairs $R_1: \mathcal{V}_A \to \mathcal{V}_B$ and $R_2: \mathcal{V}_B \to \mathcal{V}_C$, `KernelFusionPass` emits `OP_CSR_WALK_2HOP` when intermediate fan-out satisfies `OptimizerConfig` multiplicity bounds—streaming from $\mathcal{V}_A$ through $\mathcal{V}_B$ into $\mathcal{V}_C$ in CPU registers without allocating or scanning an intermediate $\mathcal{V}_B$ bitset. --- ## 5. Algebraic Subtleties: Monoid Laws, Lexicographical Asymmetry & IEEE-754 Parallelizing or reordering reductions requires strict adherence to algebraic laws: | Algebraic Property | Axiom | Compiler / VM Capability Unlocked | Consequence if Violated | | :--- | :--- | :--- | :--- | | **Associativity** | $(a \oplus b) \oplus c = a \oplus (b \oplus c)$ | Arbitrary SIMD lane trees and thread chunking. | Results vary with SIMD width or thread count. | | **Commutativity** | $a \oplus b = b \oplus a$ | Out-of-order parallel target accumulation. | Race-dependent outputs under multi-threaded push. | | **Idempotency** | $a \oplus a = a$ | CSC Pull early-exit on first active parent; chaotic lock-free fixed points. | Overcounting when duplicate paths converge (e.g., `+`). | | **Zero Annihilation** | $a \otimes \mathbf{0} = \mathbf{0} = \mathbf{0} \otimes a$ | Skipping inactive source nodes ($v_s = \mathbf{0}$) in sparse CSR scans. | Incorrect baseline values on unvisited nodes. | ### 5.1 Non-Commutativity of Lexicographical Product Monoids While a direct product of commutative monoids $(\Sigma_1 \times \Sigma_2, \oplus_1 \times \oplus_2)$ remains commutative, prioritized tie-breaking reducers such as `ArgMin(distance, node_id)` form a **lexicographical product**: $$\langle d_1, u_1 \rangle \oplus_{\text{lex}} \langle d_2, u_2 \rangle = \begin{cases} \langle d_1, u_1 \rangle & \text{if } d_1 < d_2 \\ \langle d_2, u_2 \rangle & \text{if } d_2 < d_1 \\ \langle d_1, \min(u_1, u_2) \rangle & \text{if } d_1 = d_2 \end{cases}$$ Here $\oplus_{\text{lex}}$ is associative and commutative when tie-broken by $\min(u_1, u_2)$, **but switching primary vs. secondary projection coordinates is asymmetric**. Optimization passes never commute projection order across compound tuple reducers. ### 5.2 IEEE-754 Floating-Point Non-Associativity & Kleene 3VL Over IEEE-754 `float32`/`float64`, floating-point addition $(a \oplus_{\text{fp}} b)$ is commutative but **not strictly associative** due to rounding ($(10^{20} + (-10^{20})) + 1.0 \neq 10^{20} + (-10^{20} + 1.0)$). Consequently: * Boolean $(\mathbb{B}, \lor, \land)$, 64-lane bit-sliced $(\mathbb{B}^W, \lor_W, \land_W)$, integer modular arithmetic, and ordered $(\min, \max)$ reductions are **100% bitwise deterministic** across single-threaded and multi-threaded schedules. * Floating-point `SUM` (`OP_MXV` / PageRank) guarantees bitwise cross-engine parity (`ICTX` v1) in deterministic execution mode (`threads = 1`), with canonical IEEE-754 `NaN`, `-0.0`, and **Kleene 3-valued logic (`TRUE`, `FALSE`, `NULL`)** semantics enforced identically across C++, Java 25, Rust, and the OCaml oracle. --- ## 6. Fixed-Point Convergence, Bit-Sliced Algebras & Direction Optimization ### 6.1 Least Fixed Points & Idempotent Chaotic Relaxation Recursive `ImpLog` Datalog rules and `repeatUntilStable` traversals compute the Tarski **least fixed point** over the finite lattice of domain frontiers: $$\mathcal{S}^* = \mathrm{lfp}\left(\lambda X.\; \mathcal{S}_0 \oplus \tau(X)\right)$$ When $\oplus$ is **idempotent** ($a \oplus a = a$, e.g., Boolean reachability $\lor$ or tropical shortest path $\min$) and $\tau$ distributes over $\oplus$: 1. **Semi-Naive Delta Tracking**: Only newly discovered frontier elements $\Delta \mathcal{S}^{(k)} = \mathcal{S}^{(k)} \setminus \mathcal{S}^{(k-1)}$ need to be expanded on iteration $k + 1$. 2. **Chaotic Asynchronous Convergence**: Under idempotent updates, concurrent worker threads can relax target states without per-iteration barriers while still converging to the unique least fixed point $\mathcal{S}^*$. Non-idempotent semirings ($+/\times$) preserve strict Bulk Synchronous Parallel (BSP) step boundaries so each path of length $k$ is accumulated exactly once. ### 6.2 Multi-Lane Bit-Sliced Semirings ($\mathbb{B}^W$, `0xC0`..`0xC9`) Graph traversal is memory-bandwidth bound: fetching `row_offsets[u]` and `col_targets[e]` from DRAM dominates arithmetic. By lifting the scalar Boolean semiring $\mathbb{B}$ to the $W$-fold product Boolean algebra $\mathbb{B}^W$ ($W \in \{8, 16, 32, 64\}$, `TYPE_LANE_FRONTIER = 0x10`): * Each node $u$ carries a $W$-bit lane word $L[u] \in \{0, 1\}^W$. * A single CSR neighbor scan propagates **up to 64 independent seed queries or 64 counterfactual $N-1$ edge-outage scenarios** (`OP_LANE_SET_EDGE_MASK`) per memory read (`L_next[v] |= (L_curr[u] & edge_mask[e])`). * Consensus / bridge discovery across $K$ semantic vector anchors (`OP_LANE_FILTER_QUORUM`, `0xC6`) reduces to hardware population count: $\mathrm{popcount}(L[v]) \ge q$. ### 6.3 Analytical Cost Model: CSR Push vs. CSC Pull vs. Linear Scan Given source cardinality $n_{\text{src}}$, target cardinality $n_{\text{dst}}$, edge count $m$, and active source frontier cardinality $s = |\mathcal{S}_{\text{Src}}|$: ```text Active Source Frontier Density (s / n_src) 0% 5% – 15% 60%+ 100% ├─────────────────────────────┼────────────────────────────────┼────────────────────────┤ CSR Push (OP_CSR_WALK) CSC Pull (OP_CSC_WALK) Linear BitSet / Stream • Work: O(s · d_out) • Work: O(n_dst) w/ early exit • Sequential SIMD scan • Sparse seed frontiers • Zero target write conflicts • Full-domain analytics ``` * **CSR Push (`OP_CSR_WALK`, $s / n_{\text{src}} < 5\%$)**: Reads only outgoing slices of the $s$ active sources ($O(s \cdot \hat{d}_{\text{out}})$). * **CSC Pull (`OP_CSC_WALK`, $5\% \le s / n_{\text{src}} \le 60\%$, idempotent $\oplus$)**: Iterates sequentially over target nodes $d \in \mathcal{V}_{\text{Dst}}$, writing contiguously with zero scatter-write cache misses or atomic contention, and **early-exits** row $d$ upon encountering the first active parent in `csc_sources`. --- ## 7. GNN Message Passing & Substructural Linear Memory Typing ### 7.1 Equivalence with Message Passing Neural Networks (MPNN) A Graph Neural Network layer (Gilmer et al., ICML '17) updates node representations $\mathbf{h}_v^{(\ell)} \in \mathbb{R}^D$ via: $$\mathbf{m}_v^{(\ell+1)} = \bigoplus_{u \in \mathcal{N}(v)} \phi^{(\ell)}\!\left(\mathbf{h}_u^{(\ell)}, \mathbf{h}_v^{(\ell)}, \mathbf{e}_{uv}\right), \qquad \mathbf{h}_v^{(\ell+1)} = \psi^{(\ell)}\!\left(\mathbf{h}_v^{(\ell)}, \mathbf{m}_v^{(\ell+1)}\right)$$ The aggregation step $\mathbf{m}_v^{(\ell+1)}$ is structurally identical to Impulse's Kleisli fiber fold (§2.4) over the vector space $(\mathbb{R}^D, \oplus)$ where $\oplus \in \{\mathrm{sum}, \mathrm{mean}, \mathrm{max}\}$. Storing `[N, D]` feature tensors as 128-byte-aligned SoA columns inside `.imps` allows PyTorch (`impulse-gnn`) to execute neighborhood sampling (`sample_neighbors`) and `torch.from_numpy` / `from_dlpack` tensor slicing directly over shared `mmap` pages without Python heap copies. ### 7.2 Girard's Linear Logic & Zero-Allocation Register Reuse Impulse's memory model corresponds directly to **Substructural (Linear) Type Theory** (Girard, 1987): * **Exponential Modality ($!\mathcal{G}$)**: An immutable `.imps` snapshot is typed as $!\mathcal{G}$—a read-only resource mapped into clean OS page-cache pages that can be shared across unlimited concurrent threads and processes with zero locks or copy-on-write duplication. * **Linear Frontier Buffers ($S_{\text{Src}} \multimap S_{\text{Dst}}$)**: Per-query scratch frontiers bound to VM registers (`R0`..`R63`) are linear resources consumed and recycled across non-overlapping liveness intervals by `RegisterAllocationPass`, guaranteeing **zero dynamic heap allocations (`malloc` / `new`)** in the hot execution loop. --- ## 8. Cross-Discipline Correspondence Glossary | Category Theory / PL Concept | Sparse Linear Algebra (GraphBLAS) | Impulse Graph Physical Realization | | :--- | :--- | :--- | | **Object $D \in \mathrm{Ob}(\mathbf{C}_{\text{Schema}})$** | Vector module $R^{N_D}$ | Node domain with dense IDs $0 \dots N_D - 1$ (`uint16`/`32`/`64`) | | **Morphism $R: A \to B$** | Sparse matrix $\mathbf{A}_R \in R^{N_A \times N_B}$ | 128B-aligned CSR (`A`) and CSC (`A^T`) segments | | **Kleisli Bind ($\mathbf{v} \gg= f$)** | Vector-matrix multiply ($\mathbf{v}^T \otimes_R \mathbf{A}_R$) | `OP_CSR_WALK`, `OP_CSC_WALK`, `OP_VXM` | | **$W$-Fold Boolean Algebra ($\mathbb{B}^W$)** | Bit-packed SpMM ($\mathbf{A} \otimes \mathbf{B}_{N \times W}$) | `TYPE_LANE_FRONTIER` (`0xC0`..`0xC9`, 8/16/32/64 lanes) | | **Grothendieck Fibration ($\mathcal{P}: \mathbf{E} \to \mathbf{B}$)** | Topology separated from attribute tensors | Disjoint CSR/CSC sections vs. SoA attribute columns | | **Functional Lens ($L: S \to A$)** | Column vector projection | Late SoA offset load on surviving frontier IDs | | **Functional Prism ($P: S \to \mathrm{Opt}\langle A \rangle$)** | Block sparsity mask | Section 2 `[min, max]` Zone-Map pruning | | **Monic Inbound Morphism ($1:N$)** | Column-monomial matrix ($\le 1$ entry/col) | `InjectiveDeduplicationBypassPass` (lock/monoid elision) | | **Wadler Deforestation** | Fused two-step implicit SpGEMM | `OP_CSR_WALK_2HOP` register-resident 2-hop walk | | **First Futamura Projection** | Specialized SpMV codegen | Java 25 `MethodHandle` combinator JIT (`ShaderCompiler`) | | **Exponential / Linear Types ($!\mathcal{G}, S \multimap S$)** | Read-only matrix + ping-pong work vectors | Shared `mmap` `.imps` + caller-allocated `R0`..`R63` scratch arena | --- ## Next Steps * **[Research Literature & Design Lineage](academic/literature-and-influences.md)**: Annotated bibliography of 31 peer-reviewed papers across GraphBLAS, register VMs, Vamana DiskANN, `mmap` DBMS storage theory, Datalog, and RCU concurrency. * **[Compiler Pipeline & ImpulseVM](concepts/compiler-architecture.md)**: How Stage 1 and Stage 2 passes lower `ImpScheme` into 64-bit `impOps` bytecode. * **[Data-Oriented Design](concepts/data-oriented-design.md)**: Cache-line packing, SIMD vectorization, and off-heap memory layout. ================================================================================ FILE: docs/academic/literature-and-influences.md | URL: https://www.impulsegraph.org/academic/literature-and-influences/ ================================================================================ # Research Literature, Annotated Bibliography & Design Lineage **Impulse Graph Engine** synthesizes four decades of peer-reviewed research across **sparse linear algebra**, **shared-memory HPC graph algorithms**, **virtual machine architecture**, **columnar database storage**, **disk-aligned vector search**, and **programming language theory**. This page maps each architectural decision in `.imps`, `ImpulseVM`, and the `ImpScheme` compiler back to the foundational papers that motivated or bounded its design, distinguishes established prior art from Impulse's novel contributions, and examines three core systems design trade-offs. --- ## 1. Cross-Disciplinary Lineage Map ```mermaid flowchart LR P1["Sparse Algebra & GraphBLAS\nKepner '16 • Buluç '11 • Gondran '08"] --> IR["Kleisli Semiring IR\nImpK • ImpLog • ImpScheme"] P2["HPC Graph Traversal\nBeamer '12 • Shun '13 • Sutton '18 • Then '14"] --> KRN["Direction-Opt & Multi-Lane\nOP_CSR/CSC_WALK • OP_CC_AFFOREST\nTYPE_LANE_FRONTIER (0xC0..0xC9)"] P3["Register VMs & Partial Eval\nIerusalimschy '05 • Shi '08 • Futamura '71"] --> VM["64-Register ImpulseVM\n640B Frame • MethodHandle JIT"] P4["Disk-Aligned ANN Search\nSubramanya '19 (DiskANN) • Jégou '11"] --> VEC["Section 2.6 Vamana ANN (0x08)\nBQ1/SQ8/FP16 + Rerank (0xCA..0xCB)"] P5["Columnar Storage & RUM\nAthanassoulis '16 • Abadi '08 • Cuthill '69"] --> FMT["128B C-ABI .imps Format\nSoA • Zone Maps • RCM • RCU"] P6["PL Theory, Datalog & WCOJ\nMoggi '91 • Wadler '90 • Girard '87 • Ngo '12"] --> OPT["Multiplicity Simplification\nDeforestation & Linear Buffers"] ``` --- ## 2. Prior Art vs. Novel Synthesis in Impulse Graph Rigorous systems engineering separates well-established algorithms from genuinely new architectural combinations: | Subsystem / Technique | Relationship to Prior Art | Primary Prior Art | What Impulse Adds or Synthesizes | | :--- | :--- | :--- | :--- | | **Multiplicity-Driven Bytecode Simplification** | **Novel Compiler Optimization** | Distant analogue in SQL foreign-key join elimination | Exploits exact immutable `.imps` catalog degree bounds ($1:1, 1:N, N:1$) in `InjectiveDeduplicationBypassPass` and `KernelFusionPass` to statically elide monoid folds, deduplication, and intermediate bitsets. | | **128-Byte C-ABI `.imps` Multi-Domain Snapshot** | **Novel Format Specification** | Apache Arrow IPC (tabular), GAPBS `.sg` (single-matrix) | Unifies independent per-domain dense IDs ($0 \dots N_d-1$, `uint16`/`32`/`64`), CSR/CSC matrices, SoA nullable columns, MPH key indices, and Vamana ANN slabs in one `mmap`-ready file. | | **Fused Vamana ANN $\to$ 64-Lane Quorum Walk** | **Novel Hybrid Graph-Vector ISA** | DiskANN (Subramanya '19) + MS-BFS (Then '14) | `OP_VECTOR_ANN_SEARCH (flags=1)` (`0xCA`) seeds 64 ANN anchors directly into `TYPE_LANE_FRONTIER`, walks $h$ hops in one CSR pass (`0xC3`), filters consensus bridges via `popcount >= q` (`0xC6`), and SIMD-reranks (`0xCB`). | | **Four-Way `ICTX` v1 Deterministic VM Parity** | **Novel Polyglot Verification Architecture** | McKeeman '98; Yang et al. '11 (CSmith) | Enforces bitwise register, PC, flag, and SHA-256 `ICTX` v1 state-hash identity across C++ (`-O3`/`-O0`), Pure Java 25 FFM, and a pure functional OCaml reference oracle across 166 opcodes. | | **Direction-Optimizing Push / Pull** | **Established Algorithm** | Beamer et al. (SC '12); Shun & Blelloch (PPoPP '13) | Adapted to cross-domain heterogeneous relations ($D_{\text{Src}} \to D_{\text{Dst}}$) with compile-time and runtime density switching (`OP_ADAPTIVE_WALK`). | | **Subgraph-Sampled Connected Components** | **Established Algorithm** | Sutton, Ben-Nun & Barak (IPDPS '18 — Afforest) | Implemented directly as a zero-allocation VM instruction (`OP_CC_AFFOREST`) in both C++20 OpenMP and Pure Java 25 FFM. | | **64-Register Bytecode VM + `MethodHandle` JIT** | **Established VM Techniques** | Lua 5.0 (Ierusalimschy '05); Futamura '71; Truffle ('13) | Specializes 64-bit `impOps` and CEL shaders into `java.lang.invoke.MethodHandle` trees compiled by standard OpenJDK C2 without requiring GraalVM or JNI. | | **Lock-Free Snapshot Rotation** | **Established Concurrency Pattern** | McKenney & Slingwine '98 (RCU); Athanassoulis '16 (RUM) | Paired with JDK Foreign Function & Memory `Arena.ofShared()` epoch reference counting (`SnapshotLifecycleManager`) for zero-segfault unmapping. | --- ## 3. Three Core Systems Architecture Debates ### 3.1 Why `mmap` Works in Impulse Despite CIDR '22 (*"Are You Sure You Want to Use MMAP in Your DBMS?"*) In their influential CIDR 2022 paper, **Crotty, Leis, and Pavlo** demonstrated why general-purpose *mutable* transactional DBMSs suffer severe engineering and performance problems when built on OS `mmap` instead of an explicit user-space buffer pool. Every database architect evaluating Impulse rightfully asks how `.imps` avoids those pitfalls: | Mutable DBMS `mmap` Hazard (Crotty, Leis & Pavlo, CIDR '22) | Why Mutable OLTP Engines Fail | Why Read-Only `.imps` Snapshots Are Immune | | :--- | :--- | :--- | | **1. Transactional Safety & Torn Dirty-Page Flush** | The OS kernel can flush dirty `mmap` pages to disk before Write-Ahead Log (WAL) records are persisted, violating ARIES write-ahead invariants. | `.imps` mappings are strictly `MAP_PRIVATE` / `MapMode.READ_ONLY`. **Zero dirty pages and zero in-place writes ever occur**; new snapshots are streamed sequentially to a fresh file and SHA-256 verified before mounting. | | **2. Page-Table Contention & TLB Shootdowns** | Random read-write eviction across thousands of mutable 4KB B-tree pages triggers costly cross-core TLB shootdown IPIs (`munmap` / page reclaim). | Snapshots map contiguous 128B-aligned segments backed by **2MB Transparent Huge Pages (`madvise`)**, cutting TLB entries by `512x`. Clean read-only pages drop without writeback I/O, and old epochs `munmap` only once per Blue/Green swap after active readers drain. | | **3. Synchronous Page-Fault Stalls on Worker Threads** | An unexpected major page fault stalls an OS thread holding internal latches, cascading tail latency across concurrent transactions. | Readers hold **zero latches** on the hot path, and `BinarySnapshotLoader` / `impulse_snapshot_open` issues asynchronous `MADV_WILLNEED` kernel readahead during `startupProbe` warmup before serving traffic. | | **4. `SIGBUS` / Truncation Hazards** | Concurrent file truncation or corruption crashes the process unless wrapped in OS-specific signal handlers. | `SnapshotContractValidator` and CRC-16 / SHA-256 / Ed25519 checks validate file length and section bounds *before* publication, while `SnapshotLifecycleManager` keeps the file descriptor and `Arena.ofShared()` open until active epoch leases reach `0`. | By trading away in-place mutability (the **RUM Conjecture**, Athanassoulis et al., EDBT '16), Impulse captures the $O(1)$ cold-start (`38 µs` C++ / `9.75 ms` Java 25 on 6.04 GB `twitter-2010.imps`) and multi-process page-cache sharing benefits of `mmap` without inheriting its transactional failure modes. ### 3.2 Why Single-Layer Vamana (`DiskANN`) Instead of Multi-Layer HNSW While **HNSW** (Malkov & Yashunin, TPAMI '20) is the standard in-RAM mutable vector index, its variable-height hierarchical skip-list assigns each node a random level $\ell \sim \lfloor -\ln(\mathrm{unif}(0,1)) \cdot m_L \rfloor$, resulting in jagged per-level pointer arrays that fragment contiguous file layouts and complicate SSD/page-cache prefetching. **Vamana / DiskANN** (Jayaram Subramanya et al., NeurIPS '19) instead builds a **single-layer, bounded-out-degree ($R$) directed proximity graph** rooted at the global dataset medoid using two-pass $\alpha$-RNG robust pruning ($\alpha \ge 1.2$). Adding long-range routing edges directly into a single flat layer lets `.imps` Section 2.6 (`IMP_INDEX_VAMANA_ANN = 0x08`) pack the entire index into two **fixed-stride, 128-byte-aligned arrays**: 1. **Adjacency Slab**: $N \times (R + 1) \times \texttt{uint32\_t}$ (zero pointer chasing; neighbor list of node $u$ is a single base-plus-stride slice). 2. **Quantized Routing Slab**: Compact `BQ1` (1-bit), `SQ8` (8-bit), or `FP16` codes scanned in L1/L2 cache during beam search, deferring full `Float32[D]` loads to the final top-$K$ SIMD rerank (`OP_VECTOR_RERANK_DOT`, `0xCB`)—and pairing naturally with `--vamana-locality` BFS node reordering. ### 3.3 Why a 64-Register VM (`ImpulseVM`) Instead of a Stack Bytecode Machine Stack virtual machines (JVM bytecode, WebAssembly, Python CPython, SQLite pre-VDBE register rewrite) push and pop operands implicitly, inflating instruction dispatch counts and memory traffic for binary operations. Following **Lua 5.0** (Ierusalimschy et al., 2005) and **Shi et al.** (ACM TACO 2008)—and echoing SQLite 3's own migration from a stack VDBE to a register VDBE—`ImpulseVM` encodes explicit register operands (`R0`..`R63`) inside fixed 64-bit `impOps` words: * Loop-invariant frontiers, bitsets, and scalar thresholds stay pinned in named registers across fixed-point loops without repeated `LOAD`/`PUSH`/`POP` instructions. * The entire 64-register architectural state (`impulse_vm_state_t`) occupies **640 bytes (10 cache lines)**, staying hot in L1 data cache. * In Pure Java 25, `ImpulseMethodHandleCompiler` applies the **First Futamura Projection** (partial evaluation of an interpreter with respect to a fixed `impOps` program via `MethodHandle` combinators), enabling HotSpot C2 to inline per-edge CEL shaders into register-allocated machine code. --- ## 4. Annotated Bibliography by Research Pillar ### Pillar 1: Sparse Linear Algebra, Semirings & GraphBLAS 1. **Jeremy Kepner, Peter Aaltonen, David Bader, Aydın Buluç, Franz Franchetti, John Gilbert, Dylan Hutchison, Manoj Kumar, Andrew Lumsdaine, Henning Meyerhenke, Scott McMillan, Carl Yang, Marcin Zalewski, and Timothy Mattson.** *"Mathematical Foundations of the GraphBLAS."* IEEE High Performance Extreme Computing Conference (**HPEC**), 2016. - **Core Result**: Formalizes graph algorithms (BFS, shortest paths, centrality, subgraphs) as sparse matrix-vector (`MxV` / `vXM`) and matrix-matrix (`MxM`) operations over algebraic semirings and masks. - **Realization in Impulse**: Direct mathematical basis for the **ImpK (`.impk`)** DSL, `OP_MXV` / `OP_VXM` opcodes, and masked frontier propagation over CSR/CSC segments. 2. **Aydın Buluç and John R. Gilbert.** *"The Combinatorial BLAS: Design, Implementation, and Applications."* The International Journal of High Performance Computing Applications (**IJHPCA**), 25(4):496–509, 2011. - **Core Result**: Demonstrates how customizable semiring `plus` ($\oplus$) and `times` ($\otimes$) combinators decouple parallel sparse matrix communication/storage from domain-specific graph logic. - **Realization in Impulse**: Motivates Impulse's separation of topological walk instructions from customizable monoidal reducers (`Reducer.SUM`, `MIN`, `MAX`, `ANY`). 3. **Mehryar Mohri.** *"Semiring Frameworks and Algorithms for Shortest-Distance Problems."* Journal of Automata, Languages and Combinatorics, 7(3):321–350, 2002; and **Michel Gondran and Michel Minoux**, *Graphs, Dioids and Semirings: New Models and Algorithms*, Springer, 2008. - **Core Result**: Establishes $k$-closedness and idempotency conditions guaranteeing finite convergence of generalized shortest-distance and transitive-closure iterations over dioids/semirings. - **Realization in Impulse**: Governs termination and asynchronous safety rules for `repeatUntilStable` and `ImpLog` fixed-point loops ([Mathematical Foundations §6.1](../academic.md#6-fixed-point-convergence-bit-sliced-algebras-direction-optimization)). --- ### Pillar 2: Direction-Optimizing Traversal, Connectivity & Multi-Source Bit-Slicing 4. **Scott Beamer, Krste Asanović, and David Patterson.** *"Direction-Optimizing Breadth-First Search."* IEEE/ACM International Conference for High Performance Computing, Networking, Storage and Analysis (**SC '12**), 2012; and *"The GAP Benchmark Suite"*, arXiv:1508.03619, 2015. - **Core Result**: Switching dynamically between top-down CSR Push (sparse frontiers) and bottom-up CSC Pull with early exit (dense frontiers) eliminates redundant edge inspections on low-diameter scale-free graphs; GAPBS standardizes empirical graph benchmarking (`twitter-2010`). - **Realization in Impulse**: Implemented in `DirectionSelectionPass` and `OP_ADAPTIVE_WALK` over paired CSR/CSC `.imps` sections, and used as the canonical baseline in [Benchmarks](../benchmarks.md) (`145.00 ms` C++20 / `240.29 ms` Java 25 on `twitter-2010`). 5. **Julian Shun and Guy E. Blelloch.** *"Ligra: A Lightweight Graph Processing Framework for Shared Memory."* ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming (**PPoPP**), 2013. - **Core Result**: Introduces dual sparse-array vs. dense-bitset `vertexSubset` representations with adaptive threshold switching across `EdgeMap` and `VertexMap` operators. - **Realization in Impulse**: Mirrors `ImpulseVM`'s dual `TYPE_NODE_VECTOR` (sparse ID list) and `OffHeapBitSet` (dense $\lceil N_d / 64 \rceil$ words) frontier representations. 6. **Michael Sutton, Tal Ben-Nun, and Amnon Barak.** *"Optimizing Parallel Graph Connectivity Computation via Subgraph Sampling."* IEEE International Parallel and Distributed Processing Symposium (**IPDPS**), 2018 (**Afforest**). - **Core Result**: Sampling just $k = 2$ outgoing edges per vertex discovers the giant connected component in power-law graphs, allowing subsequent full-CSR sweeps to skip >90% of vertices already linked to the dominant root. - **Realization in Impulse**: Directly implemented as `OP_CC_AFFOREST` across both C++20 and Pure Java 25 (`39,681,514` components on `twitter-2010` in `156.73 ms` C++ / `311.23 ms` Graal JIT). 7. **Manuel Then, Moritz Kaufmann, Fernando Chirigati, Tuan-Anh Hoang-Vu, Kien Pham, Alfons Kemper, Thomas Neumann, and Huy T. Vo.** *"The More the Merrier: Efficient Multi-Source Graph Traversal."* Proceedings of the VLDB Endowment (**PVLDB**), 8(4):449–460, 2014 (**MS-BFS**). - **Core Result**: Packs multiple concurrent BFS frontiers into machine bit-width lanes (64/128/256/512 bits) so one CSR adjacency scan advances dozens of traversals simultaneously, turning memory-bound walks into compute-dense bitwise operations. - **Realization in Impulse**: Core inspiration for `v0.10.0` **Multi-Lane Bit-Sliced Frontiers (`TYPE_LANE_FRONTIER = 0x10`, `0xC0`..`0xC9`)**, generalized in Impulse to support edge-outage trip masks (`OP_LANE_SET_EDGE_MASK`) for $N-1$/$N-2$ grid contingency sweeps and multi-anchor quorum filtering (`OP_LANE_FILTER_QUORUM`). 8. **Yunming Zhang, Mengjiao Yang, Riyadh Baghdadi, Shoaib Kamil, Julian Shun, and Saman Amarasinghe.** *"GraphIt: A High-Performance Graph DSL."* Proceedings of the ACM on Programming Languages (**OOPSLA**), 2018. - **Core Result**: Separates declarative graph algorithm specification from physical optimization schedules (direction, parallelization, data layout, kernel fusion). - **Realization in Impulse**: Reflected in Impulse's split between Stage 1 (logical snapshot-agnostic AST rewrites) and Stage 2 (snapshot-bound physical schedule & kernel selection). --- ### Pillar 3: Register Virtual Machines, Threaded Dispatch & Partial-Evaluation JIT 9. **Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes.** *"The Implementation of Lua 5.0."* Journal of Universal Computer Science (**J.UCS**), 11(7):1159–1176, 2005. - **Core Result**: Introduces a mainstream register-based bytecode virtual machine packing opcode and explicit register indices into fixed-width 32-bit words, sharply cutting instruction count per loop iteration compared to stack VMs. - **Realization in Impulse**: Primary inspiration for `ImpulseVM`'s 64-register (`R0`..`R63`) architecture and fixed 64-bit `impOps` instruction format (`opcode[8] | flags[8] | dst[16] | payload[32]`). 10. **Yunhe Shi, Kevin Casey, M. Anton Ertl, and David Gregg.** *"Virtual Machine Showdown: Stack Versus Registers."* ACM Transactions on Architecture and Code Optimization (**TACO**), 4(4), 2008 (extended from **ACM VEE** 2005). - **Core Result**: Demonstrates empirically that register bytecode architectures execute ~45% fewer VM instructions and reduce dispatch overhead, especially when paired with direct/computed-`goto` threading. - **Realization in Impulse**: Guides `impulse_vm.cpp`'s computed-`goto` dispatch loop and register-pinned loop invariants. 11. **Yoshihiko Futamura.** *"Partial Evaluation of Computation Process—An Approach to a Compiler-Compiler."* Systems, Computers, Controls, 2(5):45–50, 1971 (reprinted in *Higher-Order and Symbolic Computation*, 12(4):381–391, 1999); and **Thomas Würthinger, Christian Wimmer, Andreas Wöß, Lukas Stadler, Gilles Duboscq, Christian Humer, Gregor Richards, Doug Simon, and Mario Wolczko**, *"One VM to Rule Them All"*, **ACM Onward!**, 2013. - **Core Result**: Specializing an interpreter with respect to a known target program (the **First Futamura Projection**) produces a compiled native executable without maintaining a separate machine-code backend per CPU ISA. - **Realization in Impulse**: `ImpulseMethodHandleCompiler` and `ShaderCompiler` specialize `impOps` instructions and CEL ASTs into `java.lang.invoke.MethodHandle` combinator trees, letting HotSpot C2 constant-fold the interpreter away on standard JDK 21/25. --- ### Pillar 4: Disk-Aligned Approximate Nearest Neighbor (ANN) & Vector Quantization 12. **Suhas Jayaram Subramanya, Fnu Devvrit, Rohan Kadekodi, Ravishankar Krishnaswamy, and Harsha Vardhan Simhadri.** *"DiskANN: Fast Accurate Billion-Point Nearest Neighbor Search on a Single Node."* Advances in Neural Information Processing Systems (**NeurIPS**), 32, 2019. - **Core Result**: Introduces the single-layer **Vamana** $\alpha$-RNG graph ($\alpha > 1$ long-range pruning from the medoid) paired with compressed in-RAM routing codes and full-precision on-SSD vectors for low-hop, disk-friendly beam search. - **Realization in Impulse**: Directly realized in `.imps` **Section 2.6 `IMP_INDEX_VAMANA_ANN` (`0x08`)**, `OP_VECTOR_ANN_SEARCH` (`0xCA`), and `impulse snapshot optimize --vamana-locality`. 13. **Yu. A. Malkov and D. A. Yashunin.** *"Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs."* IEEE Transactions on Pattern Analysis and Machine Intelligence (**TPAMI**), 42(4):824–836, 2020. - **Core Result**: Establishes logarithmic-scaling navigable small-world proximity graphs for high-recall ANN search. - **Realization in Impulse**: Serves as the architectural baseline motivating Impulse's choice of single-layer fixed-stride Vamana slabs over jagged multi-layer HNSW skip-lists in immutable `.imps` files (§3.2). 14. **Hervé Jégou, Matthijs Douze, and Cordelia Schmid.** *"Product Quantization for Nearest Neighbor Search."* IEEE Transactions on Pattern Analysis and Machine Intelligence (**TPAMI**), 33(1):117–128, 2011. - **Core Result**: Pioneers asymmetric compressed-domain distance estimation during candidate search followed by exact reranking over top candidates. - **Realization in Impulse**: Underpins Impulse's two-stage quantized beam routing (`BQ1` 1-bit hamming, `SQ8` 8-bit scalar, `FP16`) paired with exact SIMD `Float32[D]` reranking (`OP_VECTOR_RERANK_DOT`, `0xCB`). --- ### Pillar 5: Columnar Storage, RUM Conjecture, `mmap` Analysis & Graph Reordering 15. **Manos Athanassoulis, Michael S. Kester, Lukas M. Maas, Radu Stoica, Stratos Idreos, Anastasia Ailamaki, and Mark Callaghan.** *"Designing Access Methods: The RUM Conjecture."* International Conference on Extending Database Technology (**EDBT**), 2016 (and *Communications of the ACM*, 66(4), 2023). - **Core Result**: Any data access method can optimize at most two of **Read overhead**, **Update overhead**, and **Memory/storage overhead**. - **Realization in Impulse**: Explicit architectural justification for `.imps`: by moving **Update** out-of-band (streaming Blue/Green snapshot rebuilds), Impulse simultaneously attains minimal **Read** overhead (contiguous 128B CSR/CSC) and minimal **Memory** overhead (zero B-tree pointers or MVCC headers). 16. **Mike Stonebraker, Daniel J. Abadi et al.** *"C-Store: A Column-Oriented DBMS"*, **VLDB**, 2005; and **Daniel J. Abadi, Samuel R. Madden, and Nabil Hachem**, *"Column-Stores vs. Row-Stores: How Different Are They Really?"*, **ACM SIGMOD**, 2008. - **Core Result**: Proves that **late materialization**—propagating compact position bitmaps/lists through filter stages before fetching projected columns—dramatically outperforms early tuple construction. - **Realization in Impulse**: All node and edge attributes in `.imps` are stored as disjoint SoA columns, materialized only for surviving `OffHeapBitSet` frontier IDs at terminal `collect()` or `RowView` cursor iteration. 17. **Peter A. Boncz, Marcin Zukowski, and Niels Nes.** *"MonetDB/X100: Hyper-Pipelining Query Execution."* Conference on Innovative Data Systems Research (**CIDR**), 2005. - **Core Result**: Replaces Volcano tuple-at-a-time virtual method calls with vectorized array primitives fitting inside CPU L1/L2 caches. - **Realization in Impulse**: Motivates SIMD-vectorized CEL predicate loops (`FloatVector.SPECIES_PREFERRED` in Java 25 and Google Highway in C++20). 18. **Guido Moerkotte.** *"Small Materialized Aggregates: A Light Weight Index Structure for Data Warehousing."* **VLDB**, 1998. - **Core Result**: Introduces lightweight min/max/count synopses (**Zone Maps**) enabling compile-time and scan-time block pruning with negligible storage cost. - **Realization in Impulse**: Section 2 attribute statistics (`min`, `max`, `null_count`) drive `ZoneMapPruningPass` branch elimination. 19. **Andrew Crotty, Viktor Leis, and Andrew Pavlo.** *"Are You Sure You Want to Use MMAP in Your Database Management System?"* Conference on Innovative Data Systems Research (**CIDR**), 2022. - **Core Result**: Catalogs the transactional safety, page-eviction, TLB shootdown, and I/O stall hazards of using `mmap` in mutable read-write DBMSs. - **Realization in Impulse**: Directly informs `.imps` operational safeguards (§3.1): strictly read-only immutable mappings, pre-swap SHA-256 validation, 2MB THP `madvise`, `MADV_WILLNEED` startup warmup, and Kubernetes `cgroups v2` page-cache sizing. 20. **Elizabeth Cuthill and James McKee.** *"Reducing the Bandwidth of Sparse Symmetric Matrices."* Proceedings of the 24th ACM National Conference, 1969; and **Hao Wei, Jeffrey Xu Yu, Can Lu, and Xuemin Lin**, *"Speedup Graph Processing by Graph Ordering"* (**Gorder**), **ACM SIGMOD**, 2016. - **Core Result**: Permuting dense vertex IDs so structurally proximate nodes have numerically proximate IDs dramatically increases L1/L2 cache-line hit rates and bitset word density during CSR walks. - **Realization in Impulse**: Implemented directly in `impulse snapshot optimize --rcm` (Reverse Cuthill-McKee), `--degree-sort`, and `--vamana-locality` (medoid BFS ordering). 21. **Djamal Belazzougui, Fabiano C. Botelho, and Martin Dietzfelbinger.** *"Hash, Displace, and Compress"* (**CHD**), **ESA**, 2009; and **Antoine Limasset, Guillaume Rizk, Rayan Chikhi, and Pierre Peterlongo**, *"Fast and Scalable Minimal Perfect Hashing for Massive Key Sets"* (**BBHash**), **SEA**, 2017. - **Core Result**: Constructs static, collision-free Minimal Perfect Hash Functions (MPHF) mapping $N$ static keys to $\{0 \dots N - 1\}$ in $O(1)$ probes with near-information-theoretic space. - **Realization in Impulse**: Underpins `.imps` Section 2.6 `_domain_index` external key-to-dense-ID resolution (`fromKey(...)`). --- ### Pillar 6: Category Theory, Datalog, Relational Joins & Lock-Free Concurrency 22. **Eugenio Moggi.** *"Notions of Computation and Monads."* Information and Computation, 93(1):55–92, 1991 (preliminary version **IEEE LICS**, 1989); and **Philip Wadler**, *"Deforestation: Transforming Programs to Eliminate Trees"*, Theoretical Computer Science, 73(2):231–248, 1990. - **Core Result**: Models effectful/weighted pipelines via Kleisli composition ($\mathbf{Kl}(M)$) and proves compile-time fusion laws eliminating intermediate data structures. - **Realization in Impulse**: Formalizes Impulse's domain-to-domain fluent traversal model and `OP_CSR_WALK_2HOP` intermediate-frontier elimination. 23. **Jean-Yves Girard.** *"Linear Logic."* Theoretical Computer Science, 50(1):1–101, 1987. - **Core Result**: Distinguishes unrestricted shared truth ($!A$, exponential modality) from single-use linear resources ($A \multimap B$) consumed without garbage collection. - **Realization in Impulse**: Models the split between shared read-only `mmap` snapshots ($!\mathcal{G}$) and linearly recycled VM register scratch buffers (`R0`..`R63`). 24. **Alfred Tarski.** *"A Lattice-Theoretical Fixpoint Theorem and its Applications"*, Pacific Journal of Mathematics, 5(2):285–309, 1955; **Patrick Cousot and Radhia Cousot**, *"Abstract Interpretation: A Unified Lattice Model for Static Analysis of Programs by Construction or Approximation of Fixpoints"*, **ACM POPL**, 1977; and **François Bancilhon**, *"Naive Evaluation of Recursively Defined Relations"*, 1986 (**Semi-Naive Datalog**). - **Core Result**: Guarantees unique least fixed points for monotonic operators over complete lattices and accelerates recursive Datalog rules via delta-frontier propagation. - **Realization in Impulse**: Powers `ImpLog` recursive rule compilation, `ScmFixpoint` (`repeatUntilStable`), and delta-frontier bitset tracking. 25. **Hung Q. Ngo, Ely Porat, Christopher Ré, and Atri Rudra.** *"Worst-Case Optimal Join Algorithms"*, Journal of the ACM (**JACM**), 65(3), 2018 (**ACM PODS** 2012); and **Michael Freitag, Maximilian Bandle, Tobias Schmidt, Alfons Kemper, and Thomas Neumann**, *"Adopting Worst-Case Optimal Joins in Relational Database Systems"*, **PVLDB**, 13(11), 2020. - **Core Result**: Proves binary join plans are asymptotically suboptimal on cyclic graph patterns (triangles, cliques) and achieves AGM-bound optimality ($O(N^{\rho^*})$) via multi-way sorted set intersection. - **Realization in Impulse**: Defines the boundary where linear Kleisli CSR walks hand off to sorted CSR slice / bitset intersection (`OP_BITSET_AND`) on cyclic motifs. 26. **Ruoming Pang, Ramón Cáceres, Mike Burrows, Zhifeng Chen, Pratik Dave, Nathan Germer, Alexander Golynski, Kevin Graney, Nina Kang, Lea Kissner, Jeffrey L. Korn, Abhishek Parmar, Christopher D. Richards, and Mengzhi Wang.** *"Zanzibar: Google's Consistent, Global Authorization System."* **USENIX ATC**, 2019. - **Core Result**: Establishes tuple-based Relationship-Based Access Control (ReBAC) via recursive group/hierarchy set-union and intersection reachability checks at microsecond tail latency. - **Realization in Impulse**: Primary enterprise motivation for `ImpLog` and the `impulse-authz` showcase (`0.026 µs – 0.552 µs` multi-hop ReBAC evaluation in Pure Java 25). 27. **Paul E. McKenney and John D. Slingwine.** *"Read-Copy Update: Using Execution History to Solve Concurrency Problems."* Parallel and Distributed Computing and Systems (**PDCS**), 1998 (**RCU**). - **Core Result**: Enables zero-lock, wait-free concurrent reads alongside updates by publishing new immutable versions via atomic pointer swap and deferring reclamation of old epochs until all pre-existing readers complete. - **Realization in Impulse**: Exact lifecycle mechanism of `SnapshotLifecycleManager` and `SnapshotSwapManager` (`AtomicReference` swap + `LongAdder` epoch reader draining before `Arena.ofShared().close()`). --- ### Pillar 7: Graph Neural Networks & Differential Compiler Verification 28. **Justin Gilmer, Samuel S. Schoenholz, Patrick F. Riley, Oriol Vinyals, and George E. Dahl.** *"Neural Message Passing for Quantum Chemistry"* (**MPNN**), **ICML**, 2017; and **William L. Hamilton, Rex Ying, and Jure Leskovec**, *"Inductive Representation Learning on Large Graphs"* (**GraphSAGE**), **NeurIPS**, 2017. - **Core Result**: Unifies GNNs under neighborhood message aggregation + node update functions and introduces bounded-fanout $k$-hop neighborhood sampling for scalable mini-batch training. - **Realization in Impulse**: Implemented natively in `impulse-gnn` (`sample_neighbors` over `mmap` CSR slices + zero-copy `[N, D]` SoA feature tensors). 29. **William M. McKeeman.** *"Differential Testing for Software"*, Digital Technical Journal, 10(1):100–107, 1998; and **Xuejun Yang, Yang Chen, Eric Eide, and John Regehr**, *"Finding and Understanding Bugs in C Compilers"* (**CSmith**), **ACM PLDI**, 2011. - **Core Result**: Running randomized, grammar/contract-valid programs across independent compiler and VM implementations exposes subtle semantic, optimization, and corner-case bugs without requiring manual test oracles. - **Realization in Impulse**: Directly drives `impulse-verification` (`four_way_validation.py`, `fuzz_vm_contracts.py`, `cross_compiler_parity.py`, and `cli_side_by_side_parity.py`), enforcing bitwise `ICTX` v1 consensus across C++ (`-O3`), C++ (`-O0`), Pure Java 25, and OCaml. --- ## 5. Open Research Problems & Future Directions Several active extensions of the Impulse architecture connect directly to open systems and database research questions: 1. **Direct GPU DMA & Warp-Coalesced SpMV (`cuFile` GPUDirect Storage)**: Because every `.imps` section is 128-byte aligned (matching 32-thread $\times$ 4-byte NVIDIA warp memory transactions), CSR/CSC and `[N, D]` embedding slabs can stream directly from NVMe into GPU HBM via `cuFile` without staging through host CPU RAM. 2. **Cross-Snapshot Federated Morphisms (`OP_REMAP_ID_SPACE`)**: Extending $\mathbf{C}_{\text{Schema}}$ across independently versioned `.imps` snapshots (e.g., a static reference ontology paired with a 5-minute transactional edge snapshot) via zero-copy dense-ID translation morphisms. 3. **Worst-Case Optimal Join (WCOJ) Lowering in `ImpScheme`**: Compiling cyclic `openCypher` and `ImpLog` conjunctive patterns (triangles, 4-cycles) directly into multi-way sorted CSR slice intersections (Leapfrog Triejoin / GenericJoin style). 4. **Probabilistic Sketch Monoids in $\mathbf{Kl}(\mathcal{W}_R)$**: Embedding mergeable approximate sketches (HyperLogLog for distinct neighborhood cardinality, Count-Min / KLL quantile sketches) as fixed-width register monoids for billion-edge approximate graph analytics. 5. **Property-Based & SMT Verification of Custom Monoid Laws**: Statically or fuzz-verifying associativity, commutativity, and idempotency before enabling parallel/chaotic reduction schedules on user-supplied CEL state reducers. --- ## Related Guides * **[Mathematical, Categorical & GraphBLAS Foundations](../academic.md)**: Formal semiring algebra, Grothendieck fibrations, multiplicity proofs, and linear buffer typing. * **[Polyglot Validation & Testing](../contributing/polyglot-validation.md)**: How the four-way differential validation suite and contract fuzzer enforce specification compliance. * **[Why Impulse Graph?](../concepts/why-impulse.md)**: Architectural motivation and empirical latency breakdowns. ================================================================================ FILE: docs/software-modules.md | URL: https://www.impulsegraph.org/software-modules/ ================================================================================ # Software Modules & Repository Map Impulse Graph decouples its **normative binary format and bytecode specification** (`impulse-graph-spec`) from **independent execution runtimes** that evaluate the same `.imps` snapshot files and 64-register `impOps` ISA: 1. **Normative Specification & Test Vectors (`impulse-graph-spec`)**: Layer 0 C-ABI `.imps` binary layout, `.imps.schema.yaml` contract rules, `impOps` opcode catalog, and `.impas` compliance vectors (`tc01`–`tc38`, `vm-impas/`). Zero downstream dependencies. 2. **Pure JVM Runtime (`impulse-graph-java`)**: Java 21 LTS / 25 FFM (`MemorySegment`, `Arena`), Vector API (`jdk.incubator.vector`), and `MethodHandle` JIT combinators—plus Kotlin, Scala 3, and Clojure DSLs. Zero JNI and zero third-party runtime dependencies in the core engine. 3. **Native C++20 / C-ABI Runtime (`impulse-graph-core`)**: C++20 kernel (`libimpulse_graph`, `impulse_graph.h`, `impulse_vm.h`) with Highway SIMD and OpenMP. Powers C/C++, Rust (`impulse-rust`), Python, Go, .NET (P/Invoke), and Node.js SDKs. 4. **Formal Reference Oracle (`impulse-ocaml`)**: Pure functional OCaml implementation of `ImpulseVM` and `ICTX` v1 deterministic state hashing. All runtimes execute the same `ImpulseVM` register ISA (`R0`..`R63`, `impOps`) and are verified for bitwise parity in [Polyglot Validation & Testing](contributing/polyglot-validation.md). Because `.imps` and `impOps` contain no engine-specific object headers, future standalone runtimes (such as pure managed `.NET` or `WebAssembly`) can implement the specification directly. --- ## 1. Core Components * **`ImpulseGraphSnapshot`**: Read-only, thread-safe interface over a memory-mapped `.imps` file ([Binary Snapshot Spec](reference/spec/format-specification.md)). * **`ImpulseVM`**: Register-based bytecode VM executing `impOps` instructions (`OP_CSR_WALK`, `OP_CSC_WALK`, `OP_MXV`, `OP_VXM`, `OP_CC_AFFOREST`, `OP_COLLECT_BITSET`). * **`ImpulseGraphQuery` & `ImpulseStatement`**: Compiles fluent traversals, openCypher, CEL filters, ImpLog, and ImpK into `impOps` bytecode and prepared statements. * **`SnapshotBuilder` & `SnapshotWriter`**: Single-pass streaming `.imps` writers for local disks and cloud object storage (S3/GCS) with $O(\text{chunk})$ RAM usage. --- ## 2. Repository Workspaces ### Pure JVM Engine & Tooling (`impulse-graph-java`) ```text impulse-graph-java/ ├── impulse-bom/ # Bill of Materials POM aligning all org.impulsegraph versions (v0.11) ├── impulse-spec/ # Format FFM layouts & opcode constants ├── impulse-api/ # Public interfaces (ImpulseGraphSnapshot, DomainView, ImpulseStatement) ├── impulse-storage/ # FFM CSR/CSC loader, secondary indices & lifecycle managers ├── impulse-vm/ # ImpulseVM interpreter, MethodHandle JIT & bytecode emitter ├── impulse-compiler/ # ImpScheme, openCypher & CEL optimizing compiler ├── impulse-builder/ # Streaming .imps snapshot builder ├── impulse-codegen/ # AOT Java domain/traversal code generator from .imps.schema.yaml (v0.11) ├── impulse-maven-plugin/ # Maven build plugin for schema validation & AOT codegen (v0.11) ├── impulse-gradle-plugin/ # Gradle build plugin for schema validation & AOT codegen ├── impulse-cli/ # Pure-Java CLI ('impulse-j') for JVM-only environments (v0.11) ├── impulse-kotlin/ # Kotlin DSL & coroutine extensions ├── impulse-scala/ # Scala 3 DSL extensions ├── impulse-clojure/ # Clojure / S-expression DSL └── spec/ # Pinned impulse-graph-spec submodule ``` *(See the [Java & JVM Ecosystem Hub](ecosystems/java/index.md), [Maven & Build Tooling](ecosystems/java/maven-and-build-tooling.md), and [AOT Code Generation](ecosystems/java/aot-codegen.md).)* ### Native C++20, CLI & Polyglot Workspace (`impulse-graph-core`) ```text impulse-graph-core/ ├── impulse-cpp/ # C++20 kernel, C-ABI headers & ImpulseVM (libimpulse_graph) ├── impulse-rust/ # Rust crate (impulse-graph) ├── impulse-cli/ # Standalone native CLI & compiler suite (impulse / impulse-graph) ├── impulse-python/ # Python bindings (NumPy, SciPy, PyTorch) ├── impulse-dotnet/ # .NET 8+ P/Invoke API (ImpulseGraph) ├── impulse-go/ # Go CGo bindings ├── impulse-node/ # Node.js / TypeScript N-API bindings └── spec/ # Pinned impulse-graph-spec submodule ``` *(See the [Python & PyTorch Hub](ecosystems/python/index.md) and [Native, Rust & Polyglot Hub](ecosystems/native/index.md).)* --- ## 3. Developer CLI Toolchains (`impulse` & `impulse-j`) Impulse Graph provides two CLI distributions that share command parity (verified via `cli_side_by_side_parity.py`): * **Native CLI (`impulse-graph` / `impulse` in `impulse-graph-core/impulse-cli`)**: Zero-JVM native executable for Python, C/C++, Rust, data engineering, and container pipelines (see [Native CLI Reference](ecosystems/native/cli-reference.md) and [CLI Reference](reference/cli.md)). * **Pure-Java CLI (`impulse-j` in `impulse-graph-java/impulse-cli`)**: 100% JVM CLI for enterprise Java environments where native binaries are restricted (see [Pure-Java CLI (`impulse-j`)](ecosystems/java/cli-impulse-j.md)). Core subcommands include: * `compiler assemble` / `disassemble` — `.impas` text ↔ `.impb` binary bytecode. * `compiler compile` — compiles `.impscm`, `.impk`, and `.implog` into `.impas` or `.impb`. * `run` — executes bytecode or DSL scripts against an `.imps` snapshot. * `build` — compiles CSV/TSV/Parquet manifests and `.imps.schema.yaml` contracts into `.imps` files. * `snapshot inspect` / `validate` / `optimize` — header inspection, SHA-256 and 128-byte alignment checks, Reverse Cuthill-McKee (RCM) reordering, and CSC generation. --- ## 4. Organization Repository Sitemap | Repository | Role | | :--- | :--- | | **`impulse-graph-spec`** | Layer 0 `.imps` binary format, `.imps.schema.yaml` spec, `ImpulseVM` ISA, `.impas` assembly spec, and compliance test vectors (`tc01`–`tc38`, `vm-impas/`). | | **`impulse-graph-core`** | C++20 / C-ABI kernel (`impulse-cpp`), Rust crate (`impulse-rust`), native CLI (`impulse-cli`), and FFI SDKs (Python, Go, .NET, Node.js). | | **`impulse-graph-java`** | Pure Java 21/25 FFM engine, VM interpreter/JIT, compiler suite, streaming builder, `impulse-bom`, AOT `impulse-codegen`, `impulse-maven-plugin`, `impulse-j` CLI, and Kotlin/Scala/Clojure DSLs. | | **`impulse-ocaml`** | OCaml reference implementation of `ImpulseVM` and `ICTX` v1 hashing used as a formal parity oracle. | | **`impulse-verification`** | Four-way VM parity harness (`four_way_validation.py`), side-by-side CLI parity suite (`cli_side_by_side_parity.py`), contract fuzzer (`fuzz_vm_contracts.py`), and cross-compiler parity (`cross_compiler_parity.py`). | | **`impulse-benchmarks`** | Reproducible JMH, Google Benchmark, and Python benchmark harnesses. | | **`impulse-website`** | Documentation site (`www.impulsegraph.org`). | | **`impulse-platform`** | Spring Boot gRPC server, Kafka WAL ingestion, GCS/S3 snapshot sync, and RocksDB persistence. | | **`impulse-powergrid`** | Showcase: power grid stability engine and parallel N-1 contingency simulator over MATPOWER PEGASE cases. | | **`impulse-gnn`** | Showcase: PyTorch / PyG `mmap` tensor integration and SIMD neighborhood sampler. | | **`impulse-authz`** | Showcase: Relationship-Based Access Control (ReBAC / Zanzibar) authorization service and benchmarks. | For live package registry status and coordinates (Maven Central, PyPI, crates.io, GitHub Releases), see [Status & Roadmap](status.md) and [Packages & Distribution](reference/packages.md). ================================================================================ FILE: docs/query-api/index.md | URL: https://www.impulsegraph.org/query-api/ ================================================================================ # Querying & DSLs Overview Once an `.imps` snapshot is memory-mapped into your process, **all query interfaces in Impulse Graph compile through the same [ImpScheme $\to$ `impOps` bytecode pipeline](../concepts/compiler-architecture.md)** and execute on `ImpulseVM` with zero hot-loop heap allocations. !!! note "You Do Not Need S-Expressions or Assembly to Use Impulse Graph" The navigation sidebar documents every layer of the compiler stack—including the internal S-expression IR (`ImpScheme`) and register assembly (`ImpAsm`). **95% of application code uses Tier 1 (Fluent / AOT API + CEL) or Tier 2 (openCypher).** --- ## Which Query Interface Should I Use? ```mermaid flowchart LR T1["Tier 1: Application APIs\nAOT Builders & Fluent API\n+ Google CEL Predicates"] --> IR["Tier 4: Compiler IR & ISA\nImpScheme (.impscm)\n──► impOps / ImpAsm (.impas)"] T2["Tier 2: Declarative Queries\nParameterized openCypher\n(ImpulseStatement)"] --> IR T3["Tier 3: Domain DSLs\nImpLog (Datalog / ReBAC)\nImpK (GraphBLAS / Vectors)"] --> IR ``` | Tier | Interface / Language | When to Choose It | Primary Guide | | :--- | :--- | :--- | :--- | | **Tier 1 — Everyday Application Code *(Start Here)*** | **AOT Codegen (`impulse-codegen`) & Fluent Domain API** (`snap.domain(...)`) + **Google CEL** | Default choice for microservices and scripts: IDE auto-complete, multi-hop walks, off-heap bitset algebra, monoidic state projections, fixed-point loops, multi-lane batches, and Vamana ANN search. | **[Fluent Traversal API](fluent-api.md)**, **[State Projections & Loops](advanced-querying.md)**, **[AOT Codegen (Java)](../ecosystems/java/aot-codegen.md)** & **[Google CEL](../dsl/cel.md)** | | **Tier 2 — Declarative Pattern Matching** | **Read-Only openCypher** (`ImpulseStatement` / `impulse_stmt_t`) | Teams familiar with `MATCH (a)-[:REL]->(b) WHERE ... RETURN ...` or C/FFI hosts binding `$param` values into pre-compiled SQLite-style prepared statements. | **[openCypher Guide](../dsl/opencypher.md)** | | **Tier 3 — Specialized Policy & Matrix DSLs** | **ImpLog** (`.implog`) & **ImpK** (`.impk`) | Choose **ImpLog** for recursive Datalog rules and Zanzibar ReBAC policy files; choose **ImpK** for GraphBLAS sparse matrix-vector multiplication (`MxV`), PageRank, and Connected Components. | **[ImpLog (Datalog)](../dsl/implog.md)** & **[ImpK (GraphBLAS)](../dsl/impk.md)** | | **Tier 4 — Compiler IR & Register Assembly *(Optional / Internals)*** | **ImpScheme** (`.impscm`) & **ImpAsm** (`.impas`) | Engine internals and advanced tooling: authoring custom AST macros, inspecting `.toImpAsm()` / `impulse disassemble` output, or writing `ImpulseVM` compliance test vectors. | **[ImpScheme IR](../dsl/impscm.md)** & **[ImpulseVM & ImpAsm Spec](../reference/spec/vm-specification.md)** | *Working in PyTorch or SciPy? You can also mount CSR arrays (`row_offsets`, `col_indices`) and `[N, D]` embedding columns directly as zero-copy `torch.Tensor` / `np.ndarray` views—see **[GNN & Vector Search (Python)](../ecosystems/python/gnn-and-vector-search.md)** and the **[PyTorch & GNN Showcase](../showcase/gnn.md)**.* --- ## 1. Fluent Domain-to-Domain Traversals (Tier 1) Every Fluent query anchors to a starting **Domain** (`snap.domain("User")`), seeds an initial frontier (`fromKey`, `from`, or `all`), walks zero or more directed relations (`.out(...)` / `.in(...)`), and collects the surviving nodes in the target domain: === "Java 25" ```java // 1. Multi-hop traversal with inline CEL filtering List recipientAccounts = snap.domain("User") .fromKey("usr_101") .out("OWNS") .out("TRANSFERRED_TO", "edge.amount >= 1000.0") .toKeyList(); // 2. Unbounded fixed-point reachability (transitive closure) ImpulseBitSet reachableGroups = snap.domain("User") .fromKey("usr_alice") .out("MEMBER_OF") .repeatUntilStable("PARENT_GROUP") .toBitSet(); ``` === "Python" ```python from impulse_graph import Snapshot with Snapshot("banking.imps") as snap: recipient_accounts = ( snap.domain("User") .from_node(101) .out("OWNS") .out("TRANSFERRED_TO") .to_list() ) ``` === "C++20 (`impulse::vm::QueryBuilder`)" ```cpp using namespace impulse::vm; CompiledQuery query = QueryBuilder() .inputNode(0) .walkEdge(/*MEMBER_OF=*/ 0) .repeatUntilStable([](QueryBuilder& b) { b.walkEdge(/*PARENT_GROUP=*/ 1); }) .collectBitset() .compile(); impulse_vm_context_t* ctx = nullptr; QueryResult res = query.execute(snap, /*input_param=*/ 101, &ctx); if (ctx) impulse_vm_context_destroy(ctx); ``` --- ## 2. Parameterized Prepared Statements (Tier 2: `ImpulseStatement` / `impulse_stmt_t`) For declarative `openCypher` queries, prepare a statement once and execute it repeatedly with caller-bound parameters and pre-sized scratch buffers: === "Java 25 (`ImpulseStatement`)" ```java try (ImpulseStatement stmt = snap.prepare( "MATCH (u:User)-[:PURCHASED]->(p:Product) " + "WHERE u.id = $userId AND p.price <= 100.0 " + "RETURN p")) { stmt.bindNode("userId", 42L); try (RowReader rows = stmt.execute()) { while (rows.next()) { long productDenseId = rows.getNodeId(0); } } } ``` === "C-ABI (`impulse_stmt_t`)" ```c impulse_stmt_t* stmt = NULL; impulse_stmt_prepare( snap, "MATCH (u:User)-[:PURCHASED]->(p:Product) WHERE u.id = $userId AND p.price <= 100.0 RETURN p", &stmt ); size_t buf_len = impulse_stmt_buffer_size(stmt); void* buf = malloc(buf_len); // Reusable per-thread buffer impulse_stmt_bind_node(stmt, "$userId", 42); impulse_stmt_execute(stmt, buf, buf_len); size_t word_count = impulse_stmt_row_count(stmt); const uint64_t* bitset_words = (const uint64_t*)impulse_stmt_column_data(stmt, 0); impulse_stmt_finalize(stmt); free(buf); ``` !!! tip "Ad-Hoc Compilation vs. Pre-Prepared Statements" Because the Impulse compiler pipeline (AST $\to$ Stage 1 & 2 Optimizer $\to$ `impOps` Bytecode $\to$ Java 25 `MethodHandle` JIT) completes in microseconds, compiling analytical queries directly with concrete constants unlocks **compile-time Zone Map branch pruning** (`age > 250` $\to$ `FALSE`) and **constant folding** that generic `$param` placeholders cannot exploit until bind time. Use pre-prepared statements for high-QPS request handlers (100K+ QPS), and compile ad-hoc fluent or CEL queries freely for analytical sweeps. ================================================================================ FILE: docs/query-api/fluent-api.md | URL: https://www.impulsegraph.org/query-api/fluent-api/ ================================================================================ # Fluent Traversal API The **Fluent Traversal API** provides a strongly-typed, allocation-free pipeline for stepping across domains, filtering node and edge attributes with [Google CEL](../dsl/cel.md), performing off-heap bitset algebra, and materializing results. --- ## 1. The Five Stages of a Fluent Traversal Every fluent query follows the same five-stage lifecycle: ```mermaid flowchart LR S1["1. Anchor Domain\nsnap.domain('User')"] --> S2["2. Seed Frontier\n.fromKey('usr_101')\n.from(0, 1) / .all()"] S2 --> S3["3. Walk & Filter\n.out('OWNS')\n.filter('node.balance > 0')"] S3 --> S4["4. Loops / State\n.repeatUntilStable(...)\n.outWithState(...)"] S4 --> S5["5. Terminal Collect\n.toKeyList() / .toList()\n.toBitSet() / .count()"] ``` ### Stage 1 & 2: Anchor Domain & Seed the Frontier Because every Node Domain (`User`, `Account`, `Product`) has its own independent 0-indexed dense ID space ($0 \dots N_d - 1$), multi-domain queries in Java 25 begin by binding a domain via `snap.domain("DomainName")` and selecting the initial frontier (while Python and Rust provide `snap.traverse(start_node)` as well as low-level register `QueryBuilder`s): | Seed Method (Java 25 `DomainView`) | Python / Rust Equivalent | Description | | :--- | :--- | :--- | | `.all()` | `snap.domain(d).all()` / `input_set()` | Seeds the frontier with **all $N_d$ nodes** ($0 \dots N_d - 1$) in the domain. | | `.from(long id)` | `snap.domain(d).from_node(id)` / `traverse(id)` | Seeds a single dense node ID. | | `.from(long... ids)` | `snap.domain(d).from_nodes(ids)` | Seeds a batch of dense node IDs. | | `.from(ImpulseBitSet bits)` | `vm.QueryBuilder` bitset seed | Seeds from a pre-computed off-heap BitSet. | | `.fromKey(String key)` | `snap.domain(d).from_key(key)` | Resolves an external business key (`String`, `UUID`, `int64`) to its dense ID via the domain's key catalog. | | `.fromKeys(String... keys)` | `snap.domain(d).from_keys(keys)` | Resolves a batch of external business keys to dense IDs. | --- ## 2. Cross-Language Method Reference Each language SDK exposes an idiomatic traversal and/or VM `QueryBuilder` interface: | Operation | Java 25 (`Traversal`) | Python (`Traversal`) | Rust (`Traversal`) | C++20 (`vm::QueryBuilder`) | Go / C# / Node (`QueryBuilder`) | | :--- | :--- | :--- | :--- | :--- | :--- | | **Start Traversal** | `snap.domain(d).from(id)` | `snap.traverse(id, catalog=...)` | `snap.traverse(id)` | `qb.inputNode(0)` | `InputNode(0)` / `inputNode(0)` | | **Forward Walk (CSR)** | `.out(rel)` | `.out(rel)` | `.out(rel)` | `.walkEdge(relId)` | `WalkEdge(relId, dst)` / `walkEdge(relId)` | | **Reverse Walk (CSC)** | `.in(rel)` | `.in_(rel)` | `.in_step(rel)` | `.walkCsc(relId)` | `CscWalk(relId, dst)` / `walkCsc(relId)` | | **Filtered Forward Walk** | `.out(rel, cel)` | `.out(rel, filter_id=...)` | `.out_filtered(rel, cel)` | `.walkEdgeFiltered(relId, filterId)` | `WalkEdgeFiltered(...)` / `walkEdgeFiltered(...)` | | **In-Domain Node Filter** | `.filter(cel)` | `.filter(filter_id=...)` | `.out_filtered(rel, cel)` | `.filterNode(filterId)` | `qb.filterNode(filterId)` (Node) | | **Bind Parameter** | `.withParam(k, v)` | `snap.cypher(..., params=...)` | `.with_param(k, v)` | C-ABI `impulse_stmt_bind_*` | `WithParam(k, v)` / `withParam(k, v)` | | **Fixed-Point Loop** | `.repeatUntilStable(rel)` | `vm.QueryBuilder.repeat_until_stable` | — | `.repeatUntilStable([](auto& b){...})` | `qb.repeatUntilStable(b => ...)` (Node) | | **Collect Dense IDs** | `.toList()` / `.toSet()` | `.to_list()` / `.to_set()` | `.to_vec()?` / `.to_hashset()?` | `.collectArray()` | `CollectArray(reg)` / `collectArray()` | | **Collect Business Keys** | `.toKeyList()` | `snap.resolve_keys_batch(d, ids)` | — | `.mapDenseToKeys()` | `qb.mapDenseToKeys()` (Node) | | **Collect Off-Heap BitSet**| `.toBitSet()` | `vm.QueryBuilder.collect_bitset()` | — | `.collectBitset()` | `CollectBitset(reg)` / `collectBitset()` | | **Count Surviving Nodes** | `.count()` | `.count()` | `.count()?` | `.cardinality()` | `SetCardinality(s, d)` / `cardinality()` | | **Test Single Target** | `.toBitSet().get((int) id)` | `.contains(id)` | `snap.is_reachable(rel, s, t)` | `res.testBitset(ctx, id)` | `IsReachable(...)` / `isReachable(...)` | | **Disassemble `.impas`** | `.toImpAsm()` | `.to_impas()` | — | `impulse_compile_to_impas` | — | | **Multi-Lane Sub-Builder (`v0.10.0`)** | `snap.domain(d).multiLane()` | `snap.domain(d).multi_lane()` | — | `snap.domain(d).multiLane()` / `qb.laneInitSeeds(...)` | — | | **Vector ANN & Rerank (`v0.10.0`)** | `snap.domain(d).vectorSearch(...)` | `snap.domain(d).vector_search(...)` | `snap.vamana_ann_search(...)` | `snap.domain(d).vectorSearch(...)` / `.rerank(...)` | — | !!! tip "Multi-Lane Bit-Sliced Traversals & Hybrid Vector Search (`v0.10.0`)" For simultaneous 8/16/32/64-lane provenance tracking (`snap.domain(d).multiLane()`), $N-1$/$N-2$ contingency edge masking, and Vamana ANN (`IMP_INDEX_VAMANA_ANN = 0x08`) `vectorSearch` + SIMD `.rerank(...)`, see **[State Projections, Reducers & Loops (§4–§5)](advanced-querying.md)**. !!! note **Why `.in_()` in Python and `.in_step()` in Rust?** Both Python and Rust reserve `in` as a language keyword (`for x in y`). Python follows PEP 8 with a trailing underscore (`.in_("REL")`), while Rust uses `.in_step("REL")`. --- ## 3. Filtering & Parameter Binding with Google CEL Filters can be applied either **in-domain** via `.filter(celExpr)` (which scans only the active domain's Structure-of-Arrays attribute columns) or **inline during an edge walk** via `.out(rel, celExpr)` (which evaluates edge, source, and target attributes in a single fused pass): * **`node.`**: Attribute on the currently active node domain (used in `.filter("node.age >= 21")`). * **`src.`**: Attribute on the source node of a walk step. * **`edge.`**: Attribute on the traversed edge (used in `.out("TRANSFERRED_TO", "edge.amount >= 1000.0")`). * **`tgt.`**: Attribute on the candidate target node of a walk step. * **`$param` or `@param`**: Named parameters bound via `.withParam("param", value)`. ```java long qualifiedPurchases = snap.domain("User") .fromKeys("usr_alice", "usr_bob") .withParam("minScore", 700.0) .filter("node.credit_score >= $minScore && node.active == true") .out("PURCHASED", "edge.amount > 250.0 && tgt.in_stock == true") .count(); ``` --- ## 4. Off-Heap BitSet Set Algebra (`OR`, `AND`, `AND NOT`) Because every domain's nodes are dense integers $0 \dots N_d - 1$, any frontier can be materialized into an off-heap **`ImpulseBitSet`** (`OffHeapBitSet`) and combined using word-level / SIMD bitwise operations—**provided both bitsets belong to the same domain**: ```java var users = snap.domain("User"); try (Arena arena = Arena.ofConfined()) { ImpulseBitSet aliceFriends = users.fromKey("usr_alice").out("FOLLOWS").toBitSet(); ImpulseBitSet bobFriends = users.fromKey("usr_bob").out("FOLLOWS").toBitSet(); // 1. Intersection (AND): Mutual friends of Alice and Bob ImpulseBitSet mutual = new OffHeapBitSet(arena, (int) users.nodeCount()); mutual.or(aliceFriends); mutual.and(bobFriends); // 2. Difference (AND NOT): Friends of Alice who are NOT friends of Bob ImpulseBitSet exclusiveAlice = new OffHeapBitSet(arena, (int) users.nodeCount()); exclusiveAlice.or(aliceFriends); exclusiveAlice.andNot(bobFriends); // 3. Re-seed a new traversal directly from the computed bitset List recommendedProducts = users.from(mutual) .out("PURCHASED") .toKeyList(); } ``` --- ## 5. Multi-Language End-to-End Examples === "Java 25" ```java var users = snap.domain("User"); boolean hasAccess = users.fromKey("usr_alice") .out("MEMBER_OF") .repeatUntilStable("PARENT_GROUP") .out("HAS_PERMISSION", "edge.scope == $scope") .withParam("scope", "doc:write") .toBitSet() .get((int) targetDocumentDenseId); ``` === "Python" ```python from impulse_graph import Snapshot with Snapshot("hetionet.imps") as snap: # Compound (ID 0) -> Gene <- Disease traversal indications = ( snap.traverse(start_node=0, catalog={"binds": 0, "associates": 1}) .out("binds") .in_("associates") .to_list() ) ``` === "Rust" ```rust use impulse_graph::reader::SnapshotReader; let snap = SnapshotReader::open("security.imps")?; let reachable_hosts = snap.traverse(0) .out("MEMBER_OF") .out_filtered("CAN_SSH", "edge.port == 22") .to_vec()?; ``` === "C++20 (`impulse::vm::QueryBuilder`)" ```cpp #include "impulse_vm_fluent.hpp" using namespace impulse::vm; CompiledQuery query = QueryBuilder() .inputNode(0) // R0 = seed User ID .walkEdge(/*MEMBER_OF=*/ 0) .repeatUntilStable([](QueryBuilder& b) { b.walkEdge(/*PARENT_GROUP=*/ 1); }) .walkEdgeFiltered(/*HAS_PERMISSION=*/ 2, /*filter_id=*/ 1) .collectBitset() .compile(); impulse_vm_context_t* ctx = nullptr; QueryResult res = query.execute(snap, /*input_param=*/ 42, &ctx); bool has_access = res.testBitset(ctx, target_doc_dense_id); if (ctx) impulse_vm_context_destroy(ctx); ``` === "Node.js / TypeScript" ```typescript import { Snapshot, VmContext, VmState, QueryBuilder } from 'impulse-graph'; const snap = new Snapshot('ecommerce.imps'); const ctx = new VmContext(snap); const state = new VmState(); const query = new QueryBuilder() .inputNode(0) .walkEdge(0) // PURCHASED .walkCsc(0) // <-PURCHASED .walkEdge(0) // PURCHASED .collectBitset() .compile(); const res = query.executeWithContext(ctx, state, 42); ctx.destroy(); snap.close(); ``` === "C# (.NET)" ```csharp using ImpulseGraph; using ImpulseGraph.Vm; using var snap = new Snapshot("powergrid.imps"); using var ctx = new VmContext(snap); Query query = new QueryBuilder() .InputNode(0) .WalkEdge(relationId: 0, dstReg: 1) .WalkEdge(relationId: 0, dstReg: 2) .CollectBitset(reg: 2) .Compile(); ExecutionResult res = snap.ExecuteQuery(query, ctx, inputParam: 101UL); ``` --- ## Next Steps * **[State Projections, Reducers & Loops](advanced-querying.md)**: Carry computed weights/distances across hops with `.outWithState(...)`, `:MIN`/`:MAX`/`:SUM`/`:ARGMIN` reducers, and `.project(...)`. * **[Google CEL (Filters & Math)](../dsl/cel.md)**: Full operator table and the 46 built-in SIMD math functions. ================================================================================ FILE: docs/query-api/advanced-querying.md | URL: https://www.impulsegraph.org/query-api/advanced-querying/ ================================================================================ # State Projections, Reducers & Loops While pure reachability queries pass a boolean BitSet from domain to domain, analytical queries often need to **repeat walks until convergence** or **carry and aggregate computed state** (costs, distances, capacities, or path witnesses) across hops. --- ## 1. Fixed-Point & Bounded Loops (`repeatUntilStable` & `repeat`) For recursive hierarchies, supply chains, power-grid islanding, or Relationship-Based Access Control (ReBAC), Impulse Graph executes multi-hop loops directly in off-heap bitset registers with zero per-iteration heap allocations: ### 1.1 Unbounded Transitive Closure (`repeatUntilStable`) Repeatedly steps across the specified relation until no new nodes are discovered ($\text{Frontier}_{t+1} == \text{Frontier}_t$), with optional inline CEL edge/node filtering: ```java var groups = snap.domain("Group"); // Compute full reflexive transitive closure (R*, >= 0 hops) of parent groups List allAncestorGroups = groups.fromKey("grp_engineering_west") .repeatUntilStable("PARENT_GROUP") .toKeyList(); // Transitive closure with an inline CEL predicate List activeAncestors = groups.fromKey("grp_engineering_west") .repeatUntilStable("PARENT_GROUP", "edge.active == true") .toKeyList(); ``` !!! important **Reflexive Closure ($R^*$) vs. Positive Closure ($R^+$) for Cycle Detection**: In `ImpOpsBytecodeEmitter`, `repeatUntilStable(relation)` initializes the accumulator register (`R2`) with the starting seed frontier (`R0`), computing the **reflexive** transitive closure ($R^*$, which includes 0-hop starting nodes). When testing whether a node can reach *itself* via a cycle ($\ge 1$ hop), step one hop first with `.out(relation)` before calling `.repeatUntilStable(relation)`: ```java boolean hasCycle = snap.domain("Account") .from(suspectId) .out("TRANSFERRED_TO") .repeatUntilStable("TRANSFERRED_TO") .toBitSet() .get((int) suspectId); ``` ### 1.2 Bounded Hop Expansion (`repeat(n, relation)`) Applies a domain-preserving relation step up to $N$ hops: ```java // Expand up to 3 hops across the KNOWS relation Set threeHopNetwork = snap.domain("User") .fromKey("usr_alice") .repeat(3, "KNOWS") .toSet(); ``` --- ## 2. State-Bearing Traversals & Monoidic Reducers (`.outWithState`) When a query carries computed state across an edge relation $R: D_1 \to D_2$, multiple edges from $D_1$ will frequently land on the same destination node in $D_2$. Instead of emitting duplicate rows (like a SQL `JOIN`), `.outWithState(relation, stateProjections)` (and `.outWithState(relation, edgePredicate, stateProjections)`) requires an explicit **monoidic reducer** specifying how converging values are collapsed into a single value per target node: ```text state.: = ``` ```java List budgetCities = snap.domain("City").fromKey("ATL") .outWithState("FLIGHT_LEG", "state.min_cost:MIN = src.airport_fee + edge.ticket_price") .filter("state.min_cost <= 350.0") .toKeyList(); ``` ### 2.1 The 10 Hardware SIMD Reducers & Co-Reducers `org.impulsegraph.api.traversal.Reducer` defines 8 core monoidic reducers and 2 witness co-reducers: | Reducer Tag | Category | Monoid Operation | Hardware / SIMD Execution Strategy | | :--- | :--- | :--- | :--- | | **`:MIN`** | Math | Minimum ($\min$) | Conflict-aware SIMD vector minimum prior to target scatter. | | **`:MAX`** | Math | Maximum ($\max$) | Conflict-aware SIMD vector maximum prior to target scatter. | | **`:SUM`** | Math | Accumulation ($+$) | Vectorized histogram accumulation / scatter-add. | | **`:AVG`** | Math | Arithmetic Mean | Dual accumulators (`SUM` + `COUNT`) $\to$ final vector division. | | **`:COUNT`** | Topology | Path Multiplicity | Vectorized arrival counter per target node. | | **`:OR`** | Logic | Boolean Union ($\lor$) | Bitwise `OR` across 64-bit / 512-bit words. | | **`:AND`** | Logic | Universal Match ($\land$)| Bitwise `AND` across 64-bit / 512-bit words. | | **`:ANY`** | Witness | Arbitrary Witness | Masked vector scatter using inverted visited bitmask. | | **`:ARGMIN(f)`**| Co-Reducer | Min-Value Witness | Reuses the SIMD lane-winner mask from field `f`'s `:MIN` reduction. | | **`:ARGMAX(f)`**| Co-Reducer | Max-Value Witness | Reuses the SIMD lane-winner mask from field `f`'s `:MAX` reduction. | !!! note **Semantic Type Safety on Node IDs**: Even though Dense IDs are integers (`0..N-1`), the compiler tracks them as `TYPE_NODE_ID` and forbids nonsensical arithmetic reducers (`:SUM`, `:AVG`) on node IDs while permitting witness reducers (`:ANY`, `:MIN`, `:MAX`, `:ARGMIN`, `:ARGMAX`). ### 2.2 Witness Extraction with Co-Reducers (`:ARGMIN` / `:ARGMAX`) When computing a `:MIN` or `:MAX` metric (such as the lowest shipping cost to each distribution center), you often want to know **which source node produced that winning value**. `:ARGMIN(state.field)` and `:ARGMAX(state.field)` update the witness atomically alongside the winning metric: ```java List qualifyingCenters = snap.domain("Warehouse").from(activeWarehouses) .outWithState("TRUCK_ROUTE", """ state.lowest_cost:MIN = src.handling_cost + edge.freight_fee, state.best_warehouse:ARGMIN(state.lowest_cost) = src.id """) .filter("state.lowest_cost <= 500.0") .toKeyList(); ``` ### 2.3 In-Domain State Projections (`.project`) To compute derived state values across the currently active domain *without* walking an edge ($\langle D, S \rangle \to \langle D, S' \rangle$), use `.project(...)`: ```java snap.domain("Player").fromKey("player_42") .outWithState("PLAYED_IN", """ state.total_hits:SUM = edge.hits, state.total_at_bats:SUM = edge.at_bats """) .project("state.batting_avg = state.total_hits / max(1.0, state.total_at_bats)") .filter("state.batting_avg >= 0.300") .toKeyList(); ``` ### 2.4 Consuming & Extracting Projected State at the Terminal Step There are three ways projected state and numeric attributes are consumed at the end of a query pipeline: 1. **Downstream Frontier Filtering (`Traversal`)**: As shown above, any `state.` computed by `.outWithState(...)` or `.project(...)` can be referenced in subsequent `.filter("state. ...")` or `.outWithState(...)` steps to prune the active node frontier before calling `.toBitSet()`, `.toList()`, `.toKeyList()`, or `.count()`. 2. **Terminal Scalar & Witness Reductions (`ImpulseQueryBuilder` & `ImpulseGraphQuery`)**: When you want to reduce projected values across the surviving target frontier into a single scalar aggregate (`Double`) or extract the winning target node ID (`Integer`), `org.impulsegraph.api.ImpulseQueryBuilder` provides terminal reduction operators (`reduceMin()`, `reduceMax()`, `reduceSum()`, `reduceAvg()`, `reduceArgMin()`, `reduceArgMax()`): ```java import org.impulsegraph.api.ArgType; import org.impulsegraph.api.ImpulseGraphQuery; import org.impulsegraph.api.ImpulseQueryBuilder; // Terminal scalar reduction (OP_REDUCE / OP_VECTOR_REDUCE_SUM -> Double) ImpulseGraphQuery minCostQuery = new ImpulseQueryBuilder() .input("Warehouse", ArgType.SINGLE_NODE) .walkEdge("TRUCK_ROUTE") .projectExpression("handling_cost", "+", "freight_fee") .reduceMin(); double minCost = minCostQuery.execute(snap, startWarehouseId); // Terminal witness reduction (reduceArgMin / reduceArgMax -> winning target Node ID) ImpulseGraphQuery bestCenterQuery = new ImpulseQueryBuilder() .input("Warehouse", ArgType.SINGLE_NODE) .walkEdge("TRUCK_ROUTE") .projectExpression("handling_cost", "+", "freight_fee") .reduceArgMin(); int bestCenterId = bestCenterQuery.execute(snap, startWarehouseId); ``` 3. **Multi-Column Tabular State Extraction (`v1.0.0` Roadmap)**: On the high-level `Traversal` fluent interface, terminal collectors (`collect()`, `toBitSet()`, `toList()`, `toKeyList()`, `count()`) currently return the surviving target node frontier (`ImpulseBitSet` / dense IDs / keys). Direct multi-column tabular extraction of attached `state.*` registers (`Traversal.collectRows()`) is scheduled for the `v1.0.0` release. --- ## 3. Early Scalar State vs. Late Materialization of Heavy Attributes A key rule of thumb for high-throughput queries is distinguishing lightweight scalar state from heavy strings or high-dimensional vectors: * **Carry Lightweight Numbers in State (`float32`, `int32`, `float64`)**: Accumulating weights, distances, or timestamps inside `.outWithState(...)` keeps all data in contiguous SIMD vector registers. * **Late-Materialize Strings & Business Keys at the End**: Never copy strings during intermediate hops. Traverse strictly over dense `0..N-1` IDs and resolve external keys or string attributes only for the surviving target nodes via `.toKeyList()`: ```java // Hot loop walks User -> Product -> Factory strictly on dense integer IDs, // resolving string business keys only for the surviving Factory nodes at the end: List factoryKeys = snap.domain("User") .fromKey("usr_alice") .out("PURCHASED", "edge.amount >= 100.0") .out("MANUFACTURED_BY") .toKeyList(); ``` --- ## 4. Multi-Lane Bit-Sliced Traversals, Quorum & Outage Screening (v0.10.0 Feature Showcase) Standard 1-bit frontiers (`TYPE_BITSET_HANDLE` `0x04`) collapse all seed nodes into a single boolean union ($\bigcup_i \text{Reach}(s_i)$), erasing per-seed provenance after the first hop. **Multi-Lane Bit-Sliced Execution (`TYPE_LANE_FRONTIER = 0x10`, opcodes `0xC0..0xC9`)** generalizes the frontier into an adaptive $W$-bit unsigned word per node (`WIDTH_8` $\le 8$, `WIDTH_16` $\le 16$, `WIDTH_32` $\le 32$, `WIDTH_64` $\le 64$ lanes, with automatic $\lceil K / 64 \rceil$ multi-batch chunking for $K > 64$), propagating up to 64 independent traversals in a single CSR/CSC pass. ### 4.1 The Five Multi-Lane Pipeline Stages (`0xC0..0xC9`) 1. **Three Initialization Modes (`0xC0..0xC2`)**: * **Distinct Seeds (`OP_LANE_INIT_SEEDS` `0xC0` / `.fromSeeds(...)` / `.fromKeys(...)`)**: Assigns each seed $s_b$ to its own bit lane (`lanes[s_b] |= (1ULL << b)`). * **Concept Groups (`OP_LANE_INIT_GROUPS` `0xC1` / `.fromGroups(...)`)**: Maps multiple candidate nodes $(u, g)$ into shared group lane $g \in [0, K-1]$ (`lanes[u] |= (1ULL << g)`) for Group Steiner Tree discovery. * **Counterfactual Edge Outages (`OP_LANE_SET_EDGE_MASK` `0xC2` / `.fromOutages(...)`)**: Attaches per-edge trip bitmasks (`edge_trip_mask[rel_id][e] |= (1ULL << b)`) so lane $b$ treats branch $e$ as open/tripped during $N-1$ / $N-2$ contingency screening. 2. **Single-Pass Bit-Sliced CSR/CSC Walks (`OP_LANE_CSR_WALK` `0xC3`, `OP_LANE_CSC_WALK` `0xC4`)**: * Propagates all active lanes across outgoing (`0xC3`) or incoming (`0xC4`) edges in a single topology scan: $$\text{next\_lanes}[v] \;\mathrel{\vert}=\; (\text{current\_lanes}[u] \land \text{active\_mask}) \land \neg\text{edge\_trip\_mask}[\text{rel\_id}][e]$$ * Setting the `FIXPOINT` modifier (`flags & 0x04` / `.repeatUntilStable(rel)`) executes delta-frontier propagation (`newly_reached = step_out[v] & ~out_lanes[v]`) until all lanes converge with zero per-iteration allocations. 3. **Bit-Lane Pruning (`OP_LANE_PRUNE_MASK` `0xC5`)**: * **`mode = 0` (Explicit Deny Mask / `.pruneWhere` / `.pruneDeniedBy`)**: Clears denied nodes or strips specific lane bits via `lanes[u] &= ~deny_mask[u]`. * **`mode = 1` (Intra-Word `ALLOW & ~DENY` Zanzibar Split)**: Splits the lane word into `allow_bits = low_half` and `deny_bits = high_half`, computing `lanes[u] = allow_bits & ~deny_bits` in one register operation. * **`mode = 2` (Degree-Gated Hub Quorum Prune / `.pruneHubs(maxDeg, minQuorum)`)**: Suppresses promiscuous supernode hubs by zeroing `lanes[u]` whenever $\text{deg}(u) > \text{max\_deg}$ and $\text{popcount}(\text{lanes}[u]) < \text{min\_quorum}$. 4. **Quorum Filtering & Bridging Back to 1-Bit `Traversal` (`OP_LANE_FILTER_QUORUM` `0xC6`)**: * Evaluates $\text{popcount}(\text{lanes}[u] \land \text{req\_mask}) \ge \text{min\_k} \land (\text{lanes}[u] \land \text{forbid\_mask}) = 0$ and emits a standard `TYPE_BITSET_HANDLE` (`0x04`) via `.toQuorumTraversal(minLanes)`. 5. **Terminal Per-Lane Reductions & Minimum Set Cover (`0xC7..0xC9`)**: * **`OP_LANE_REDUCE_AND` (`0xC7` / `.checkAllNodesReachedPerLane()`)**: Bitwise AND across all $N_d$ nodes to identify which contingency lanes maintained full connectivity (`active_mask & ~all_reached`). * **`OP_LANE_REDUCE_ATTR` (`0xC8` / `.reducePerLane(...)` / `.argMinNodesPerLane(...)`)**: Single-pass reduction of a scalar attribute into $K$ per-lane accumulators (`SUM`, `MIN`, `MAX`, `COUNT`, or deterministic lowest-ID-tie-broken `ARGMIN` / `ARGMAX` witness node IDs). * **`OP_LANE_SET_COVER` (`0xC9` / `.findSetCoverPairs(...)` / `.findGreedySetCover(...)`)**: Finds exact 2-node pairs or a greedy minimum witness node cover (`argmax_u popcount(lanes[u] & uncovered)`) spanning `target_mask`. ```cpp #include "impulse_vm_fluent.hpp" using namespace impulse::vm; SnapshotView snap(raw_snapshot); // Evaluate a 10-gene oncology panel (8 tumor drivers + 2 cardiac safety genes) in one 16-bit pass: MultiLaneResult panel = snap.domain("Gene").multiLane() .fromKeys({"BRCA1", "BRCA2", "EGFR", "MYC", "KRAS", "PIK3CA", "BRAF", "ERBB2", "KCNH2_SAFE", "SCN5A_SAFE"}) .out("INTERACTS_GiG") .pruneHubs(/*max_degree=*/ 500, /*min_quorum=*/ 2) .in("BINDS_CbG") .mustHitAtLeast(5, {"BRCA1", "BRCA2", "EGFR", "MYC", "KRAS", "PIK3CA", "BRAF", "ERBB2"}) .mustAvoidAll({"KCNH2_SAFE", "SCN5A_SAFE"}) .collect(); auto multi_target_drugs = panel.keysWithQuorum(5); auto two_drug_cocktails = panel.findSetCoverPairs(0x00FFULL); ``` ### 4.2 Empirical Width-Scaling Throughput (`MultiLaneVmBenchmarkTest`, Java 25 VM) Executed on Apple Silicon (ARM64, JDK 25.0.2) over an off-heap CSR graph with $|V| = 50,000$ nodes and $|E| = 500,000$ directed edges (`org.impulsegraph.vm.MultiLaneVmBenchmarkTest`), a 2-hop accumulated `OP_LANE_CSR_WALK` (`0xC3`) scales near-linearly with the number of active lanes because the CSR offset/target memory reads are amortized across all $L$ bit-lanes: | Active Lanes ($L$) | Selected `LaneWidth` | 2-Hop Batch Latency | Amortized Latency / Lane | Effective Throughput (Lane-MTEPS) | | :---: | :---: | :---: | :---: | :---: | | **`L = 1`** | `WIDTH_8` | `0.224 ms` | `224.26 µs` | `2,229.5 MTEPS` | | **`L = 8`** | `WIDTH_8` | `0.226 ms` | `28.23 µs` | `17,714.1 MTEPS` | | **`L = 16`** | `WIDTH_16` | `0.234 ms` | `14.59 µs` | `34,258.8 MTEPS` | | **`L = 32`** | `WIDTH_32` | `0.225 ms` | `7.04 µs` | `71,012.5 MTEPS` | | **`L = 64`** | `WIDTH_64` | **`0.230 ms`** | **`3.60 µs`** | **`138,979.4 MTEPS`** | In the companion N-64 transmission line contingency benchmark (`OP_LANE_SET_EDGE_MASK` `0xC2` + 3-hop `OP_LANE_CSR_WALK` `0xC3` + `OP_LANE_REDUCE_AND` `0xC7`), screening 64 simultaneous edge outages completes in **`0.411 ms`** (**`6.43 µs` per N-1 outage**, or **`155,576` outages/sec** on a single core). --- ## 5. Hybrid Vector ANN Search & Exact SIMD Reranking (v0.10.0 Feature Showcase) For GraphRAG, biomedical knowledge graphs, and semantic entity retrieval, Impulse embeds **Single-Layer Vamana / DiskANN Proximity Graphs (`IMP_INDEX_VAMANA_ANN = 0x08`)** directly into Section 2.6 of the `.imps` file so vector search and symbolic CSR/CSC graph walks share the **exact same $0 \dots N_d-1$ dense domain node IDs** with zero ID translation: 1. **Two-Stage Quantized Vamana Beam Routing (`IMP_INDEX_VAMANA_ANN = 0x08`)**: * During greedy beam expansion from `medoid_node_id`, `OP_VECTOR_ANN_SEARCH` (`0xCA`) evaluates compressed routing codes (`BQ1` 1-bit binary via `XOR + popcount`, `SQ8` 8-bit scalar quantization, or `FP16` half-precision) stored in the 128-byte-aligned `quant_slab`, reducing memory bandwidth by `4x–32x`, and then reranks the `ef_search` beam candidates against the full-precision `FLOAT32` attribute column. 2. **Fused `TYPE_LANE_FRONTIER` Handshake (`OP_VECTOR_ANN_SEARCH` `0xCA` with `flags = 1`)**: * When `flags & 1 != 0` (or via `MultiLaneBuilder::fromConceptVectors`), `OP_VECTOR_ANN_SEARCH` directly seeds the top-$K$ ANN hits into a `TYPE_LANE_FRONTIER` (`0x10`) without materializing an intermediate host array. 3. **Multi-Hop Graph Walk, Quorum Bridge & Exact SIMD Reranking (`OP_VECTOR_RERANK_DOT` `0xCB`)**: * After expanding the vector seeds across symbolic graph relations (`OP_LANE_CSR_WALK` `0xC3`), pruning high-degree hubs (`OP_LANE_PRUNE_MASK` `0xC5`), and filtering for multi-concept bridge nodes (`OP_LANE_FILTER_QUORUM` `0xC6`), `OP_VECTOR_RERANK_DOT` (`0xCB`) computes exact hardware-SIMD similarity (`L2`, `COSINE`, `DOT`) over the 128-byte-aligned `FLOAT32` SoA vector attribute for only the surviving frontier nodes. ```cpp #include "impulse_vm_fluent.hpp" using namespace impulse::vm; SnapshotView snap(raw_snapshot); // 1. Single-lane Vamana ANN seed -> 2-hop graph expansion -> exact SIMD vector reranking: std::vector ranked_compounds = snap.domain("Disease") .vectorSearch("disease_embedding_vamana", query_embedding, /*top_k=*/ 16) .out("ASSOCIATES_DaG") .in("BINDS_CbG") .rerank(compound_target_embedding, "compound_embedding", /*metric=COSINE*/ 1) .collect(); // 2. Multi-concept Vector + Group Steiner Tree extraction for GraphRAG: SteinerSubgraph rag_subgraph = snap.domain("Entity").multiLane() .fromConceptVectors( "entity_embedding_vamana", { {"GLP1_Agonist", glp1_embedding}, {"mTOR_Pathway", mtor_embedding}, {"Diabetic_Nephropathy", nephropathy_embedding} }, /*hits_per_concept=*/ 20 ) .out("RELATES_TO") .pruneHubs(/*max_degree=*/ 1000, /*min_quorum=*/ 2) .out("RELATES_TO") .toSteinerSubgraph(/*min_concept_quorum=*/ 2); ``` ================================================================================ FILE: docs/dsl/opencypher.md | URL: https://www.impulsegraph.org/dsl/opencypher/ ================================================================================ # openCypher Dialect Guide Impulse Graph includes an embedded, zero-dependency **openCypher** compiler frontend that lowers read-only `MATCH ... WHERE ... RETURN` queries into [`ImpScheme` S-Expressions](impscm.md) and executes them as 64-bit `impOps` bytecode on `ImpulseVM`. --- ## 1. Supported openCypher Clause Grammar Because `.imps` snapshots are strictly read-only, the openCypher frontend focuses on high-speed analytical pattern matching and projection: ```cypher MATCH [WHERE ] RETURN ``` ### 1.1 Supported `MATCH` Patterns ```cypher // 1. Single-Hop Forward Traversal (CSR Walk) MATCH (u:User)-[:FOLLOWS]->(f:User) // 2. Single-Hop Reverse Traversal (CSC Walk) MATCH (p:Product)<-[:PURCHASED]-(u:User) // 3. Multi-Hop Metapath Across Domains MATCH (d:Disease)-[:DdG]->(g:Gene)<-[:CuG]-(c:Compound) // 4. Escaped / Namespaced Relationship Types (Backticks) MATCH (d:Disease)-[:`DISGENET::da`]->(g:Gene) // 5. Bounded Variable-Length Path (*min..max) or Unbounded Kleene Star (*) MATCH (u1:User)-[:FOLLOWS*1..3]->(u2:User) MATCH (u1:User)-[:FOLLOWS*]->(u2:User) // 6. Multi-Relation Unions and Undirected Steps MATCH (u:User)-[:FOLLOWS|FRIENDS_WITH]->(f:User) MATCH (a:Account)-[:TRANSFERRED_TO]-(b:Account) // 7. Edge Variable Binding (for edge attribute filtering & projection) MATCH (u:User)-[t:TRANSFERRED_TO]->(a:Account) ``` ### 1.2 Compile-Time Guardrails & Intentional Exclusions To guarantee sub-millisecond latency and deterministic memory bounds, the compiler enforces strict rules at parse time: 1. **Explicit Relationship Types Required**: Every edge in a `MATCH` pattern must declare its relationship type (`-[:OWNS]->`). Untyped edges (`-->` or `-[e]->`) are rejected because each relation in `.imps` is stored as an isolated CSR/CSC matrix. 2. **No Disconnected Cartesian Products**: Disconnected patterns like `MATCH (a:User), (b:Account)` are rejected at compile time to prevent $O(M \times N)$ cross-joins. 3. **Variable-Length Path Bounds**: Variable-length paths support bounded hops (`*2`, `*1..4`, `*..3`) or pure unbounded Kleene star (`*`, which lowers to `ScmFixpoint` / `OP_FIXPOINT_START`). Open-ended ranges without an upper bound (e.g. `*1..`) are rejected at parse time. 4. **Read-Only Execution**: Mutation and DDL clauses (`CREATE`, `MERGE`, `SET`, `DELETE`, `CREATE INDEX`) are rejected—updates are handled via [out-of-band `.imps` snapshot rebuilds](../getting-started/handling-mutations.md). 5. **Analytical Frontier Focus**: Clauses such as `OPTIONAL MATCH`, `WITH`, `UNWIND`, `CALL`, and algorithmic functions like `shortestPath()` are not supported. Projections in `RETURN` focus on target domain entities (`RETURN c`, `RETURN c.id`, `RETURN count(c)`). Arbitrary expressions or multi-variable Cartesian projections are not supported. --- ## 2. `WHERE` Predicates & `RETURN` Projections * **Seed Anchoring (`WHERE u._key = $key` or `WHERE u.id = $id`)**: Constraining the starting node variable anchors the initial traversal frontier to that key or dense node ID. * **Inline Node & Edge Attribute Filtering**: Predicates on edge variables (`t.amount >= $minAmt`) or node variables (`a.balance > 0`) compile directly into vectorized [Google CEL](cel.md) shaders (`OP_CSR_WALK_FILTERED` / `OP_NODE_FILTER`) evaluated inline during the CSR/CSC walk step. * **`RETURN` Target Frontier Projections**: * `RETURN c` (or `RETURN c.id`): Projects the surviving **target domain node frontier** into a zero-copy result set (`BitSetRowReader` yielding surviving dense node IDs in Java, `List[int]` in Python `snap.cypher(...)`, or bitset words in C-ABI `impulse_stmt_column_data(stmt, 0)`). * `RETURN count(c)`: Computes the scalar cardinality or aggregate of the surviving target frontier (`OP_SET_CARDINALITY` / `OP_VECTOR_REDUCE_SUM` / `OP_COLLECT_VALUE_MAP`) without materializing full arrays. !!! important **Set Semantics vs. Traditional Cypher Multi-Sets (Why Edge & Intermediate Hop Tuples Collapse)**: Traditional Cypher engines (like Neo4j) use multi-set (bag) path semantics, emitting one row per path tuple `(u, t, dst)`. Impulse Graph evaluates every hop using **Set Semantics (Monoidic Reduction)**: - When `WHERE t.amount >= 1000.0` filters an edge variable `t`, only edges satisfying that predicate are traversed, and all qualifying edges landing on the same destination node `dst` immediately collapse into `dst`'s target bitset via bitwise `OR`. - Consequently, `RETURN` outputs the **surviving target domain frontier** (or `count(target)`), rather than unreduced per-edge or intermediate-hop tuple rows. To inspect target node attributes or external keys for the surviving target IDs, use the target domain's O(1) key/attribute accessors. - **Shortest-Path Witness Tracking**: For single-hop minimum-cost witness selection, use `:ARGMIN` (`OP_REDUCE` with `ARGMIN` / `OP_STREAM_REDUCE_ARGMIN` / `reduceArgMin`). Full multi-hop path sequence reconstruction requires recording per-hop predecessor vectors across BFS levels. --- ## 3. Running openCypher Across Languages === "Java 25 (`ImpulseStatement`)" ```java String cypher = """ MATCH (d:Disease)-[:DdG]->(g:Gene)<-[:CuG]-(c:Compound) WHERE d.id = $diseaseId RETURN c """; try (ImpulseStatement stmt = snap.prepare(cypher)) { stmt.bindNode("diseaseId", 42L); try (RowReader rows = stmt.execute()) { while (rows.next()) { long compoundDenseId = rows.getNodeId(0); System.out.println("Compound ID: " + compoundDenseId); } } } ``` === "Python (`snap.cypher`)" ```python from impulse_graph import Snapshot with Snapshot("banking.imps") as snap: # Returns the list of surviving destination Account dense node IDs dst_account_ids = snap.cypher( """ MATCH (u:User)-[:OWNS]->(src:Account)-[:TRANSFERRED_TO]->(dst:Account) WHERE u.id = $user_id RETURN dst """, params={"user_id": 101}, catalog={"OWNS": 0, "TRANSFERRED_TO": 1}, ) for account_id in dst_account_ids: print("Reached Account dense ID:", account_id) ``` === "C / C++20 (`impulse_stmt_*`)" ```c impulse_stmt_t* stmt = NULL; impulse_stmt_prepare( snap, "MATCH (u:User)-[e:KNOWS]->(f:User) WHERE u.id = $uid AND e.weight >= 0.8 RETURN f", &stmt ); size_t buf_len = impulse_stmt_buffer_size(stmt); void* buf = malloc(buf_len); impulse_stmt_bind_node(stmt, "$uid", 101); impulse_stmt_execute(stmt, buf, buf_len); size_t word_count = impulse_stmt_row_count(stmt); const uint64_t* bitset_words = (const uint64_t*)impulse_stmt_column_data(stmt, 0); impulse_stmt_finalize(stmt); free(buf); ``` --- ## 4. How openCypher Lowers to `ImpScheme` IR Under the hood, `CypherCompiler` lowers `MATCH ... WHERE ... RETURN` patterns directly into [`ImpScheme` S-Expressions](impscm.md): | openCypher Query | Lowered `ImpScheme` IR (`.impscm`) | | :--- | :--- | | `MATCH (d:Disease)-[:DdG]->(g:Gene)<-[:CuG]-(c:Compound)`
`WHERE d.id = $diseaseId RETURN c` | `(program (csr-walk "DdG") (csc-walk "CuG") (collect-bitset))` | | `MATCH (d:Disease)-[:DdG]->(g:Gene)<-[:CuG]-(c:Compound)`
`WHERE d.id = $diseaseId RETURN count(c)` | `(program (csr-walk "DdG") (csc-walk "CuG") (collect-count))` | | `MATCH (u:User)-[e:knows]->(f:User)`
`WHERE u.id = $uid AND e.weight >= 0.8 RETURN f` | `(program (csr-walk "knows" (shader (cel-expr (vec-cmp-gte (get-attr edge "weight") 0.8)))) (collect-bitset))` | ================================================================================ FILE: docs/dsl/cel.md | URL: https://www.impulsegraph.org/dsl/cel/ ================================================================================ # Google CEL (Filters, Projections & SIMD Math) **Impulse Graph Engine** embeds a zero-dependency **Google Common Expression Language (CEL)** compiler across all query frontends (Fluent API, openCypher, ImpLog, and ImpK), powering both **boolean predicate filtering (`WHERE` / `.filter`)** and **state / column projections (`.outWithState` / `.project` / `RETURN`)**. *(Note: Impulse CEL implements the analytical and vectorized math subset of Google CEL—including scalar and vector arithmetic, comparisons, bitwise logic, ternary branching, in-list membership, and 46 SIMD math functions. General CEL protobuf message descriptors, dynamic map literals, and list comprehensions like `.all()` or `.map()` are not included).* --- ## 1. Two Roles: Predicate Filters vs. Column Projections 1. **Predicate Mode (`.filter(...)`, `.out(rel, cel)`, `WHERE`)**: * Evaluates boolean expressions into off-heap bitmasks (`TYPE_BITSET_HANDLE`), driving SIMD frontier pruning (`OP_NODE_FILTER`, `OP_CSR_WALK_FILTERED`). * Example: `.out("TRANSFERRED_TO", "edge.amount >= 1000.0 && !tgt.is_frozen")` 2. **Projection Mode (`.outWithState(...)`, `.project(...)`, `RETURN`)**: * Evaluates numeric, temporal, or conditional expressions over active nodes/edges into 128-byte-aligned off-heap state vectors and Apache Arrow-compatible result columns. * Example: `.outWithState("FLIGHT", "state.min_cost:MIN = src.airport_fee + edge.price * 1.08")` ### Context Identifiers * **`node.`**: Attribute on the active domain during an in-domain `.filter(...)` or `.project(...)`. * **`src.`**: Source node attribute during an edge walk. * **`edge.`**: Edge attribute on the traversed relation. * **`tgt.` / `dest.`**: Target node attribute during an edge walk. * **`state.`**: Attached state vector field carried along the traversal. * **`$param` / `@param`**: Bound runtime parameter. --- ## 2. Operators & Built-In SIMD Math Library ### 2.1 Operators | Category | Operators | Examples | | :--- | :--- | :--- | | **Arithmetic** | `+`, `-`, `*`, `/`, `%` | `edge.weight * 100.0 + tgt.priority` | | **Comparison** | `==`, `!=`, `<`, `<=`, `>`, `>=` | `tgt.region == "us-east" && edge.miles < 500.0` | | **Logical** | `&&`, `\|\|`, `!` | `!tgt.is_locked && (src.is_admin \|\| src.level > 5)` | | **Conditional** | `? :` (Ternary) | `edge.active ? tgt.score * 1.5 : 0.0` | | **Membership** | `in`, `[a, b, c]` | `tgt.tier in [1, 2, 3]` | ### 2.2 Built-in Vector Math Functions All math functions compile directly to hardware SIMD instructions (`impOps` vector math kernels): * **Algebraic & Clamping**: `abs`, `min`, `max`, `sqrt`, `rsqrt`, `cbrt`, `pow(x, y)`, `hypot(x, y)`, `lerp(a, b, t)`, `clamp(x, min, max)`, `copysign`, `fmod`. * **Exponential & Logarithmic**: `exp`, `exp2`, `exp10`, `expm1`, `log`, `log2`, `log10`, `log1p`. * **Trigonometric & Hyperbolic**: `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `sinc`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`. * **Neural Activations**: `relu`, `leaky_relu`, `sigmoid`, `gelu`, `silu`, `softplus`. * **Rounding & Special**: `floor`, `ceil`, `trunc`, `round`, `erf`, `erfc`, `lgamma`. * **Bitwise**: `popcount`, `clz`, `ctz`, `rotl`, `rotr`. * **Safe Floating-Point Guards**: * `safeDiv(num, den, fallback)`: Returns `fallback` when `den == 0.0` or non-finite, preventing `NaN` propagation. * `isNan(x)`, `isInf(x)`, `isFinite(x)`: IEEE-754 classification predicates (backed by `OP_ASSERT_FINITE`). --- ## 3. Compile-Time Algebraic Optimization (`CelAstOptimizer`) Before bytecode emission, CEL expressions are simplified by the Stage 1 optimizer in `< 10 µs`: | Input CEL Expression | Simplified AST / `ImpScheme` Output | Optimization Applied | | :--- | :--- | :--- | | `2 + 3 * 4` | `14` | Constant folding | | `x * 1 + 0` / `!(!edge.valid)` | `x` / `(get-attr edge "valid")` | Identity & double-negation elimination | | `true ? src.score : tgt.score` | `(get-attr src "score")` | Dead branch elimination | | `sqrt(edge.distance) < 10.0` | `edge.distance < 100.0` | Monotonic function inversion (eliminates `sqrt` in inner loop) | | `node.age > 250` *(when Zone Map `age.max == 114`)* | `false` *(prunes entire walk)* | Stage 1 Zone Map contradiction pruning | ================================================================================ FILE: docs/dsl/implog.md | URL: https://www.impulsegraph.org/dsl/implog/ ================================================================================ # ImpLog Specification (`.implog`) **ImpLog (`.implog`)** is the declarative **Datalog & Logic DSL** for **Impulse Graph Engine**, designed for fine-grained Relationship-Based Access Control (ReBAC / Zanzibar), transitive reachability, security policy verification, and recursive graph analytics. Unlike traditional query languages that struggle with unbounded recursion or duplicate path explosions, ImpLog evaluates Horn clauses (`Head :- Body`) using **set-theoretic semi-naïve fixed-point iteration** over off-heap bitsets, compiling directly to [`ImpScheme` IR](impscm.md) and `impOps` bytecode. --- ## 1. Syntax & Rule Primitives ImpLog programs consist of **Relation Declarations (`.decl`)** and **Horn Rules (`Head :- Body.`)**: ```prolog // 1. Typed Relation Declarations (mapped to .imps domains & relations) .decl direct_member(user: User, group: Group) .decl group_parent(child: Group, parent: Group) .decl doc_owner(doc: Document, user: User) .decl doc_editor(doc: Document, group: Group) .decl doc_viewer(doc: Document, group: Group) .decl account_locked(user: User) // 2. Recursive Transitive Group Membership (Base + Inductive Step) member(U, G) :- direct_member(U, G). member(U, Parent) :- member(U, Child), group_parent(Child, Parent). // 3. Permission Derivation & Stratified Negation (!) can_edit(U, D) :- doc_owner(D, U), !account_locked(U). can_edit(U, D) :- member(U, G), doc_editor(D, G), !account_locked(U). can_view(U, D) :- can_edit(U, D). can_view(U, D) :- member(U, G), doc_viewer(D, G), !account_locked(U). ``` | ImpLog Construct | Syntax | Compiled `ImpulseVM` Execution | | :--- | :--- | :--- | | **Conjunction (Join)** | `H(X, Z) :- R1(X, Y), R2(Y, Z).` | Sequential CSR / CSC walk (`OP_CSR_WALK` / `OP_CSC_WALK`). | | **Disjunction (Union)**| `H(X, Y) :- R1(X, Y) ; R2(X, Y).`| Bitset union (`OP_SET_UNION` / `OP_ROARING_BITMAP_OR`). | | **Stratified Negation**| `H(X) :- R(X), !Banned(X).` | Bitset difference (`OP_ROARING_BITMAP_AND_NOT`). | | **Bound Query Goal** | `?- can_view("usr_alice", Doc).` | **Magic Sets** rewrite pushing the seed binding to the root walk. | | **Lattice Aggregation (Roadmap)** | `Dist(X, Y, min(C)) :- ...` | Monoidal in-flight reduction ($\bigoplus$) at target nodes (expressed via Fluent API `.outWithState`). | --- ## 2. Key Compiler Optimizations 1. **Semi-Naïve Fixed-Point Evaluation ($\Delta \mathcal{S}_{t+1} = \tau(\Delta \mathcal{S}_t) \setminus \mathcal{S}_{\text{visited}}$)**: * Recursive rules never re-traverse edges from already-visited nodes. Each iteration expands only the newly discovered delta frontier $\Delta \mathcal{S}_t$ and subtracts $\mathcal{S}_{\text{visited}}$ via a single `OP_ROARING_BITMAP_AND_NOT` instruction until $\Delta \mathcal{S}_{t+1} = \emptyset$. 2. **Magic Sets Goal-Directed Rewriting**: * When a query binds a specific entity (e.g., `?- can_view("usr_alice", Doc)`), the compiler rewrites the recursive rules so `ImpulseVM` expands **only the subgraph reachable from `"usr_alice"`** rather than materializing group memberships for every user in the snapshot. 3. **Lattice Datalog ($\text{Datalog}^\mathcal{L}$ — Planned Roadmap)**: * Formal semiring aggregations (`min`, `max`, `sum`) inside recursive rule heads are scheduled for `v1.0.0`. In `v0.10.0`, monotonic reductions are evaluated with zero heap allocations using the Fluent Traversal API (`.outWithState(...)`) and VM opcodes `OP_CSR_WALK_REDUCE` / `OP_MXV`. --- ## 3. Compiling & Running `.implog` Programs via CLI ```bash # 1. Compile .implog rules into human-readable ImpAsm (.impas) impulse compile authz.implog -o authz.impas # 2. Inspect intermediate ImpScheme S-Expression IR (.impscm) impulse compile authz.implog --emit-ir # 3. Assemble into binary impOps bytecode (.impb) and run against a snapshot impulse assemble -i authz.impas -o authz.impb impulse run --snapshot production.imps --bytecode authz.impb --input-val 1042 ``` --- ## 4. Executing `.implog` Rules from Host SDKs You can compile and execute `.implog` programs directly inside your application using the in-kernel compiler C-ABI (`IMPULSE_LANG_IMPLOG`), the C++20 `DatalogParser`, or by loading pre-assembled `.impb` bytecode in Java and polyglot SDKs: === "C / C++20 (`impulse_compile_and_execute`)" ```c #include "impulse_vm.h" const char* implog_rules = "member(U, G) :- direct_member(U, G).\n" "member(U, P) :- member(U, C), group_parent(C, P).\n" "?- member(1042, G).\n"; impulse_vm_state_t state = {0}; state.query_context = impulse_vm_context_create(snap); // Compile .implog -> ImpScheme -> impOps and execute in a single call impulse_vm_status_t status = impulse_compile_and_execute( snap, implog_rules, IMPULSE_LANG_IMPLOG, &state, /*input_seed=*/ 1042 ); impulse_vm_context_destroy((impulse_vm_context_t*)state.query_context); ``` === "Java 25 / Polyglot (Pre-Compiled `.impb` Bytecode)" ```java // Pre-compile via CLI: // impulse compile authz.implog -o authz.impas && impulse assemble -i authz.impas -o authz.impb byte[] bytecodeBytes = Files.readAllBytes(Path.of("authz.impb")); try (Arena arena = Arena.ofConfined()) { MemorySegment prog = arena.allocateFrom(ValueLayout.JAVA_BYTE, bytecodeBytes); int instructionCount = (int) (bytecodeBytes.length / VmStateLayout.INSTRUCTION_SIZE_BYTES); // Compile to fused MethodHandle chain or execute directly in ImpulseVmInterpreter MethodHandle mh = ImpulseMethodHandleCompiler.compile(prog, instructionCount); ImpulseBitSet permittedDocs = (ImpulseBitSet) mh.invoke(graph, 1042, arena); } ``` !!! note **In-Process Java Execution & Annotations**: In-process compilation of `.implog` rule strings is supported directly in Java via `ImpLogCompiler.compileToExecutable(rules, snap, arena)`. Compile-time Java source annotations (`@ImpLogRule`) are scheduled for the `v1.0.0` release. ================================================================================ FILE: docs/dsl/impk.md | URL: https://www.impulsegraph.org/dsl/impk/ ================================================================================ # ImpK Specification (`.impk`) > **Architectural Role**: **Primary User Frontend DSL (GraphBLAS & Vector Math)** > > **ImpK** (`.impk`) is the high-level array and vector domain-specific language for the **Impulse Graph Engine**, designed for GraphBLAS matrix mathematics, PageRank, connected components, triangle counting, and SIMD vector operations. It compiles down to `ImpScheme` (`.impscm`) intermediate representation before being emitted as `ImpulseVM` bytecode (`impOps`). --- ## 1. Syntax & Core Primitives ImpK treats graph relations as sparse adjacency matrices, node frontiers as dense vectors or bitsets, and traversals as algebraic matrix-vector multiplications. The syntax consists of declarative statement assignments evaluated in sequence. ### Statement Operations | ImpK Statement | Operation | Lowered `impOps` Bytecode | | :--- | :--- | :--- | | `y = A * x` | Semiring Matrix-Vector Product (SpMV) | `OP_MXV` (`0x41`) | | `z = x + y` | Element-wise Vector Addition | `OP_EWISE_ADD` (`0x43`) | | `z = x * y` | Element-wise Vector Multiplication | `OP_EWISE_MULT` (`0x44`) | | `p = pagerank(A, x, 0.85)` | PageRank ($k$ iterations, damping $\alpha$) | `OP_MXV` + vector scale & bias loop | | `cc = afforest(A)` | Afforest / FastSV Connected Components | `OP_CC_AFFOREST` (`0x40`) | | `d = degree(A)` | Out-Degree Vector Projection | `OP_DEGREE_STREAM` (`0x4A`) | | `top = topk(v, 10)` | Top-$K$ Value & Node Selection | `OP_TOPK` (`0x34`) | --- ## 2. Multi-Lane Bit-Sliced SpMM & Vector Operations ImpK provides first-class operations for 64-lane bit-sliced contingency screening (`0xC0`..`0xC9`) and hybrid vector search (`0xCA`..`0xCB`): ``` // 1. Seed up to 64 independent query lanes F0 = lane_seeds([0, 1]) // 2. Configure counterfactual edge trips for contingency screening F1 = lane_edge_mask(A, [12, 45]) // 3. Bit-sliced forward SpMM walk across relation A F2 = lane_spmm(A, F0, true) // 4. Reverse (CSC) bit-sliced SpMM walk F3 = lane_spmm_csc(A, F2, false) // 5. Evaluate quorum across surviving lanes (>= 2 lanes active) B = lane_quorum(F3, 2) // 6. Vector ANN search and exact dot-product reranking cands = ann_search([0.15, -0.42, 0.88], 10, 0, false) scores = rerank_dot(cands, [0.15, -0.42, 0.88], 0, cosine) ``` --- ## 3. Code Example: PageRank in ImpK ``` // PageRank with damping factor 0.85 and uniform initial distribution x = uniform_vector(1.0) p = pagerank(FOLLOWS, x, 0.85) top10 = topk(p, 10) ``` --- ## 4. Compiling ImpK via CLI Using the `impulse-graph` CLI toolchain: ```bash # 1. Compile .impk source directly into canonical .impas assembly text impulse-graph compile algorithm.impk -o algorithm.impas # 2. Assemble text assembly into binary bytecode (.impb) impulse-graph assemble -i algorithm.impas -o algorithm.impb # 3. Execute compiled bytecode program against a snapshot impulse-graph run --snapshot production.imps --bytecode algorithm.impb ``` --- ## 5. Executing `.impk` Programs from Host SDKs In-process compilation and execution of `.impk` scripts is supported directly through the C-ABI (`IMPULSE_LANG_IMPK`), C++20 `impulse::impk::ImpKCompiler`, and Java 25 `ImpKCompiler`: === "Java 25 (`ImpKCompiler`)" ```java // Compile and execute ImpK scripts directly in-process String script = "y = FOLLOWS * x\n"; CompiledQuery query = ImpKCompiler.compileToExecutable(script, snapshot, arena); Object result = query.execute(snapshot, inputNodeId, arena); ``` === "C / C++20 (`impulse_compile_and_execute`)" ```c #include "impulse_vm.h" const char* impk_script = "y = FOLLOWS * x\n"; impulse_vm_state_t state = {0}; state.query_context = impulse_vm_context_create(snap); impulse_vm_status_t status = impulse_compile_and_execute( snap, impk_script, IMPULSE_LANG_IMPK, &state, /*input_seed=*/ 42 ); impulse_vm_context_destroy((impulse_vm_context_t*)state.query_context); ``` !!! note "Compile-Time Annotations Roadmap" Direct script compilation via `ImpKCompiler.compileToExecutable(...)` is available today. Compile-time Java source code annotations (`@ImpKQuery`) and macro metaprogramming frontends are scheduled for the `v1.0.0` release. ================================================================================ FILE: docs/dsl/impscm.md | URL: https://www.impulsegraph.org/dsl/impscm/ ================================================================================ # ImpScheme Specification (`.impscm`) !!! note "Internal Compiler IR — Prefer Higher-Level APIs for Application Queries" **ImpScheme (`.impscm`) is primarily an internal compiler implementation detail**—the homoiconic S-Expression Intermediate Representation (IR) that sits between Impulse's user-facing frontends and the `impOps` bytecode emitter. While writing `.impscm` directly is fully supported (and useful for compiler pass debugging, custom macro authoring, or low-level benchmarking), **application developers will almost always be better served by higher-level options**: * **[Fluent Traversal API](../query-api/fluent-api.md)** (`snap.domain("User").fromKey(...).out(...)`) * **[openCypher Prepared Statements](opencypher.md)** (`snap.prepare("MATCH ... WHERE ... RETURN ...")`) * **[Google CEL Filters & Projections](cel.md)** (`node.age >= 21 && edge.amount > 1000.0`) * **[ImpK](impk.md)** or **[ImpLog](implog.md)** domain-specific languages All of those higher-level interfaces automatically compile down to this exact `ImpScheme` IR under the hood. > **Architectural Role**: **Universal Compiler IR & Low-Level Macro Extension Target** > > **ImpScheme** (`.impscm`) serves as the common AST compiler bus where logical optimization passes (filter fusion, partition elimination, direction selection, and register allocation) are performed before emitting `ImpulseVM` bytecode. --- ## 1. Syntax & Core Primitives ImpScheme uses parenthesized Lisp/Scheme forms. All expressions are evaluated prefix style. ### Primitive Data Types * `node` (u32 node index) * `bitset` (Roaring bitmap / dense bitset handle) * `lane-frontier` (8/16/32/64-bit multi-lane bit-sliced frontier handle, `TYPE_LANE_FRONTIER = 0x10`, `v0.10.0`) * `graph` (snapshot handle) * `int` / `float` / `bool` (scalar primitives) ### Core Language Forms ```scheme ;; Top-Level Program Block (program body ...) ;; Defining a Named Query (define-query query-name body ...) ;; Lexical Bindings (let ([var1 val1] [var2 val2]) body ...) ;; Variable Assignment (set! var val) ;; Return Form (return expr) ;; Transitive Closures & Fixed-Point Loops (fixpoint "RELATION" max-iters body ...) (loop-while condition body ...) ``` --- ## 2. Graph & Vector Operators ImpScheme exposes native `impOps` primitives directly as S-expressions: | ImpScheme Form | Functionality | Target `impOps` Opcode | | :--- | :--- | :--- | | `(csr-walk "REL")` | Advance 1-hop across relation via forward CSR | `OP_CSR_WALK` | | `(csc-walk "REL")` | Reverse 1-hop traversal via CSC | `OP_CSC_WALK` | | `(csr-walk-2hop "R1" "R2")` | Fused 2-hop forward traversal | `OP_CSR_WALK_2HOP` | | `(set:intersect a b)` | Bitset intersection (AND) | `OP_ROARING_BITMAP_AND` (`OP_SET_INTERSECT`) | | `(set:union a b)` | Bitset union (OR) | `OP_ROARING_BITMAP_OR` (`OP_SET_UNION`) | | `(set:difference a b)` | Bitset difference (AND-NOT) | `OP_ROARING_BITMAP_AND_NOT` (`OP_SET_DIFFERENCE`) | | `(collect-bitset)` | Materialize surviving frontier into output register | `OP_COLLECT_BITSET` | | `(lane-init-seeds seed_reg width_flag)` | Initialize `TYPE_LANE_FRONTIER` from up to 64 seed node IDs (`v0.10.0`) | `OP_LANE_INIT_SEEDS` (`0xC0`) | | `(lane-init-groups pairs_reg num_groups)` | Initialize `TYPE_LANE_FRONTIER` from `(node_id, group_idx)` pairs (`v0.10.0`) | `OP_LANE_INIT_GROUPS` (`0xC1`) | | `(lane-set-edge-mask pairs_reg "REL")` | Attach counterfactual per-edge trip mask for relation `"REL"` (`v0.10.0`) | `OP_LANE_SET_EDGE_MASK` (`0xC2`) | | `(lane-walk-csr "REL" [1])` | Bit-sliced forward CSR step (optional `1` enables `FIXPOINT` loop) (`v0.10.0`) | `OP_LANE_CSR_WALK` (`0xC3`) | | `(lane-walk-csc "REL" [1])` | Bit-sliced reverse CSC step (optional `1` enables `FIXPOINT` loop) (`v0.10.0`) | `OP_LANE_CSC_WALK` (`0xC4`) | | `(lane-prune-mask mode arg0 arg1)` | Prune lane bits (`0` = deny mask, `1` = `ALLOW & ~DENY`, `2` = hub quorum) (`v0.10.0`) | `OP_LANE_PRUNE_MASK` (`0xC5`) | | `(lane-filter-quorum min_quorum mask_reg)` | Filter nodes with `popcount(lanes[u] & req_mask) >= min_quorum` into `TYPE_BITSET_HANDLE` (`v0.10.0`) | `OP_LANE_FILTER_QUORUM` (`0xC6`) | | `(lane-reduce-and)` | Bitwise AND reduction across all domain nodes (`v0.10.0`) | `OP_LANE_REDUCE_AND` (`0xC7`) | | `(lane-reduce-attr attr_id reduce_op)` | Per-lane attribute reduction (`SUM`, `MIN`, `MAX`, `COUNT`, `ARGMIN`, `ARGMAX`) (`v0.10.0`) | `OP_LANE_REDUCE_ATTR` (`0xC8`) | | `(lane-set-cover mask_reg mode)` | Greedy minimum witness node cover or 2-node pair cover over `mask_reg` (`v0.10.0`) | `OP_LANE_SET_COVER` (`0xC9`) | | `(vector-ann-search q_reg top_k idx_id fused)` | Vamana ANN beam search (`fused = 1` outputs `TYPE_LANE_FRONTIER`) (`v0.10.0`) | `OP_VECTOR_ANN_SEARCH` (`0xCA`) | | `(vector-rerank-dot q_reg attr_id metric)` | Exact SIMD similarity reranking (`L2`, `COSINE`, `DOT`) over active frontier (`v0.10.0`) | `OP_VECTOR_RERANK_DOT` (`0xCB`) | --- ## 3. Code Example: Transitive Reachability in ImpScheme ```scheme ;; ==================================================================== ;; Transitive Reachability in ImpScheme (.impscm) ;; ==================================================================== (program (fixpoint "FOLLOWS" 100 (csr-walk "FOLLOWS")) (collect-bitset)) ``` --- ## 4. Automatic Vector Fusion Passes The ImpScheme compiler performs algebraic AST optimization passes before bytecode emission and register allocation. ### Example: Fusing Consecutive 1-Hop Walks into `OP_CSR_WALK_2HOP` When the compiler encounters two consecutive 1-hop walks over low-multiplicity relations: ```scheme (program (csr-walk "ORDER_CONTAINS_PRODUCT") (csr-walk "PRODUCT_HAS_TAG") (collect-bitset)) ``` The Stage 2 optimizer pass fuses them into a single 2-hop kernel: ```scheme (program (csr-walk-2hop "ORDER_CONTAINS_PRODUCT" "PRODUCT_HAS_TAG") (collect-bitset)) ``` Emitting `OP_CSR_WALK_2HOP` to traverse both hops without materializing an intermediate bitset. --- ## 5. Compiling & Executing ImpScheme Using the `impulse-graph` CLI: ```bash # 1. Compile .impscm source to canonical .impas assembly text impulse-graph compile reachability.impscm -o reachability.impas # 2. Assemble .impas text into binary bytecode (.impb) impulse-graph assemble -i reachability.impas -o reachability.impb # 3. Execute compiled bytecode program against a snapshot impulse-graph run --snapshot production.imps --bytecode reachability.impb ``` impulse assemble -i reachability.impas -o reachability.impb # 4. Execute query program against snapshot impulse run --snapshot production.imps --bytecode reachability.impb --input-val 1042 ``` ================================================================================ FILE: docs/ecosystems/index.md | URL: https://www.impulsegraph.org/ecosystems/ ================================================================================ # Ecosystems, Runtimes & Developer Hubs **Impulse Graph Engine** separates graph storage, schema contracts, and execution semantics from any single host programming language. Rather than wrapping one monolithic server or forcing every ecosystem through a foreign-function bottleneck, Impulse pairs an **open specification layer** with **pluggable, idiomatic execution runtimes**. ```mermaid flowchart TD subgraph Spec["Open Normative Layer (Language-Neutral)"] IMPS[".imps Binary Snapshot Format (4KB Page 0, 128B CSR/CSC/SoA)"] YAML[".imps.schema.yaml Structural Schema Contract"] ISA["impOps 64-Bit Register Bytecode ISA (R0..R63)"] end Spec --> JVM["Java & JVM Enterprise Runtime (Pure Java 21 LTS / 25+ FFM & Vector API)"] Spec --> PY["Python, Data Science & ML Track (pybind11 + C++20 Kernel, NumPy/PyTorch)"] Spec --> NAT["Native Systems & Polyglot C-ABI (C++20, Rust, Go, .NET, Node.js)"] Spec --> OCAML["Normative Verification Oracle (Pure Functional OCaml & ICTX v1)"] ``` --- ## Shared Architectural Foundation Every runtime track in the ecosystem operates directly against three identical, versioned artifacts: 1. **[Impulse Binary Snapshot (`.imps`)](../reference/spec/format-specification.md)**: An immutable, 4KB-page-aligned and 128-byte-section-aligned file containing per-domain catalogs, CSR/CSC adjacency arrays, Structure-of-Arrays (SoA) node and edge columns, optional Section 2.6 Vamana ANN indices, and a trailing SHA-256 checksum. Any `.imps` file built in Python, Rust, or C++ mounts without conversion in pure Java—and vice versa. 2. **[Declarative Schema Contract (`.imps.schema.yaml`)](../reference/spec/schema-specification.md)**: Defines disjoint node domains ($0 \dots N_d - 1$), primary key types, typed relations, traversal directions (`[out, in]`), and nullable/optional evolution rules enforced both at build time and prior to live snapshot swaps. 3. **[`impOps` Bytecode ISA & Multi-Frontend Compiler](../reference/spec/vm-specification.md)**: Queries written in `openCypher`, `ImpK`, `ImpLog`, `CEL`, or fluent language SDKs lower through the homoiconic `ImpScheme` (`.impscm`) IR into packed 64-bit `impOps` (`.impb`) register instructions. --- ## Runtime & Ecosystem Track Matrix Choose the developer hub matching your primary deployment environment and toolchain: | Ecosystem Track | Execution Engine & Memory Model | Build & CLI Tooling | Primary Workloads | Developer Hub | | :--- | :--- | :--- | :--- | :--- | | **1. Java & JVM Enterprise** | **100% Pure Java 21 LTS / 25+** (`java.lang.foreign` FFM + `jdk.incubator.vector`). Zero JNI, zero `.so`/`.dylib` native libraries, zero third-party runtime dependencies in core modules. | `impulse-bom`, `impulse-maven-plugin` (7 Mojos), `impulse-codegen` AOT builders, pure-Java `impulse-j` CLI, Kotlin / Scala 3 / Clojure DSLs. | Spring Boot / Quarkus / gRPC services, ReBAC authorization, AML screening, Kubernetes zero-downtime hot-swap (`SnapshotLifecycleManager`). | **[Java & JVM Hub](java/index.md)** | | **2. Python, Data Science & ML** | Pre-built **`pybind11` wheels** (`pip install impulse-graph`) embedding the C++20 SIMD kernel (`libimpulse_graph_static`). | `impulse build` Parquet/CSV compiler, zero-copy `memoryview` / NumPy / SciPy CSR / PyTorch tensor views. | Graph analytics notebooks, disk-backed GNN neighbor sampling over multi-hundred-GB graphs, GraphRAG & Vamana ANN vector retrieval. | **[Python & ML Hub](python/index.md)** | | **3. Native Systems & Polyglot C-ABI** | Zero-dependency **C++20 / Highway SIMD kernel** (`libimpulse_graph`), self-contained **Rust** crate, Go (CGo), .NET 8+ (P/Invoke), Node.js (N-API). | Native **`impulse-graph` (`impulse`) CLI** with Parquet ingestion, RCM / Vamana-locality reordering, and Ed25519 signing. | Embedded systems, Rust services, high-density C++ engines, power-grid contingency simulation, CI data pipelines. | **[Native & C-ABI Hub](native/index.md)** | | **4. Normative Verification Oracle** | Pure functional **OCaml** reference interpreter (`impulse-ocaml`) computing canonical `ICTX` v1 state hashes. | Four-Way Polyglot Validation Suite (`four_way_validation.py`) & differential contract fuzzer. | Formal ISA semantics, cross-engine bitwise parity verification across C++ (`-O3` / `-O0`), Java 25, and OCaml. | **[Polyglot Validation](../contributing/polyglot-validation.md)** | --- ## Cross-Ecosystem Interoperability in Practice Because `.imps` snapshots and `.imps.schema.yaml` contracts are strictly host-independent, production teams routinely mix tracks across their data and serving tiers: * **Python / Native Data Plane → Pure Java Serving Plane**: An Airflow, Spark, or dbt job compiles Parquet exports from Snowflake/BigQuery into an RCM-reordered `.imps` file using the native `impulse build` CLI (see [Snapshots from Parquet & CSV](python/snapshots-from-parquet-csv.md)) and uploads it to S3 or GCS. Stateless Java 25 microservices poll the bucket via `SnapshotLifecycleManager`, validate structural compatibility against their compiled `.imps.schema.yaml` contract, and atomically swap epochs with zero JNI dependencies in the serving container. * **Java JDBC Ingestion → Python ML Training**: A Java batch job streams relational tables via `SnapshotBuilder` or `CsvManifestSnapshotBuilder` (see [Building Snapshots in Java](java/building-snapshots.md)), producing an `.imps` artifact that data scientists immediately memory-map in Python for PyTorch Geometric training or hybrid vector/graph retrieval (see [AI & GraphRAG Overview](../ai/index.md)). --- ## Extensibility to Future Runtime Tracks Decoupling the binary data layout (`.imps`) and instruction set (`impOps`) from any single language runtime makes the architecture cleanly extensible to new execution environments without changing existing data pipelines, schemas, or queries: * **Pure Managed `.NET` Runtime Track**: A pure C# implementation built on `System.IO.MemoryMappedFiles.MemoryMappedFile`, `Span`, and `System.Runtime.Intrinsics.Vector512` can mount `.imps` files directly without P/Invoke native binaries. * **WebAssembly (`wasm32` SIMD128) Edge & Browser Track**: A compact `wasm32` `ImpulseVM` runtime using 128-bit WebAssembly SIMD instructions can execute `.impb` programs directly over range-fetched or OPFS-mounted `.imps` snapshots inside Cloudflare Workers or browser tabs. Any new runtime implementation achieves full ecosystem compatibility by passing the normative **531-vector `ImpulseVM` compliance suite** (`impulse-graph-spec/test-vectors/`) and matching the OCaml oracle's `ICTX` v1 register, flag, and status hashes bit-for-bit. --- ## Where to Go Next * **Evaluating architectural fit?** Read **[Embedded Snapshot Engine vs. Graph Databases](../getting-started/embedded-vs-graph-db.md)** and **[Changing Data & Live Updates](../getting-started/handling-mutations.md)**. * **Building on the JVM?** Enter the **[Java & JVM Enterprise Hub](java/index.md)**. * **Working with Parquet, Pandas, or PyTorch?** Enter the **[Python, Data Science & ML Hub](python/index.md)**. * **Integrating C++20, Rust, Go, or the native CLI?** Enter the **[Native Systems & C-ABI Hub](native/index.md)**. * **Looking for Maven Central, PyPI, or crates.io coordinates?** See **[Packages & Distribution](../reference/packages.md)**. ================================================================================ FILE: docs/ecosystems/java/index.md | URL: https://www.impulsegraph.org/ecosystems/java/ ================================================================================ # Java & JVM Enterprise Hub `impulse-graph-java` (`org.impulsegraph`) is a **100% pure Java** implementation of the Impulse Graph Engine, `ImpulseVM`, multi-frontend query compiler, and streaming snapshot builder targeting **Java 21 LTS** and **Java 22+ / Java 25 LTS**. It mounts `.imps` binary snapshots directly off-heap using the JDK Foreign Function & Memory (FFM) API (`java.lang.foreign.MemorySegment`, `Arena`) and executes vectorized CSR/CSC walks and attribute filters via the JDK Vector API (`jdk.incubator.vector`) and `MethodHandle` C2 JIT combinators. --- ## Why Pure Java FFM (Zero JNI)? Enterprise JVM teams traditionally face an architectural tradeoff when embedding high-throughput engines such as RocksDB or DuckDB: JNI wrappers bundle platform-specific `.so` / `.dylib` / `.dll` binaries (`glibc` vs. `musl`, `x86_64` vs. `aarch64`), opaque native C++ allocators invisible to JFR, and native library CVE surface area. `impulse-graph-java` eliminates JNI completely: * **Zero Native Binaries**: Pure `.jar` artifacts run identically on Linux (`glibc` and `musl`/Alpine), macOS (`arm64`/`x86_64`), and Windows without native shared libraries. * **Zero Third-Party Runtime Dependencies**: Core runtime modules (`impulse-spec`, `impulse-api`, `impulse-storage`, `impulse-vm`, `impulse-compiler`, `impulse-builder`) depend strictly on `java.*` and `jdk.incubator.vector`—zero Jackson, Guava, Netty, or Protobuf version conflicts on your application classpath. * **Empirical C++ Parity & Zero-Allocation Hot Path**: Because CSR/CSC traversals over 128-byte-aligned segments are memory-bandwidth bound, warmed-up Java 25 executes within **`1.65x`** of the 10-thread C++20 kernel on the 1.47B-edge `twitter-2010` BFS benchmark (`240.29 ms` Java vs. `145.00 ms` C++) with `0.00 ms` GC pauses. * **Sub-Microsecond Service Latency**: On a 600,000-user enterprise ReBAC directory benchmark, JFR profiling records **`0.026 µs – 0.552 µs`** per multi-hop authorization check—`3.5x` to `73x` less CPU time than Jackson JSON response serialization (`1.91 µs – 2.56 µs`). See [Benchmarks](../../benchmarks.md) and [JVM Ecosystem Comparison](../../benchmarks/jvm-ecosystem-comparison.md). --- ## Module Architecture & Bill of Materials (`impulse-bom`) !!! info "Version Note: v0.11 Tooling Suite" Core runtime and JVM language artifacts (`impulse-spec`, `impulse-api`, `impulse-storage`, `impulse-vm`, `impulse-compiler`, `impulse-builder`, `impulse-kotlin`, `impulse-scala_3`, `impulse-clojure`) are published on Maven Central at **`0.10.0`**. The enterprise developer tooling suite—**`impulse-bom`**, **`impulse-codegen` v2**, **`impulse-maven-plugin`** (7-Mojo lifecycle suite), **`impulse-cli`** (`impulse-j`), **`SchemaYamlCodec`**, and **`SnapshotLifecycleManager`**—ships in **`0.11.0`** (`v0.11`). ```mermaid flowchart TD BOM["impulse-bom (Maven / Gradle BOM)"] subgraph Runtime["Zero-Dependency Core Runtime"] SPEC["impulse-spec (v0.9 / v0.10 FFM Layouts)"] API["impulse-api (Snapshot, DomainView, Schema & Lifecycle SPIs)"] STOR["impulse-storage (BinarySnapshotLoader, SnapshotContractValidator, Health)"] VM["impulse-vm (ImpulseVM, MethodHandle JIT, SnapshotLifecycleManager)"] COMP["impulse-compiler (Cypher, ImpK, ImpLog, CEL, SchemaBindValidatorPass)"] end subgraph BuildAndTooling["Ingestion, AOT Codegen & Build Tooling"] BLD["impulse-builder (SnapshotBuilder, CsvManifestSnapshotBuilder)"] CG["impulse-codegen (SchemaCodeEmitter v2 Typed Builders & RowViews)"] CLI["impulse-cli (impulse-j Pure-Java CLI)"] MVN["impulse-maven-plugin (7-Goal Build & CI Verification Plugin)"] end subgraph Langs["Idiomatic JVM Language Extensions"] KT["impulse-kotlin"] SC["impulse-scala_3"] CLJ["impulse-clojure"] end BOM -.-> Runtime BOM -.-> BuildAndTooling BOM -.-> Langs STOR --> API & SPEC VM --> STOR & API COMP --> VM & API BLD --> SPEC & API CG --> STOR & API CLI --> CG & COMP & BLD & VM MVN --> CLI & CG KT & SC & CLJ --> API ``` | Artifact (`org.impulsegraph`) | Scope | Third-Party Runtime Deps | Purpose | | :--- | :--- | :--- | :--- | | **`impulse-bom`** *(v0.11)* | `import` | None | Aligns versions across all `org.impulsegraph` modules. | | **`impulse-api`** | `compile` | **Zero** | Public interfaces (`ImpulseGraphSnapshot`, `DomainView`, `Traversal`, `ImpulseStatement`, `SchemaYamlCodec`, `SnapshotResolver`). | | **`impulse-spec`** | `runtime` | **Zero** | Binary Snapshot Format FFM memory layouts and constants. | | **`impulse-storage`** | `compile` / `runtime` | **Zero** | `BinarySnapshotLoader`, `SnapshotSwapManager`, `SnapshotContractValidator`, `SnapshotSchemaExtractor`, `ImpulseHealthIndicator`. | | **`impulse-vm`** | `runtime` | **Zero** | `ImpulseVmInterpreter`, `ImpulseMethodHandleCompiler`, multi-lane handlers, and `SnapshotLifecycleManager`. | | **`impulse-compiler`** | `runtime` | **Zero** | `openCypher`, `ImpK`, `ImpLog`, `ImpScheme`, and `CEL` compilers, optimizer passes, and `QueryRegistry`. | | **`impulse-builder`** | `compile` (ETL / tests) | **Zero** | Off-heap streaming `SnapshotBuilder` and `CsvManifestSnapshotBuilder`. | | **`impulse-codegen`** *(v0.11)* | Build-time | **Zero** | Emits zero-dependency schema-typed Java wrappers, traversals, CEL metamodels, and flyweight `RowView` cursors. | | **`impulse-cli`** *(v0.11)* | CLI / CI | `info.picocli:picocli` | Pure-Java `impulse-j` CLI jar and launcher script. | | **`impulse-maven-plugin`** *(v0.11)* | Maven `` | Maven Plugin API | AOT codegen (`generate`), query validation (`aot-compile`), test fixture builds, and compatibility gates. | | **`impulse-kotlin`** / **`impulse-scala_3`** / **`impulse-clojure`** | `compile` | Language stdlib | Idiomatic Kotlin Coroutines, Scala 3 context functions/opaque types, and Clojure homoiconic macros. | --- ## JDK 21 LTS vs. JDK 22+ / JDK 25 LTS Flag Matrix Impulse Graph relies on two modern JDK subsystems: 1. **Foreign Function & Memory API (`java.lang.foreign.Arena`, `MemorySegment`)**: Finalized as a standard API in **JDK 22 (JEP 454)**. In **JDK 21 LTS**, FFM is a preview API (JEP 442) and therefore requires `--enable-preview`. Calling `FileChannel.map` / restricted FFM operations requires `--enable-native-access=ALL-UNNAMED` at runtime. 2. **Vector API (`jdk.incubator.vector`)**: Remains an incubator module across JDK 21–25 and requires `--add-modules jdk.incubator.vector` at both compile time and runtime. | Target JDK | `javac` Compiler Flags | `java` Runtime / Test Runner Flags | Notes | | :--- | :--- | :--- | :--- | | **JDK 21 LTS** | `--release 21 --enable-preview --add-modules jdk.incubator.vector` | `--enable-preview --add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED` | FFM (`Arena` / `MemorySegment`) is a preview API in JDK 21 (JEP 442). | | **JDK 22 – 24** | `--release 22 --add-modules jdk.incubator.vector` | `--add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED` | **No `--enable-preview` required**—FFM was finalized in JEP 454. | | **JDK 25 LTS (Recommended)** | `--release 25 --add-modules jdk.incubator.vector` | `--add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED` | Supports Project Leyden AOT Class/Method Caching (`-XX:AOTCache=impulse.aotcache`) for `< 10 ms` cold start. | !!! tip "Compiler vs. Runtime Flag Distinction" `--enable-native-access=ALL-UNNAMED` is strictly a **`java` JVM runtime flag**—do not pass it to `javac`, which rejects unknown launcher flags. Conversely, `--add-modules jdk.incubator.vector` is required by both `javac` (when compiling code referencing vector types) and `java`. --- ## Copy-Paste Build, IDE & Container Setup === "Maven (`pom.xml`)" ```xml 0.11.0 org.impulsegraph impulse-bom ${impulse.version} pom import org.impulsegraph impulse-api org.impulsegraph impulse-storage org.impulsegraph impulse-vm org.impulsegraph impulse-compiler org.apache.maven.plugins maven-compiler-plugin 3.13.0 25 --add-modules jdk.incubator.vector org.apache.maven.plugins maven-surefire-plugin 3.5.2 @{argLine} --add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED org.apache.maven.plugins maven-failsafe-plugin 3.5.2 @{argLine} --add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED ``` === "Gradle Kotlin DSL (`build.gradle.kts`)" ```kotlin plugins { java application } val impulseVersion = "0.11.0" // or "0.10.0" on Maven Central today java { toolchain { languageVersion.set(JavaLanguageVersion.of(25)) // or 21 for JDK 21 LTS } } dependencies { implementation(platform("org.impulsegraph:impulse-bom:$impulseVersion")) implementation("org.impulsegraph:impulse-api") implementation("org.impulsegraph:impulse-storage") implementation("org.impulsegraph:impulse-vm") implementation("org.impulsegraph:impulse-compiler") } val isJdk21 = java.toolchain.languageVersion.get().asInt() == 21 tasks.withType().configureEach { options.compilerArgs.addAll( buildList { if (isJdk21) add("--enable-preview") add("--add-modules") add("jdk.incubator.vector") } ) } tasks.withType().configureEach { useJUnitPlatform() jvmArgs( buildList { if (isJdk21) add("--enable-preview") add("--add-modules=jdk.incubator.vector") add("--enable-native-access=ALL-UNNAMED") } ) } tasks.withType().configureEach { jvmArgs( buildList { if (isJdk21) add("--enable-preview") add("--add-modules=jdk.incubator.vector") add("--enable-native-access=ALL-UNNAMED") } ) } ``` === "IntelliJ IDEA" When importing a Maven or Gradle project configured as above, IntelliJ IDEA automatically picks up compiler arguments from `maven-compiler-plugin` / `JavaCompile`. If running `main()` classes or JUnit tests directly via the IntelliJ runner rather than delegated Maven/Gradle execution: 1. **Compiler Settings** (*Settings → Build, Execution, Deployment → Compiler → Java Compiler*): Under **Override compiler parameters per-module** (or **Additional command line parameters**), ensure: ```text --add-modules jdk.incubator.vector ``` *(Add `--enable-preview` if Project SDK is JDK 21).* 2. **Run / Debug & JUnit Template VM Options** (*Run → Edit Configurations → Edit configuration templates... → JUnit / Application → Modify options → Add VM options*): ```text --add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED ``` *(Add `--enable-preview` if running on JDK 21).* === "Production Container (`Dockerfile`)" Keep `-Xmx` lean (`2g–4g`) so container memory stays available to the Linux page cache backing read-only `mmap` `.imps` snapshots (see [Kubernetes Memory Sizing](kubernetes-and-lifecycle.md#4-kubernetes-memory-sizing-avoiding-the-cgroups-v2-mmap-oomkilled-trap)): ```dockerfile FROM eclipse-temurin:25-jre-noble WORKDIR /app COPY target/my-graph-service.jar /app/app.jar # Generational ZGC + Vector API + FFM native access + lean heap ENV JAVA_TOOL_OPTIONS="--add-modules jdk.incubator.vector \ --enable-native-access=ALL-UNNAMED \ -Xms2g -Xmx4g \ -XX:+UseZGC -XX:+ZGenerational" ENTRYPOINT ["java", "-jar", "/app/app.jar"] ``` **Optional JDK 25 Project Leyden AOT Warmup (`< 10 ms` Cold Start)**: ```bash # Step 1 (CI / Docker build): Record AOT class & method profile java -XX:AOTMode=record -XX:AOTConfiguration=impulse.aotconf -jar /app/app.jar --warmup-exit java -XX:AOTMode=create -XX:AOTConfiguration=impulse.aotconf -XX:AOTCache=impulse.aotcache -jar /app/app.jar # Step 2 (Production entrypoint): Mount pre-compiled AOT cache java -XX:AOTCache=impulse.aotcache -jar /app/app.jar ``` --- ## Day-1 to Day-2 Developer Guide Map Follow this sequence to go from raw relational/CSV data to a zero-downtime Kubernetes service: | Stage | Guide | What You Will Build | | :--- | :--- | :--- | | **1. Data Ingestion** | **[Building Snapshots in Java](building-snapshots.md)** | Stream PostgreSQL/JDBC result sets via `SnapshotBuilder` or compile CSV/TSV/JSONL manifests in pure Java via `CsvManifestSnapshotBuilder`. | | **2. Type-Safe APIs** | **[Schema-First Development & AOT Codegen](aot-codegen.md)** | Author `.imps.schema.yaml` contracts (or extract them from `.imps` files) and generate domain-distinct `Id` records, typed `Traversal` builders, CEL metamodels, and zero-allocation `RowView` cursors. | | **3. Build & CI Gates** | **[Maven Plugin & Build-Time AOT Pipeline](maven-and-build-tooling.md)** | Wire all 7 `impulse-maven-plugin` goals (`generate`, `generate-test`, `aot-compile`, `build-snapshot`, `extract-schema`, `validate`, `check-compat`) into `mvn verify`. | | **4. CLI & Inspection** | **[Pure-Java CLI (`impulse-j`)](cli-impulse-j.md)** | Run `build`, `inspect`, `validate`, `stats`, `schema check-compat`, `codegen`, `compile`, `explain`, and `run` on any JVM without native binaries. | | **5. Production Ops** | **[Kubernetes, Hot-Swap Lifecycle & Schema Evolution](kubernetes-and-lifecycle.md)** | Configure `SnapshotLifecycleManager`, K8s startup/readiness/liveness probes, rolling `Expand -> Migrate -> Contract` schema evolution, and `cgroups v2` memory limits. | | **6. Polyglot JVM & Core SDK** | **[Kotlin, Scala 3, Clojure & Java API](jvm-languages.md)** · **[Java SDK Reference](../../reference/java-api.md)** | Combine AOT-generated classes with Kotlin Coroutines, Scala 3 context functions, Clojure S-expressions, and low-level `ImpulseVM` APIs. | ================================================================================ FILE: docs/ecosystems/java/building-snapshots.md | URL: https://www.impulsegraph.org/ecosystems/java/building-snapshots/ ================================================================================ # Building Snapshots in Java This guide covers building immutable `.imps` binary snapshots in pure Java using **`org.impulsegraph:impulse-builder`**. Depending on where your source data lives, Java provides two zero-dependency build paths: 1. **Programmatic Streaming (`SnapshotBuilder`)**: Stream rows directly from PostgreSQL/MySQL/Oracle via JDBC, Kafka state stores, or custom Java pipelines in bounded $O(\text{chunk})$ off-heap memory. 2. **Declarative Manifest Building (`CsvManifestSnapshotBuilder`)**: Compile CSV, TSV, and JSONL node/edge files from a declarative YAML or JSON manifest in pure Java without installing native binaries. If you haven't already, read [Core Concepts](../../getting-started/core-concepts.md) first for an overview of CSR/CSC adjacency layouts and per-domain dense ID spaces. !!! tip "Building from Apache Parquet or Attaching Vamana Vector Indices?" If your upstream tables are stored in **Apache Parquet**, `.npy` / `.safetensors` embeddings, or require offline RCM / Vamana ANN index construction, use the standalone native CLI (`impulse build`) documented in **[Snapshots from Parquet & CSV (CLI & Python)](../python/snapshots-from-parquet-csv.md)**. Because `.imps` is language-neutral, snapshots built by the native CLI mount directly in pure Java with zero conversion. --- ## What Are We Building? Our relational database has four tables for a banking transfer graph: | Table | Columns | | :--- | :--- | | `users` | `user_id BIGINT`, `name VARCHAR`, `age INT` | | `accounts` | `account_id BIGINT`, `balance DOUBLE` | | `user_accounts` | `user_id BIGINT`, `account_id BIGINT` | | `account_transfers` | `from_account_id BIGINT`, `to_account_id BIGINT`, `amount DOUBLE` | !!! note In a production banking schema, `account_transfers` also carries `timestamp` (`TIMESTAMP_MS`), `currency`, and `transfer_type`. Each column attaches to `TRANSFERRED_TO` as its own 128-byte-aligned Structure-of-Arrays (SoA) edge attribute column. Here we attach `amount` (`DataType.F64`) to keep the walkthrough concise. Target graph topology: ```text (User: 101) ──[:OWNS]──> (Account: 5001) ──[:TRANSFERRED_TO {amount: 2500.00}]──> (Account: 7008) ``` Once built, we memory-map the `.imps` file and execute engine-native queries such as *"Which accounts received transfers over \$1,000 from accounts owned by User 101?"*. --- ## Project Dependencies & JVM Flags Import `impulse-bom` (see the [Java & JVM Enterprise Hub](index.md#copy-paste-build-ide-container-setup) for full Maven/Gradle setup) and add `impulse-builder` alongside the core runtime modules: ```xml org.impulsegraph impulse-builder org.impulsegraph impulse-api org.impulsegraph impulse-storage org.impulsegraph impulse-vm ``` At runtime, pass `--add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED` to `java` (plus `--enable-preview` if running on **JDK 21 LTS**). --- ## Part 1: Programmatic JDBC Streaming (`SnapshotBuilder`) ### Step 1: Define Domains & Understand Natural Keys vs. Dense IDs Entities in Impulse Graph are partitioned into **Domains** (here `User` and `Account`). Every domain has its own independent, contiguous 0-indexed dense ID space $0 \dots N_d - 1$, allowing CSR `row_offsets[]` and SoA attribute arrays to use direct array indexing with zero hash lookups. !!! warning "Natural Keys vs. Ephemeral Dense IDs (0 .. N_d - 1)" Dense node IDs ($0 \dots N_d - 1$) are **ephemeral physical array indices** valid only for a single `.imps` snapshot revision. Whenever a snapshot is rebuilt—or reordered offline via Reverse Cuthill-McKee (`--rcm`) or degree sorting—a user's dense ID changes as rows are inserted or deleted. **Architectural Rule**: Never persist raw Impulse dense IDs into PostgreSQL, Kafka events, caches, or external API responses. Always persist your domain's immutable **natural business keys** (`UUID`, `Long`, or `String`) and translate at the query boundary via `.fromKey(...)` / `.toKeyList()` (or typed AOT `DomainView` methods—see [Schema-First AOT Codegen](aot-codegen.md)). During programmatic JDBC ingestion, **`IdMapper`** (`LongIdMapper`, `UuidIdMapper`, `StringIdMapper`, `BytesIdMapper`) maps database primary keys to sequential dense IDs as you scan the domain table: !!! important The `ORDER BY` in the domain scan query determines dense ID assignment order ($0, 1, 2, \dots$). When streaming CSR edges in a single pass (Step 4), the edge SQL query **must** `ORDER BY` its source foreign key in the exact same order so source dense IDs arrive monotonically non-decreasing. ```java import org.impulsegraph.api.IdMapper; import org.impulsegraph.api.LongIdMapper; import org.impulsegraph.builder.api.DomainDefinition; import org.impulsegraph.builder.api.PrimitiveWidth; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; IdMapper userMapper = new LongIdMapper("User"); long denseId = 0; try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT user_id FROM users ORDER BY user_id")) { while (rs.next()) { userMapper.registerMapping(rs.getLong("user_id"), denseId++); } } DomainDefinition userDomain = DomainDefinition.builder(userMapper.size()) .idWidth(PrimitiveWidth.UINT32) // UINT16 (<=65,535), UINT32 (<=4.29B), or UINT64 .build(); ``` ### Step 2: Add the `Account` Domain Apply the same pattern to `Account`: ```java IdMapper accountMapper = new LongIdMapper("Account"); long accDenseId = 0; try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT account_id FROM accounts ORDER BY account_id")) { while (rs.next()) { accountMapper.registerMapping(rs.getLong("account_id"), accDenseId++); } } DomainDefinition accountDomain = DomainDefinition.builder(accountMapper.size()) .idWidth(PrimitiveWidth.UINT32) .withPrimaryKeyIndex(true) .primaryKeyAttribute("account_id") .addAttribute("account_id", accountKeySource) // Optional AttributeDataSource for embedded key lookup .addAttribute("balance", accountBalanceSource) // Optional SoA node attribute column .build(); ``` !!! note "Disjoint Per-Domain ID Spaces" Dense ID `0` in `User` is distinct from and unrelated to dense ID `0` in `Account`. Every relation explicitly binds a `sourceDomain` and `targetDomain`. #### Domains Without Attributes & High-Cardinality Memory Sizing If a domain requires neither node attributes nor embedded key dictionaries, only its node count is required (`DomainDefinition.builder(accountCount).idWidth(PrimitiveWidth.UINT32).build()`). When sizing builder memory for large graphs: * **Off-Heap Topology & Column Streaming (`StreamingSnapshotWriter` & `ExternalSortStaging`)**: Streams pre-mapped dense IDs in fixed-size off-heap `MemorySegment` chunks (`65,536` edges per chunk) and spills intermediate CSC sort runs to disk whenever the staging buffer reaches `.withStagingMemoryLimit(...)` (default **64 MB**). * **In-Memory `IdMapper` Reference Classes**: `LongIdMapper`, `UuidIdMapper`, and `StringIdMapper` hold two `ConcurrentHashMap` instances on the Java heap (~120–200+ bytes per node), suitable up to ~10M–50M nodes depending on `-Xmx`. * **Scaling Beyond 100M Nodes**: Pre-compute dense IDs in SQL/warehouse views (`ROW_NUMBER() OVER (ORDER BY id) - 1 AS dense_id`), implement `IdMapper` over an off-heap sorted `MemorySegment` binary-search table, or run `impulse build` over Parquet exports (see [Snapshots from Parquet & CSV](../python/snapshots-from-parquet-csv.md)). --- ### Step 3: Stream Edges & Columnar Attributes via `RelationDataSource` Rather than allocating Java edge objects on the heap, `SnapshotBuilder` pulls batches of primitive IDs into reusable off-heap `MemorySegment` buffers via **`RelationDataSource`** and **`EdgeChunkIterator`**. Remember to call `stmt.setFetchSize(10_000)` so the JDBC driver streams rows instead of buffering the entire table in heap memory: ```java package com.example.builder; import org.impulsegraph.api.IdMapper; import org.impulsegraph.builder.spi.EdgeChunkIterator; import org.impulsegraph.builder.spi.RelationDataSource; import java.lang.foreign.MemorySegment; import java.lang.foreign.ValueLayout; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcRelationDataSource implements RelationDataSource { private final Connection connection; private final String edgeQuery; private final long edgeCount; private final IdMapper sourceMapper; private final IdMapper targetMapper; public JdbcRelationDataSource(Connection connection, String countQuery, String edgeQuery, IdMapper sourceMapper, IdMapper targetMapper) throws SQLException { this.connection = connection; this.edgeQuery = edgeQuery; this.sourceMapper = sourceMapper; this.targetMapper = targetMapper; try (Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(countQuery)) { if (!rs.next()) { throw new IllegalStateException("Count query returned 0 rows"); } this.edgeCount = rs.getLong(1); } } @Override public long getEdgeCount() { return edgeCount; } @Override public EdgeChunkIterator getEdges() { try { PreparedStatement stmt = connection.prepareStatement( edgeQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(10_000); ResultSet rs = stmt.executeQuery(); return new EdgeChunkIterator() { private boolean hasNextRow = rs.next(); @Override public boolean hasNext() { return hasNextRow; } @Override public int nextChunk(MemorySegment srcIds, MemorySegment tgtIds, int limit) { int count = 0; try { int sWidth = limit > 0 ? (int) (srcIds.byteSize() / limit) : 4; int tWidth = limit > 0 ? (int) (tgtIds.byteSize() / limit) : 4; while (hasNextRow && count < limit) { long srcDenseId = sourceMapper.getId(rs.getLong(1)); long tgtDenseId = targetMapper.getId(rs.getLong(2)); if (sWidth == 2) { srcIds.setAtIndex(ValueLayout.JAVA_SHORT_UNALIGNED, count, (short) srcDenseId); } else if (sWidth == 8) { srcIds.setAtIndex(ValueLayout.JAVA_LONG_UNALIGNED, count, srcDenseId); } else { srcIds.setAtIndex(ValueLayout.JAVA_INT_UNALIGNED, count, (int) srcDenseId); } if (tWidth == 2) { tgtIds.setAtIndex(ValueLayout.JAVA_SHORT_UNALIGNED, count, (short) tgtDenseId); } else if (tWidth == 8) { tgtIds.setAtIndex(ValueLayout.JAVA_LONG_UNALIGNED, count, tgtDenseId); } else { tgtIds.setAtIndex(ValueLayout.JAVA_INT_UNALIGNED, count, (int) tgtDenseId); } count++; hasNextRow = rs.next(); } } catch (SQLException e) { throw new RuntimeException("Error reading JDBC edge row", e); } return count; } @Override public void close() throws Exception { rs.close(); stmt.close(); } }; } catch (SQLException e) { throw new RuntimeException("Failed to initiate JDBC edge stream", e); } } } ``` Stream the `amount` edge attribute in the **exact same SQL `ORDER BY` sequence** (`ORDER BY from_account_id, to_account_id`) via **`AttributeDataSource`** so element $k$ in `amount[]` aligns with edge $k$ in CSR `col_indices[]`: ```java import org.impulsegraph.builder.api.DataType; import org.impulsegraph.builder.api.Nullability; import org.impulsegraph.builder.spi.AttributeChunkIterator; import org.impulsegraph.builder.spi.AttributeDataSource; AttributeDataSource transferAmountSource = new AttributeDataSource() { @Override public DataType dataType() { return DataType.F64; } @Override public Nullability nullability() { return Nullability.NON_NULL; } @Override public AttributeChunkIterator iterator() { try { PreparedStatement stmt = conn.prepareStatement( "SELECT amount FROM account_transfers ORDER BY from_account_id, to_account_id", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(10_000); ResultSet rs = stmt.executeQuery(); return new AttributeChunkIterator() { private boolean hasNextRow = advanceOrClose(); private boolean advanceOrClose() { try { boolean more = rs.next(); if (!more) { rs.close(); stmt.close(); } return more; } catch (SQLException e) { throw new RuntimeException("Error advancing transfer amount cursor", e); } } @Override public boolean hasNext() { return hasNextRow; } @Override public int nextChunk(MemorySegment destination, int limit) { int count = 0; try { while (hasNextRow && count < limit) { destination.setAtIndex(ValueLayout.JAVA_DOUBLE_UNALIGNED, count, rs.getDouble(1)); count++; hasNextRow = advanceOrClose(); } } catch (SQLException e) { throw new RuntimeException("Error reading transfer amount", e); } return count; } }; } catch (SQLException e) { throw new RuntimeException("Failed to stream transfer amounts", e); } } }; ``` --- ### Step 4: Configure Relations & Write the Snapshot Bind CSR (forward `.out(...)`) and optional CSC (reverse `.in(...)`) topologies to each `RelationDefinition`, attach `transferAmountSource`, stamp schema provenance metadata, and stream the `.imps` file to disk or directly to an S3/GCS `OutputStream`: ```java import org.impulsegraph.builder.api.CompressionScheme; import org.impulsegraph.builder.api.RelationDefinition; import org.impulsegraph.builder.api.SnapshotBuilder; import org.impulsegraph.builder.api.Topology; import java.nio.file.Path; import java.time.Instant; RelationDataSource ownsDataSource = new JdbcRelationDataSource( conn, "SELECT COUNT(*) FROM user_accounts", "SELECT user_id, account_id FROM user_accounts ORDER BY user_id", userMapper, accountMapper ); RelationDataSource transferDataSource = new JdbcRelationDataSource( conn, "SELECT COUNT(*) FROM account_transfers", "SELECT from_account_id, to_account_id FROM account_transfers ORDER BY from_account_id, to_account_id", accountMapper, accountMapper ); RelationDefinition ownsRelation = RelationDefinition.builder("User", "Account") .addTopology(Topology.CSR, CompressionScheme.RAW) .addTopology(Topology.CSC, CompressionScheme.RAW) .dataSource(ownsDataSource) .build(); RelationDefinition transferRelation = RelationDefinition.builder("Account", "Account") .addTopology(Topology.CSR, CompressionScheme.RAW) .addTopology(Topology.CSC, CompressionScheme.RAW) .addAttribute("amount", transferAmountSource) .dataSource(transferDataSource) .build(); SnapshotBuilder.create() .withVersion((short) 10) .withStagingDirectory(Path.of("/tmp/impulse_staging")) .withStagingMemoryLimit(64 * 1024 * 1024L) // 64 MB external-sort spill threshold .addDomain("User", userDomain) .addDomain("Account", accountDomain) .addRelation("OWNS", ownsRelation) .addRelation("TRANSFERRED_TO", transferRelation) .withSchemaProvenance("BankGraph", "1.0.0", null) .addFooterMetadata("sys.build.generator", "BankGraphJdbcPipeline") .addFooterMetadata("sys.build.timestamp", Instant.now().toString()) .writeTo(Path.of("datasets/bank_graph.imps")); ``` !!! tip "Type-Safe Generated Writer (`SnapshotWriter`)" If you define a `.imps.schema.yaml` contract, `impulse-codegen` generates a typed `SnapshotWriter` wrapper that pre-populates `impulse.schema.*` footer provenance, domain `PrimitiveWidth`, and relation `CSC` flags automatically. See [Schema-First Development & AOT Codegen](aot-codegen.md). --- ## Part 2: Declarative CSV / TSV / JSONL Builds (`CsvManifestSnapshotBuilder`) !!! info "Version Note: v0.11 Tooling Suite" `CsvManifestSnapshotBuilder.buildV10Snapshot(...)` (streaming YAML/JSON manifest compilation over CSV, TSV, and JSONL inputs with domain/edge SoA attributes, vector columns, nullable bitmaps, and schema provenance metadata) is part of the **`v0.11`** pure-Java tooling suite (and powers `impulse-j build` and `impulse-maven-plugin:build-snapshot`). When your upstream data is exported as **CSV, TSV, or JSONL** files—or when generating deterministic `.imps` test fixtures in CI—you do not need to write custom `RelationDataSource` iterators or install a native binary. `CsvManifestSnapshotBuilder` compiles a declarative `manifest.yaml` (or `manifest.json`) directly to a 128-byte-aligned `.imps` snapshot in pure Java: ### Example `manifest.yaml` ```yaml schema_name: BankGraph schema_version: "1.0.0" domains: - id: 0 name: User id_width: uint32 key_type: int64 id_column: user_id file: domains/users.csv attributes: - name: name type: string - name: age type: int32? - id: 1 name: Account id_width: uint32 key_type: int64 id_column: account_id file: domains/accounts.jsonl attributes: - name: balance type: float64 relations: - id: 0 name: OWNS from: User to: Account direction: bidirectional file: relations/user_accounts.csv - id: 1 name: TRANSFERRED_TO from: Account to: Account direction: bidirectional file: relations/transfers.tsv attributes: - name: amount type: float64 ``` ### Invoking `CsvManifestSnapshotBuilder` from Java ```java import org.impulsegraph.builder.csv.CsvManifestSnapshotBuilder; import java.nio.file.Path; // Default 64 MB external-sort staging limit in a temporary staging directory: CsvManifestSnapshotBuilder.buildV10Snapshot( Path.of("datasets/manifest.yaml"), Path.of("datasets/bank_graph.imps") ); // Or with explicit staging directory and memory budget: CsvManifestSnapshotBuilder.buildV10Snapshot( Path.of("datasets/manifest.yaml"), Path.of("datasets/bank_graph.imps"), Path.of("/var/tmp/impulse-staging"), 256L * 1024 * 1024 // 256 MB ); ``` What `CsvManifestSnapshotBuilder.buildV10Snapshot` handles automatically: * **Multi-Format Node & Edge Parsing**: Streams `.csv`, `.tsv`, and `.jsonl` files in $O(\text{chunk})$ heap memory via `StreamingColumnStager`. * **Automatic Primary Key Columns & Resolution**: Ensures each domain's `id_column` (`string`, `int32`, `int64`, `uuid`) is registered with `withPrimaryKeyIndex(true)` and resolves natural source/target keys in edge files to dense IDs. * **Unsorted Edge Streams**: Externally sorts arbitrary-order edge rows and their attached edge attributes by `(srcDenseId, tgtDenseId)` via `ExternalSortStaging`, and builds optional reverse `CSC` indices when `direction: bidirectional` or `include_csc: true` is set. * **Nullable Bitmaps & Vector Columns**: Supports trailing `?` nullable shorthand (`int32?`, `string?`) with 128-byte-padded validity bitmaps and fixed-length vector columns (`float32[4]`). * **Provenance Footer**: Embeds `impulse.schema.name`, `impulse.schema.version`, and `impulse.schema.sha256` (SHA-256 of the manifest bytes) into the `.imps` footer trailer. --- ## Step 5: Mount and Query the Snapshot Mount the compiled `.imps` file inside a shared FFM `Arena` and execute an engine-native Kleisli traversal seeded by the external business key (`"101"`), filtering on the `amount` edge attribute and resolving surviving target nodes back to external account keys: ```java import org.impulsegraph.api.ImpulseGraphSnapshot; import org.impulsegraph.storage.csr.BinarySnapshotLoader; import java.lang.foreign.Arena; import java.nio.file.Path; import java.util.List; Path snapshotFile = Path.of("datasets/bank_graph.imps"); try (Arena arena = Arena.ofShared(); BinarySnapshotLoader.LoadedSnapshot loaded = BinarySnapshotLoader.loadSnapshot(snapshotFile, arena)) { ImpulseGraphSnapshot graph = loaded.graph(); // Engine-native 2-hop CSR traversal with fused CEL edge filter: // User("101") -[:OWNS]-> Account -[:TRANSFERRED_TO {amount > 1000.0}]-> Account List recipientAccountKeys = graph.domain("User") .fromKey("101") .out("OWNS") .out("TRANSFERRED_TO", "edge.amount > 1000.0") .toKeyList(); System.out.println("Recipient account keys: " + recipientAccountKeys); } ``` !!! note "External `IdMapper` Resolution for Topology-Only Snapshots" If you built a topology-only snapshot via `SnapshotBuilder` without embedding primary key attribute columns, seed the traversal via `graph.domain("User").from(userMapper.getId(101L))` and translate the resulting `.toList()` dense IDs at the boundary with `accountMapper::getKey`. --- ## FAQ ### Can I stream `.imps` bytes directly to S3 or Google Cloud Storage? Yes. `SnapshotBuilder` writes sequentially in a single pass without seeking backward, so you can pass any `OutputStream` or `WritableByteChannel` backed by an S3/GCS multipart upload stream: ```java try (OutputStream s3Out = openS3MultipartUploadStream("my-bucket", "snapshots/bank_graph.imps")) { builder.writeTo(s3Out); } ``` ### Can I cryptographically sign snapshots in Java? Yes. Pass a `java.security.PrivateKey` and certificate chain before calling `writeTo(...)`: ```java builder.withSignature(privateKey, certificateChain); ``` --- ## Next Steps * **[Schema-First Development & AOT Codegen](aot-codegen.md)** — Replace string domain/relation/attribute names with compile-time verified Java classes. * **[Maven Plugin & Build-Time AOT Pipeline](maven-and-build-tooling.md)** — Automate test snapshot builds (`build-snapshot`) and schema validation in Maven. * **[Changing Data & Live Updates](../../getting-started/handling-mutations.md)** — Architectural patterns for CDC refresh and Blue/Green hot-swapping. * **[Fluent API Guide](../../query-api/fluent-api.md)** & **[ReBAC Authorization Showcase](../../showcase/authz.md)**. ================================================================================ FILE: docs/ecosystems/java/aot-codegen.md | URL: https://www.impulsegraph.org/ecosystems/java/aot-codegen/ ================================================================================ # Schema-First Development & AOT Code Generation !!! info "Version Note: v0.11 Tooling Suite" `SchemaYamlCodec`, `SnapshotSchemaExtractor`, `SnapshotContractValidator`, and `impulse-codegen` v2 (`GeneratorMain` / `SchemaCodeEmitter`) ship in **`v0.11`** (`0.11.0`). Generated source files have **zero third-party dependencies**—they import exclusively `java.*` and `org.impulsegraph.*`. In stringly-typed graph APIs, three classes of bugs routinely escape into production: 1. **Cross-Domain Dense ID Confusion**: Passing `Account` dense ID `0` into a `User` traversal (`snap.domain("User").from(accountDenseId)`), silently traversing an unrelated entity because every domain independently indexes $0 \dots N_d - 1$. 2. **Invalid Direction or Typo Bugs**: Calling `.in("USER_POSTS_POST")` on a forward-only relation built without a reverse `CSC` index, or misspelling an attribute name inside a CEL string (`"reputaton >= 50"`). 3. **Producer/Consumer Drift**: Mounting a newly rebuilt `.imps` snapshot where an upstream pipeline dropped an attribute or widened a non-null column to nullable. `impulse-codegen` eliminates all three failure modes at **`javac` compile time** and **snapshot mount time** by compiling a declarative [`.imps.schema.yaml`](../../reference/spec/schema-specification.md) contract into strongly-typed, zero-allocation Java 21+ classes. --- ## 1. Authoring or Extracting `.imps.schema.yaml` ### Authoring a Schema Contract Forward Create `src/main/resources/schema.yaml` (or `bank.imps.schema.yaml`): ```yaml package: com.example.bank.graph graphName: BankGraph version: "1.2.0" domains: User: idWidth: uint32 keyType: uuid attributes: username: { type: fixed_string, dimension: 32, nullable: false, indexed: true } risk_score: { type: int32, nullable: false } kyc_tier: { type: int32, optional: true, since: "1.2.0" } embedding: { type: "float32[128]", nullable: false } Account: idWidth: uint32 keyType: int64 attributes: balance: { type: float64, nullable: false } frozen_reason: { type: var_string, nullable: true } relations: owns: source: User target: Account directions: [out, in] inverseAlias: ownedBy cardinality: one_to_many transferredTo: source: Account target: Account directions: [out] # Forward CSR only — no reverse CSC index cardinality: many_to_many attributes: amount: { type: float64, nullable: false } ``` You can parse and validate any schema manifest programmatically using `SchemaYamlCodec` and `SchemaValidator` in `impulse-api` (zero external YAML libraries required): ```java import org.impulsegraph.api.schema.GraphManifest; import org.impulsegraph.api.schema.SchemaValidator; import org.impulsegraph.api.schema.SchemaYamlCodec; import java.nio.file.Path; import java.util.List; GraphManifest manifest = SchemaYamlCodec.parse(Path.of("src/main/resources/schema.yaml")); List errors = SchemaValidator.validate(manifest); if (!errors.isEmpty()) { throw new IllegalArgumentException("Invalid schema: " + errors); } String sha256 = manifest.schemaFingerprintSha256(); // Deterministic canonical YAML SHA-256 ``` ### Reverse-Extracting a Schema from an Existing `.imps` Snapshot If a Python or Rust pipeline already produces an `.imps` file, reconstruct its canonical `.imps.schema.yaml` via [`impulse-j schema extract`](cli-impulse-j.md), [`impulse-maven-plugin:extract-schema`](maven-and-build-tooling.md), or `SnapshotSchemaExtractor`: ```java import org.impulsegraph.storage.csr.BinarySnapshotLoader; import org.impulsegraph.storage.schema.SnapshotSchemaExtractor; import java.lang.foreign.Arena; import java.nio.file.Path; try (Arena arena = Arena.ofConfined(); BinarySnapshotLoader.LoadedSnapshot loaded = BinarySnapshotLoader.loadSnapshot(Path.of("datasets/bank_graph.imps"), arena)) { String canonicalYaml = SnapshotSchemaExtractor.extractYaml(loaded); System.out.println(canonicalYaml); } ``` `GeneratorMain.generate(...)` also accepts an `.imps` file directly as its input path, performing reverse extraction and Java source emission in one step. --- ## 2. Running `impulse-codegen` In standard builds, configure [`impulse-maven-plugin:generate`](maven-and-build-tooling.md) so generated sources are compiled automatically during `generate-sources`. You can also invoke `GeneratorMain` via [`impulse-j codegen`](cli-impulse-j.md) or Java code: ```java import org.impulsegraph.codegen.GeneratorMain; import java.nio.file.Path; GeneratorMain.generate( Path.of("src/main/resources/schema.yaml"), Path.of("target/generated-sources/impulse"), null // Uses 'package:' from schema.yaml, or overrides if non-null ); ``` --- ## 3. Complete Catalog of Generated Artifacts For the `BankGraph` schema above, `SchemaCodeEmitter` emits the following classes into `com.example.bank.graph`: | Generated Class | Role & Compile-Time / Runtime Guarantees | | :--- | :--- | | **`UserId`**, **`AccountId`** | Distinct Java `record` wrappers (`record UserId(long denseId)`) enforcing `denseId >= 0`. Passing an `AccountId` to `snap.users().from(...)` is a **`javac` compile error**. | | **`BankGraphSnapshot`** | AutoCloseable typed facade embedding `SCHEMA_YAML` & `SCHEMA`. `open(Path, Arena)` mounts the `.imps` file and runs `SnapshotContractValidator.validateAndBind(...)` upfront, pre-resolving off-heap `BoundSchemaHandles`. Provides `users()`, `accounts()`, and `createLifecycleManager(...)`. | | **`UserDomainView`**, **`AccountDomainView`** | Domain entrypoints parameterized by the domain's `keyType`: `UserDomainView` exposes `fromKey(UUID)`, `toDenseId(UUID)`, `toKey(long) -> UUID`, `hasKycTier()`, and `vectorSearchEmbedding(float[], int)` (enforcing `length == 128`). `AccountDomainView` exposes `fromKey(long)` and `toKey(long) -> long`. | | **`UserTraversal`**, **`AccountTraversal`** | Kleisli frontier builders whose edge methods transition the static return type across domains: `UserTraversal.outOwns()` returns `AccountTraversal`. Reverse methods (`inOwns()`, `ownedBy()`) are emitted **only** when `directions` includes `in` (or `symmetric: true`)—`inTransferredTo()` is not generated because `transferredTo` is `[out]`-only! | | **`UserAttrs`**, **`UserPredicate`**, **`AccountAttrs`**, **`AccountPredicate`** | Type-safe CEL node attribute metamodel (`IntAttr`, `LongAttr`, `DoubleAttr`, `BoolAttr`, `StringAttr`, `BytesAttr`) with automatic string escaping and `.and(...)` / `.or(...)` / `.not()` composition. | | **`TransferredToEdgeAttrs`**, **`TransferredToEdgePredicate`** | Emitted for relations with edge attributes (`TransferredToEdgeAttrs.AMOUNT.gt(1000.0)`), accepted by `AccountTraversal.outTransferredTo(TransferredToEdgePredicate)`. | | **`UserRowView`**, **`AccountRowView`** | **Zero-allocation flyweight off-heap cursors** reused across `forEachRow(Consumer)`. Reads little-endian primitives, UTF-8 strings, validity bitmasks (`isFrozenReasonNull()`), optional guards (`hasKycTier()`, `kycTierOrDefault(0)`), and reusable vector buffers (`embedding(float[] dest)`) directly from pre-bound `MemorySegment` slices. | | **`UserRecord`**, **`AccountRecord`** | Immutable boundary Java `record` DTOs materialized via `row.toRecord()` or `traversal.toRecords()`. Non-null columns map to primitives (`double balance`); nullable or `optional: true` columns map to boxed types (`String frozenReason`, `Integer kycTier`). | | **`BankGraphSnapshotWriter`** | Typed streaming builder wrapper (`domainUser(...)`, `domainAccount(...)`, `relationOwns(...)`, `relationTransferredTo(...)`) that automatically configures `PrimitiveWidth`, `Topology.CSC`, and `impulse.schema.*` footer provenance. | --- ## 4. Before vs. After: Stringly-Typed vs. Schema-First AOT === "After: Schema-First AOT (`impulse-codegen`)" ```java import com.example.bank.graph.AccountAttrs; import com.example.bank.graph.AccountRecord; import com.example.bank.graph.BankGraphSnapshot; import com.example.bank.graph.TransferredToEdgeAttrs; import java.lang.foreign.Arena; import java.nio.file.Path; import java.util.List; import java.util.UUID; UUID userUuid = UUID.fromString("00000000-0000-0000-0000-000000000101"); try (Arena arena = Arena.ofShared(); // Validates entire schema contract & pre-binds MemorySegment handles at open time! BankGraphSnapshot snap = BankGraphSnapshot.open(Path.of("datasets/bank.imps"), arena)) { // 1. Domain-transitioning Kleisli pipeline: // users() [UserDomainView] // -> fromKey(UUID) [UserTraversal] // -> outOwns() [AccountTraversal] // -> outTransferredTo(EdgePredicate) [AccountTraversal] // -> where(AccountPredicate) [AccountTraversal] var suspectAccounts = snap.users() .fromKey(userUuid) .outOwns() .outTransferredTo(TransferredToEdgeAttrs.AMOUNT.gt(10_000.0)) .where(AccountAttrs.BALANCE.ge(50_000.0) .and(AccountAttrs.FROZEN_REASON.isNull())); // 2. Zero-allocation off-heap iteration via reusable AccountRowView flyweight: suspectAccounts.forEachRow(row -> { long accountDenseId = row.denseId(); double balance = row.balance(); // Direct MemorySegment LE_DOUBLE read // Process in-place without allocating per-row heap objects... }); // 3. Or materialize typed external keys (List) / boundary DTOs (List): List accountKeys = suspectAccounts.toKeyList(); List records = suspectAccounts.toRecords(); } ``` === "Before: Raw Stringly-Typed Core API" ```java import org.impulsegraph.api.ImpulseGraphSnapshot; import org.impulsegraph.storage.csr.BinarySnapshotLoader; import java.lang.foreign.Arena; import java.nio.file.Path; import java.util.List; try (Arena arena = Arena.ofShared(); BinarySnapshotLoader.LoadedSnapshot loaded = BinarySnapshotLoader.loadSnapshot(Path.of("datasets/bank.imps"), arena)) { ImpulseGraphSnapshot snap = loaded.graph(); // Domain names, relation names, key formatting, and CEL identifiers are // verified only when the query executes at runtime: List rawKeys = snap.domain("User") .fromKey("00000000-0000-0000-0000-000000000101") .out("owns") .out("transferredTo", "edge.amount > 10000.0") .filter("balance >= 50000.0 && isNull(frozen_reason)") .toKeyList(); List accountKeys = rawKeys.stream().map(Long::valueOf).toList(); } ``` --- ## 5. Zero-Allocation Flyweight `RowView` & Evolution Guards Inside `RowView`, `SchemaCodeEmitter` binds `MemorySegment` references (`dataSeg`, `validitySeg`, `offsetsSeg`) once from `BoundSchemaHandles` before iterating the surviving `ImpulseBitSet` frontier: * **Zero Heap Churn on Vectors**: For `embedding: { type: "float32[128]" }`, `UserRowView` generates `void embedding(float[] dest)`, allowing a single caller-allocated `float[128]` array to be reused across millions of visited nodes without allocating `float[]` arrays per node. * **Safe Rolling Evolution (`optional: true` / `since`)**: Attributes marked `optional: true` or carrying a `since:` version tag allow your new consumer code to mount older `.imps` snapshots where that column does not yet exist. Generated `UserDomainView.hasKycTier()`, `UserRowView.hasKycTier()`, and `row.kycTierOrDefault(0)` let application code branch cleanly without `NullPointerException` or bounds traps, while calling bare `row.kycTier()` when absent fails fast with a descriptive `IllegalStateException`. * **`@Deprecated` Propagation**: Adding `deprecated: "Use kyc_tier"` to any domain, attribute, relation, or virtual relation in `.imps.schema.yaml` automatically emits `@Deprecated` on the corresponding generated Java methods so IDEs and `-Werror` builds flag stale usages immediately. --- ## Next Steps * **[Maven Plugin & Build-Time AOT Pipeline](maven-and-build-tooling.md)** — Run `impulse:generate` and `impulse:aot-compile` automatically during `mvn compile`. * **[Day-2 Operations: Kubernetes, Hot-Swap Lifecycle & Schema Evolution](kubernetes-and-lifecycle.md)** — Pair `BankGraphSnapshot.createLifecycleManager(...)` with zero-downtime epoch swaps. ================================================================================ FILE: docs/ecosystems/java/maven-and-build-tooling.md | URL: https://www.impulsegraph.org/ecosystems/java/maven-and-build-tooling/ ================================================================================ # Maven Plugin & Build-Time AOT Pipeline !!! info "Version Note: v0.11 Tooling Suite" The 7-Mojo `org.impulsegraph:impulse-maven-plugin` suite (`generate`, `generate-test`, `aot-compile`, `build-snapshot`, `extract-schema`, `validate`, `check-compat`) ships in **`v0.11`** (`0.11.0`). In `0.10.0` on Maven Central, only the baseline `generate` goal is published. `impulse-maven-plugin` (goal prefix **`impulse`**) integrates schema-first Java code generation, snapshot-agnostic build-time query verification, deterministic `.imps` test fixture building, and multi-consumer compatibility gating directly into the standard Maven build lifecycle. --- ## 1. Summary of All 7 Maven Goals | Goal (`impulse:`) | Mojo Class | Default Lifecycle Phase | Key `` Parameters | Purpose | | :--- | :--- | :--- | :--- | :--- | | **`impulse:generate`** | `GenerateQueryBuildersMojo` | `generate-sources` | `schemaFile`, `outputDirectory`, `packageName`, `skipIfMissing` | Generates typed Java snapshot facades, `Id` records, traversals, CEL metamodels, `RowView` cursors, and writers; registers compile source root. | | **`impulse:generate-test`** | `GenerateTestQueryBuildersMojo` | `generate-test-sources` | `schemaFile`, `outputDirectory`, `packageName`, `skipIfMissing` | Generates typed Java classes from a test schema and registers `target/generated-test-sources/impulse` as a test compile root. | | **`impulse:aot-compile`** | `AotCompileQueriesMojo` | `generate-sources` | `queriesDirectory`, `schemaFile`, `outputDirectory`, `skipIfMissing` | Lowers `.cypher`, `.impk`, `.implog`, and `.impscm` query files, validates all domain/relation/direction/attribute references via `SchemaBindValidatorPass`, and emits normalized `.impscm` IR resources. | | **`impulse:build-snapshot`** | `BuildSnapshotMojo` | `generate-test-resources` | `manifestFile` *(req)*, `outputFile` *(req)*, `skipIfMissing` | Compiles a CSV/TSV/JSONL `manifest.yaml` or `manifest.json` into an immutable `.imps` binary snapshot in pure Java. | | **`impulse:extract-schema`** | `ExtractSchemaMojo` | *(CLI / explicit)* | `snapshotFile` *(req)*, `outputFile` *(req)* | Reverse-extracts a canonical `.imps.schema.yaml` file from an existing `.imps` binary snapshot. | | **`impulse:validate`** | `ValidateSnapshotMojo` | `verify` | `snapshotFile` *(req)*, `schemaFile`, `strictAlignment`, `deepAudit`, `quickCheck` | Audits `.imps` Page 0 header, 128B alignment, CSR monotonicity, CSC transpose multiset, SHA-256 digest, and optional consumer schema conformance. | | **`impulse:check-compat`** | `CheckCompatMojo` | `verify` | `snapshotFile` *(req)*, `consumerSchemas` *(req)* | CI producer gate: validates a candidate `.imps` file against a list of downstream consumer `.imps.schema.yaml` contracts, failing `mvn verify` on any breaking change. | ### Exact Parameter Reference & System Properties | Goal(s) | XML Tag | `-D` User Property | Default Value | | :--- | :--- | :--- | :--- | | `generate` | `` | `-Dimpulse.schemaFile` | `${project.basedir}/src/main/resources/schema.yaml` | | `generate` | `` | `-Dimpulse.outputDirectory` | `${project.build.directory}/generated-sources/impulse` | | `generate` | `` | `-Dimpulse.packageName` | `org.impulsegraph.generated` *(if `package:` omitted in YAML)* | | `generate-test` | `` | `-Dimpulse.testSchemaFile` | `${project.basedir}/src/test/resources/schema.yaml` | | `generate-test` | `` | `-Dimpulse.testOutputDirectory` | `${project.build.directory}/generated-test-sources/impulse` | | `generate-test` | `` | `-Dimpulse.testPackageName` | `org.impulsegraph.generated.test` | | `aot-compile` | `` | `-Dimpulse.queriesDirectory` | `${project.basedir}/src/main/impulse/queries` | | `aot-compile` | `` | `-Dimpulse.aotOutputDirectory` | `${project.build.directory}/generated-resources/impulse/queries` | | `build-snapshot` | `` | `-Dimpulse.manifestFile` | *(Required)* | | `build-snapshot`, `extract-schema` | `` | `-Dimpulse.outputFile` | *(Required)* | | `extract-schema`, `validate`, `check-compat` | `` | `-Dimpulse.snapshotFile` | *(Required)* | | `validate` | `` / `` / `` | `-Dimpulse.strictAlignment` / `-Dimpulse.deepAudit` / `-Dimpulse.quickCheck` | `false` | | `generate`, `generate-test`, `aot-compile`, `build-snapshot` | `` | `-Dimpulse.skipIfMissing` | `false` | --- ## 2. Recipe 1: Schema-First AOT Source Generation & IDE Integration Bind `generate` (and optionally `generate-test`) in your microservice `pom.xml`: ```xml org.impulsegraph impulse-maven-plugin ${impulse.version} generate-main-graph-api generate ${project.basedir}/src/main/resources/bank.imps.schema.yaml ${project.build.directory}/generated-sources/impulse com.example.bank.graph ``` ### Automatic IntelliJ IDEA & Eclipse `m2e` Source-Root Registration `impulse-maven-plugin` embeds `META-INF/m2e/lifecycle-mapping-metadata.xml` with `true` and `true` for `generate`, `generate-test`, `aot-compile`, and `build-snapshot`, and invokes `project.addCompileSourceRoot(...)` / `project.addTestCompileSourceRoot(...)` directly. Importing or reloading the Maven project in **IntelliJ IDEA**, **Eclipse (`m2e`)**, or **VS Code Java** automatically marks `target/generated-sources/impulse` as a generated source root without requiring `build-helper-maven-plugin`. --- ## 3. Recipe 2: Build-Time Query Verification (`impulse:aot-compile`) If your team maintains standalone `.cypher`, `.impk`, `.implog`, or `.impscm` query files under `src/main/impulse/queries/`, `impulse:aot-compile` catches query bugs during `mvn compile`—**without requiring a multi-gigabyte `.imps` file on the build runner**. ```xml org.impulsegraph impulse-maven-plugin ${impulse.version} aot-validate-and-lower-queries aot-compile ${project.basedir}/src/main/impulse/queries ${project.basedir}/src/main/resources/bank.imps.schema.yaml ${project.build.directory}/generated-resources/impulse/queries ``` ### What `SchemaBindValidatorPass` Catches at Build Time During `aot-compile`, each query file is parsed by its frontend compiler (`CypherCompiler`, `ImpKCompiler`, `ImpLogCompiler`, or `ImpScmParser`) into `ImpScheme` AST and checked against `schemaFile` via `SchemaBindValidatorPass`: * **Unknown Domains, Relations, or Attributes**: e.g., `r.unknown_score > 10` in a `.cypher` file fails `mvn compile` with `MojoFailureException` listing every offending file and AST path. * **Missing Reverse `CSC` Topology**: Walking backward (`<-[:userPostsPost]-` or `(csc-walk "userPostsPost")`) over a relation declared `directions: [out]` fails the build immediately. * **CEL Expression Type Mismatches**: Applying arithmetic or boolean operators to incompatible attribute types (such as comparing a `var_string` column with `>` against a numeric literal or applying `&&` to a numeric field). Validated queries are serialized as normalized `.impscm` S-expression IR files under `target/generated-resources/impulse/queries/`. At service startup (or pre-swap inside `SnapshotLifecycleManager`), `QueryRegistry.validateAndBindAll(snapshot, arena)` performs Stage 2 physical binding to emit snapshot-specific `impOps` bytecode—or use [`impulse-j compile --snapshot ... -o query.impb`](cli-impulse-j.md) when building against a fixed `.imps` artifact. --- ## 4. Recipe 3: Test Fixture Snapshots & Producer CI Compatibility Gates In a snapshot producer pipeline—or an integration-test module—combine `build-snapshot` (during `generate-test-resources`) with `validate` and `check-compat` (during `verify`): ```xml org.impulsegraph impulse-maven-plugin ${impulse.version} build-test-fixture-snapshot generate-test-resources build-snapshot ${project.basedir}/src/test/impulse/manifest.yaml ${project.build.directory}/test-snapshots/social.imps audit-built-snapshot verify validate ${project.build.directory}/test-snapshots/social.imps ${project.basedir}/src/main/resources/producer.imps.schema.yaml true true verify-downstream-consumers verify check-compat ${project.build.directory}/test-snapshots/social.imps ${project.basedir}/contracts/feed-service-v1.imps.schema.yaml ${project.basedir}/contracts/trust-safety-v2.imps.schema.yaml ``` If a producer commit removes an attribute, changes a column type, widens nullability from `nullable: false` to `nullable: true`, or drops `CSC` on a relation required by `feed-service-v1.imps.schema.yaml`, `mvn verify` fails before the snapshot is ever published to S3/GCS. ### Ad-Hoc Reverse Schema Extraction To bootstrap a `schema.yaml` from an existing `.imps` file directly from Maven: ```bash mvn org.impulsegraph:impulse-maven-plugin:0.11.0:extract-schema \ -Dimpulse.snapshotFile=datasets/production.imps \ -Dimpulse.outputFile=src/main/resources/schema.yaml ``` --- ## Roadmap: Gradle Plugin & JSR-269 Annotation Processor (`v0.12`) !!! note "Upcoming in v0.12" * **Native Gradle 8/9 Plugin (`org.impulsegraph.impulse`)**: Dedicated incremental Gradle tasks wrapping `CodegenService`, `CompilerService`, and `SchemaService` with Gradle Build Cache support (Gradle users on `v0.11` can invoke `org.impulsegraph.codegen.GeneratorMain` or `org.impulsegraph.cli.ImpulseCliMain` via a standard `JavaExec` task). * **JSR-269 `@ImpulseQuery` Annotation Processor**: Compile-time verification of inline Java string queries (`@ImpulseQuery("MATCH (u:User)...")`) directly inside `javac` without external query files. --- ## Next Steps * **[Pure-Java CLI (`impulse-j`)](cli-impulse-j.md)** — Run the exact same `SchemaService`, `CodegenService`, `SnapshotService`, and `CompilerService` workflows from shell scripts and CI containers. * **[Day-2 Operations: Kubernetes, Hot-Swap Lifecycle & Schema Evolution](kubernetes-and-lifecycle.md)** — Pair CI `check-compat` gates with runtime `SnapshotLifecycleManager` validation. ================================================================================ FILE: docs/ecosystems/java/cli-impulse-j.md | URL: https://www.impulsegraph.org/ecosystems/java/cli-impulse-j/ ================================================================================ # Pure-Java CLI (`impulse-j`) & Tooling Parity !!! info "Version Note: v0.11 Tooling Suite" The pure-Java CLI **`impulse-j`** (`org.impulsegraph:impulse-cli`, shaded classifier `all`) ships in **`v0.11`** (`0.11.0`). Impulse Graph provides two command-line distributions that operate on the exact same `.imps`, `.imps.schema.yaml`, `.impas`, and `.impb` files: 1. **`impulse-j` (`org.impulsegraph:impulse-cli`)**: A 100% pure-Java CLI packaged as an executable shaded JAR (`impulse-cli-*-all.jar`) with a POSIX `sh` wrapper script. 2. **`impulse-graph` / `impulse` (`impulse-graph-core/impulse-cli`)**: The native Rust/C++20 binary embedding `libimpulse_graph_static.a` (see [Native CLI Reference](../native/cli-reference.md)). --- ## 1. Why `impulse-j` Exists In many enterprise JVM environments—bank CI runners, air-gapped Artifactory/Nexus networks, locked-down developer laptops, and distroless JRE containers—downloading or approving platform-specific native C++/Rust binaries requires separate security review, whereas fetching a signed JAR from an internal Maven mirror is already standard practice. `impulse-j` embeds the pure-Java storage loader, streaming CSV/TSV/JSONL snapshot builder, schema validator, AOT code generator, multi-frontend compiler, `QueryExplainer`, and `ImpulseVM` into a single cross-platform artifact that runs anywhere **JDK 21 LTS** or **JDK 22+ / 25 LTS** is installed. --- ## 2. Installation & Invocation === "`impulse-j` Launcher Script" The `impulse-j` POSIX shell wrapper automatically resolves `JAVA_HOME` (or `java` on `PATH`), locates `impulse-cli-*-all.jar` (or reads `IMPULSE_J_JAR`), inspects `java -version` to inject `--enable-preview` automatically when running on **JDK 21**, and adds `--add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED`: ```bash # Override JAR path or pass extra JVM heap/GC flags via environment variables: export IMPULSE_J_JAR=/opt/impulse/impulse-cli-0.11.0-all.jar export IMPULSE_J_OPTS="-Xmx4g" impulse-j --version impulse-j inspect datasets/social.imps --format json ``` === "Direct `java -jar`" Invoke the shaded `-all.jar` directly on JDK 22+ / JDK 25 LTS (add `--enable-preview` before `--add-modules` if running on JDK 21 LTS): ```bash java --add-modules jdk.incubator.vector \ --enable-native-access=ALL-UNNAMED \ -jar impulse-cli-0.11.0-all.jar \ snapshot validate datasets/social.imps --strict-alignment --deep-audit ``` === "`jbang` (Zero-Install Maven Execution)" Run `impulse-j` directly from Maven Central or an internal corporate Maven repository via [JBang](https://www.jbang.dev/): ```bash jbang --java 25 \ --runtime-option=--add-modules=jdk.incubator.vector \ --runtime-option=--enable-native-access=ALL-UNNAMED \ org.impulsegraph:impulse-cli:0.11.0:all \ schema extract datasets/social.imps -o schema.yaml ``` --- ## 3. Command Reference & Exact Flags ```text impulse-j ├── schema │ ├── extract [-o|--output ] │ ├── validate [-s|--snapshot ] [--format text|json] │ └── check-compat -s|--snapshot -c|--consumer ... [--format text|json] ├── codegen -s|--schema -o|--out [-p|--package ] ├── snapshot (build, inspect, stats also available as top-level shorthands) │ ├── build -m|--manifest -o|--output │ ├── inspect [--format text|json] [--page-map] [--domain ] [--relation ] [--anonymize] │ ├── validate [--strict-alignment] [--quick-check] [--deep-audit] [--format text|json] │ └── stats [--format text|json] [-v|--verbose] [--supernode-threshold ] ├── compile [-o|--output ] [--schema ] [-s|--snapshot ] [--emit-ir] [--lang ] ├── assemble -i|--input -o|--output ├── disassemble -i|--input [-o|--output ] ├── explain [--lang ] [-s|--snapshot ] [--schema ] └── run -s|--snapshot -b|--bytecode [-i|--input-val ] [--verify] [--format text|json] ``` ### 3.1 Schema Governance (`schema extract | validate | check-compat`) ```bash # Reconstruct canonical .imps.schema.yaml from any v0.9 / v0.10 .imps binary impulse-j schema extract production.imps -o extracted.imps.schema.yaml # Validate YAML structural invariants alone, or verify conformance against a snapshot impulse-j schema validate src/main/resources/schema.yaml --snapshot production.imps --format json # Multi-consumer CI compatibility gate (repeatable -c / --consumer flag; exits non-zero on violation) impulse-j schema check-compat \ --snapshot candidate-v2.imps \ --consumer contracts/authz-service.yaml \ --consumer contracts/fraud-scorer.yaml \ --format text ``` ### 3.2 AOT Java Code Generation (`codegen`) Accepts either a `.yaml`/`.yml` schema file or a compiled `.imps` binary snapshot: ```bash impulse-j codegen \ --schema src/main/resources/schema.yaml \ --out target/generated-sources/impulse \ --package com.example.graph.generated ``` ### 3.3 Snapshot Lifecycle (`build`, `inspect`, `snapshot validate`, `stats`) ```bash # Compile CSV, TSV, and JSONL node/edge files from manifest.yaml or manifest.json impulse-j build -m datasets/manifest.yaml -o datasets/graph.imps # Inspect Page 0 header, domains, relations, 128B/4KB page map, and SHA-256 in JSON impulse-j inspect datasets/graph.imps --page-map --format json # Generate an anonymized inspection bundle (redacts proprietary domain/relation/attribute names) impulse-j inspect datasets/graph.imps --anonymize --format json > support-bundle.json # Verify 128B alignment, CSR monotonicity, CSC transpose multiset, and SHA-256 footer impulse-j snapshot validate datasets/graph.imps --strict-alignment --deep-audit # Compute degree percentiles (min/avg/P50/P90/P99/max), sparsity, and supernodes (Z-score >= 3.0) impulse-j stats datasets/graph.imps --verbose --supernode-threshold 3.0 --format json ``` ### 3.4 Query Compilation, Disassembly, `explain` & `run` ```bash # Stage 1 schema-validated lowering to normalized ImpScheme (.impscm) IR (no snapshot required) impulse-j compile queries/friends.cypher --schema schema.yaml --emit-ir -o target/friends.impscm # Full Stage 1 + Stage 2 compilation against a snapshot into ImpAsm (.impas) or binary ImpOps (.impb) impulse-j compile queries/friends.cypher --schema schema.yaml --snapshot graph.imps -o target/friends.impas impulse-j compile queries/friends.cypher --schema schema.yaml --snapshot graph.imps -o target/friends.impb # Assemble .impas <-> Disassemble .impb impulse-j assemble -i target/friends.impas -o target/friends.impb impulse-j disassemble -i target/friends.impb # Multi-pass optimizer trace + ImpAsm disassembly report (accepts file path or inline query string) impulse-j explain "MATCH (u:User)-[:OWNS]->(a:Account) WHERE u._id = 0 RETURN a" \ --lang cypher --schema schema.yaml --snapshot graph.imps # Execute .impb, .impas, .impscm, .cypher, .impk, or .implog on ImpulseVM with static register verification impulse-j run --snapshot graph.imps --bytecode target/friends.impb --input-val 42 --verify --format json ``` --- ## 4. Side-by-Side CLI Capability Matrix (`impulse-j` vs. Native `impulse-graph`) Shared commands between `impulse-j` and the native `impulse-graph` (`impulse`) binary are continuously verified against a **134-check side-by-side parity suite** in `impulse-verification`. Use the table below to choose the right tool for your pipeline: | Capability / Command | `impulse-j` (Pure Java) | `impulse-graph` (Native Rust/C++20) | Notes | | :--- | :---: | :---: | :--- | | **CSV / TSV / JSONL `build`** | Yes | Yes | Byte-for-byte compatible `.imps` output; both mount in Java, Python, C++, and Rust. | | **Apache Parquet `build`** | — | **Yes** | Native CLI streams Parquet column chunks directly via Arrow/Parquet C++. | | **Vamana ANN Index Build (`--embeddings`, `--vector-index`)** | — | **Yes** | Built by `impulse build`, `attach-embeddings`, or `optimize`; **queried natively in Java** via `OP_VECTOR_ANN_SEARCH`. | | **`inspect` (`--format json`, `--page-map`, `--domain`, `--relation`)** | Yes | Yes | 100% parity on structural inspection. | | **`inspect --anonymize`** | **Yes** | — | Redacts domain, relation, attribute, and metadata identifiers for enterprise support bundles. | | **`snapshot validate` (`--strict-alignment`, `--quick-check`, `--deep-audit`)** | Yes | Yes | Header CRC, 128B alignment, CSR bounds/monotonicity, CSC transpose multiset, SHA-256. | | **`stats` (`--supernode-threshold`, `--format json`)** | Yes | Yes | Degree percentiles (`P50`/`P90`/`P99`/`max`) and Z-score supernode counts. | | **`schema extract \| validate \| check-compat`** | **Yes** | — | Consumer-driven structural subtyping & canonical `.imps.schema.yaml` extraction. | | **`codegen` (Typed Java Source Emission)** | **Yes** | — | Generates zero-dependency Java 21+ snapshot facades, traversals, CEL metamodels, and `RowView`s. | | **`compile` / `assemble` / `disassemble` / `run`** | Yes | Yes | Both compile all 4 DSLs, assemble/disassemble `.impas` ↔ `.impb`, and execute `ImpulseVM`. | | **`explain` (Stage 1 + Stage 2 Pass Trace)** | **Yes** | — | Prints step-by-step AST transformations across `PassTracer` plus final `ImpAsm` disassembly. | | **`snapshot optimize` (`--rcm`, `--vamana-locality`, `--degree-sort`, `--csc`)** | — | **Yes** | Offline Reverse Cuthill-McKee cache-locality reordering and medoid BFS layout optimization. | | **`attach-embeddings` / `convert-tensors` / `bench-vector`** | — | **Yes** | `.npy` / `.fvecs` / `.safetensors` ingestion and quantized (`SQ8`/`FP16`/`BQ1`) ANN benchmarking. | | **`snapshot diff` / `export` / `generate`** | — | **Yes** | Structural snapshot diffing, CSV/TSV/JSONL export, and synthetic Graph500 R-MAT generation. | | **`crypto` (`keygen`, `sign`, `verify` Ed25519)** | — *(Builder RSA/ECDSA)* | **Yes** | Standalone CLI Ed25519 key generation and detached/footer signature verification. | --- ## Next Steps * **[Day-2 Operations: Kubernetes, Hot-Swap Lifecycle & Schema Evolution](kubernetes-and-lifecycle.md)** — Automate live snapshot rollouts in production pods. * **[Native CLI Reference (`impulse-graph`)](../native/cli-reference.md)** — Full documentation for Parquet builds, `--rcm` reordering, and Vamana vector indexing. ================================================================================ FILE: docs/ecosystems/java/kubernetes-and-lifecycle.md | URL: https://www.impulsegraph.org/ecosystems/java/kubernetes-and-lifecycle/ ================================================================================ # Day-2 Operations: Kubernetes, Hot-Swap Lifecycle & Schema Evolution !!! info "Version Note: v0.11 Tooling Suite" `SnapshotLifecycleManager`, `SnapshotResolver`, `LocalPathSnapshotResolver`, `ConsumerSchemaContext`, `SwapResult`, `SnapshotContractValidator`, and lifecycle-backed `ImpulseHealthIndicator` probes (`startup()`, `readiness()`, `liveness()`) ship in **`v0.11`** (`0.11.0`). Low-level `SnapshotSwapManager` and `GraphSnapshot`-backed `ImpulseHealthIndicator` are available in `0.10.0`. Because Impulse Graph executes read-only traversals directly over immutable `.imps` files, production microservices never apply row-by-row mutations in place. Instead, an upstream job periodically writes a fresh `.imps` snapshot to object storage (S3/GCS) or a mounted volume, and stateless serving pods atomically rotate epochs in memory with zero query downtime (see [Long-Lived Dynamic Service](../../deployment/dynamic-service.md)). This guide covers wiring transactional Blue/Green swaps, Kubernetes probes, rolling schema evolution, and `cgroups v2` container memory limits in Java. --- ## 1. Zero-Downtime Hot-Swap with `SnapshotLifecycleManager` `SnapshotLifecycleManager` (`org.impulsegraph.vm.lifecycle`) wraps `SnapshotSwapManager` with a transactional 5-stage validation pipeline before any live traffic sees a new snapshot: 1. **Isolated Staging (`Arena.ofShared()`)**: Maps the candidate `.imps` file into an isolated candidate `Arena` and verifies Page 0 magic, section bounds, and the trailing SHA-256 checksum (`verifyChecksum = true`). 2. **Consumer Contract Validation (`SnapshotContractValidator`)**: Verifies every required domain, relation, endpoint, traversal direction (`CSC`), attribute type, vector dimension, and nullability invariant against the service's compiled `GraphManifest`, producing pre-resolved `BoundSchemaHandles`. 3. **Optional Pre-Swap Query Binding (`QueryRegistry`)**: Compiles and binds all registered `openCypher` / `ImpScheme` queries against the candidate snapshot inside the candidate `Arena`. 4. **Typed Facade Construction**: Instantiates the AOT-generated `Snapshot` facade (or exposes `GraphSnapshot` directly). 5. **Atomic Swap & Virtual-Thread RCU Drain**: Atomically flips the active epoch pointer. A background virtual thread parks until all in-flight readers on the retired epoch release their leases (`activeReaders == 0`), then unmaps the retired `Arena` and optionally deletes the staged local file. ### Complete Production Service Example ```java package com.example.bank.service; import com.example.bank.graph.AccountAttrs; import com.example.bank.graph.BankGraphSnapshot; import org.impulsegraph.api.lifecycle.CandidateSnapshotRef; import org.impulsegraph.api.lifecycle.ConsumerSchemaContext; import org.impulsegraph.api.lifecycle.SnapshotResolver; import org.impulsegraph.api.lifecycle.SwapResult; import org.impulsegraph.compiler.registry.QueryRegistry; import org.impulsegraph.storage.csr.ImpulseHealthIndicator; import org.impulsegraph.storage.lifecycle.LocalPathSnapshotResolver; import org.impulsegraph.vm.lifecycle.SnapshotLifecycleManager; import java.nio.file.Path; import java.util.List; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public final class BankGraphService implements AutoCloseable { private final SnapshotResolver resolver; private final SnapshotLifecycleManager lifecycle; private final ImpulseHealthIndicator healthIndicator; private final ScheduledExecutorService poller; public BankGraphService(Path snapshotPath, QueryRegistry queryRegistry) { // Detect file updates by SHA-256 digest (or RevisionMode.METADATA for mtime+size) this.resolver = new LocalPathSnapshotResolver( snapshotPath, LocalPathSnapshotResolver.RevisionMode.SHA256, false // deleteOnRejectOrClose: set true when staging temp files from S3/GCS ); // Create lifecycle manager bound to BankGraphSnapshot.SCHEMA + pre-swap query gate this.lifecycle = BankGraphSnapshot.createLifecycleManager( resolver, epoch -> queryRegistry.validateAndBindAll(epoch.graph(), epoch.arena()) ); this.healthIndicator = lifecycle.healthIndicator(); // Poll every 30 seconds on a background scheduler this.poller = Executors.newSingleThreadScheduledExecutor(Thread.ofPlatform().daemon().factory()); this.poller.scheduleWithFixedDelay(this::refreshSnapshot, 30, 30, TimeUnit.SECONDS); } /** Reader hot path: acquires a lock-free epoch lease and releases it in finally. */ public List findHighBalanceAccounts(UUID userKey, double minBalance) { return lifecycle.withSnapshot(snap -> snap.users() .fromKey(userKey) .outOwns() .where(AccountAttrs.BALANCE.ge(minBalance)) .toKeyList() ); } /** Background refresh loop with exhaustive sealed SwapResult handling. */ void refreshSnapshot() { SwapResult result = lifecycle.pollAndSwap(resolver); switch (result) { case SwapResult.Swapped s -> System.out.printf("Swapped active graph epoch to revision %s%n", s.revisionId()); case SwapResult.Unchanged _ -> { // No new revision available; no-op } case SwapResult.Rejected r -> System.err.printf("Rejected candidate %s (%d violation(s)): %s%n", r.candidateRevisionId(), r.violations().size(), r.message()); } } public ImpulseHealthIndicator health() { return healthIndicator; } @Override public void close() { poller.shutdownNow(); lifecycle.close(); } } ``` ### Custom S3 / GCS `SnapshotResolver` SPI For cloud object stores, implement the single-method `@FunctionalInterface` `SnapshotResolver`. Pass `deleteOnRejectOrClose = true` on `CandidateSnapshotRef` so `SnapshotLifecycleManager` automatically deletes rejected candidates immediately and deletes retired local `.imps` files once their epoch drains: ```java SnapshotResolver s3Resolver = (ConsumerSchemaContext ctx) -> { // Query S3/GCS manifest pointer for major schema version (e.g., s3://bucket/BankGraph/v1/latest.json) String latestEtag = fetchLatestEtag(ctx.graphName(), ctx.majorVersion()); if (ctx.activeSnapshotRevision().filter(latestEtag::equals).isPresent()) { return java.util.Optional.empty(); // Already serving latest revision } Path stagedFile = downloadToLocalNvmeScratch(latestEtag); return java.util.Optional.of(new CandidateSnapshotRef(latestEtag, stagedFile, true)); }; ``` ### What Happens When a Corrupt or Incompatible Snapshot Lands? If a truncated upload, SHA-256 mismatch, or schema-breaking `.imps` file is discovered during `pollAndSwap`: 1. `trySwap` catches the `IOException` or `SnapshotCompatibilityException` **before** touching the active pointer. 2. The candidate `Arena` (`arenaB`) is closed immediately, and `stagedFile` is deleted if `deleteOnRejectOrClose == true`. 3. `swapRejectedCount` increments (`ImpulseMetricsRegistry` records `snapshotSwapRejected`), `swapDegraded` flips to `true`, and `SwapResult.Rejected` returns structured `CompatibilityViolation` diagnostics. 4. **Zero Reader Impact**: The existing healthy epoch continues serving 100% of queries without latency spikes or restarts. --- ## 2. Kubernetes Probes (`startupProbe`, `readinessProbe`, `livenessProbe`) `ImpulseHealthIndicator` (zero external framework imports) exposes three distinct probe methods tailored to Kubernetes pod semantics: | Probe Method | Before Initial Mount | Active Epoch Healthy | Active Healthy + Candidate Swap Rejected (`swapDegraded=true`) | Purpose in Kubernetes | | :--- | :---: | :---: | :---: | :--- | | **`health.startup()`** | `DOWN` (503) | `UP` (200) | `UP` (200) | Gives the pod time to download the initial `.imps` from S3/GCS and run `mmap` + `MADV_WILLNEED` warmup without triggering `livenessProbe` kills. | | **`health.readiness()`** | `DOWN` (503) | `UP` (200) | **`UP` (200)** | Keeps the pod in Service endpoints when a bad upstream snapshot is rejected—because the prior valid epoch is still serving traffic! | | **`health.liveness()`** | `UP` (200) | `UP` (200) | **`UP` (200)** | Prevents cascading fleet-wide pod restart storms if S3 is unreachable or an upstream build breaks compatibility. | ### Wiring to Spring Boot Actuator or Lightweight HTTP Endpoints ```java import org.impulsegraph.storage.csr.ImpulseHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component("impulseGraph") public class ImpulseSpringHealthIndicator implements HealthIndicator { private final ImpulseHealthIndicator delegate; public ImpulseSpringHealthIndicator(BankGraphService service) { this.delegate = service.health(); } @Override public Health health() { ImpulseHealthIndicator.HealthReport report = delegate.readiness(); Health.Builder builder = (report.status() == ImpulseHealthIndicator.Status.UP) ? Health.up() : Health.down(); report.details().forEach(builder::withDetail); return builder.build(); } } ``` Expose dedicated `/healthz/startup`, `/healthz/ready`, and `/healthz/live` handlers mapped to `delegate.startup()`, `delegate.readiness()`, and `delegate.liveness()`, and configure your Kubernetes `Deployment`: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: bank-graph-service spec: replicas: 3 template: spec: containers: - name: app image: ghcr.io/example/bank-graph-service:1.2.0 env: - name: JAVA_TOOL_OPTIONS value: >- --add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED -Xms2g -Xmx4g -XX:+UseZGC -XX:+ZGenerational resources: requests: cpu: "2" memory: "16Gi" limits: memory: "16Gi" startupProbe: httpGet: path: /healthz/startup port: 8080 periodSeconds: 5 failureThreshold: 36 # Up to 180s for cold S3 download + mmap warmup readinessProbe: httpGet: path: /healthz/ready port: 8080 periodSeconds: 5 failureThreshold: 2 livenessProbe: httpGet: path: /healthz/live port: 8080 periodSeconds: 15 failureThreshold: 3 ``` Alert on `swapDegraded == true` (or `swapRejectedCount > 0` in Prometheus / JMX `ImpulseEngineMXBean`) rather than failing `livenessProbe`. --- ## 3. Rolling Zero-Downtime Schema Evolution (`Expand -> Migrate -> Contract`) `SnapshotContractValidator` and `impulse-j schema check-compat` enforce **consumer-driven structural subtyping**: a producer snapshot is valid for a consumer if and only if it provides at least the domains, relations, directions, and attribute contracts required by that consumer's `GraphManifest`. | Producer Change | Classification | Runtime & CI Behavior | | :--- | :---: | :--- | | Add a new Domain, Relation, or Attribute | **Safe (Additive)** | Existing consumer pods ignore unknown catalog entries and hot-swap cleanly. | | Add `CSC` (`in` direction) to an `[out]`-only relation | **Safe (Additive)** | Consumers requiring `[out]` continue walking CSR; new consumers can walk `[in]`. | | Narrow attribute from `nullable: true` to `nullable: false` | **Safe (Covariant)** | Consumers expecting `nullable: true` accept non-null snapshot columns. | | Remove a required Domain, Relation, or Attribute | **Breaking** | Rejected with `MISSING_DOMAIN`, `MISSING_RELATION`, or `MISSING_ATTRIBUTE`. | | Change attribute type or vector dimension (`float32[128]` → `float32[256]`) | **Breaking** | Rejected with `TYPE_MISMATCH` or `DIMENSION_MISMATCH`. | | Widen attribute from `nullable: false` to `nullable: true` | **Breaking** | Rejected with `NULLABILITY_MISMATCH` (prevents silent `0`/`""` reads on primitive getters). | | Drop `CSC` on a relation where consumer declares `directions: [out, in]` | **Breaking** | Rejected with `MISSING_DIRECTION`. | ### Three-Step Zero-Downtime Rollout Pattern To rename or replace an attribute (e.g., migrating `legacy_tier` to `kyc_tier`) without coordinating downtime between producer pipelines and Kubernetes deployments: 1. **Expand (Producer)**: Add `kyc_tier` alongside `legacy_tier` in the producer build. Run `impulse-j schema check-compat` against active v1 consumer schemas—all pass because `legacy_tier` is still present. Old pods hot-swap to the expanded snapshot seamlessly. 2. **Migrate (Consumers)**: Roll out v2 consumer pods whose `schema.yaml` requires `kyc_tier` and drops `legacy_tier` from its required contract (or marks `kyc_tier` `optional: true, since: "1.2.0"` if v2 code must deploy before the producer runs!). 3. **Contract (Producer)**: Once no v1 consumer pods remain active, remove `legacy_tier` from the producer manifest and update the CI `check-compat` consumer registry. --- ## 4. Kubernetes Memory Sizing & Avoiding the `cgroups v2` `mmap` `OOMKilled` Trap Understanding how the JVM and Linux `cgroups v2` account for memory-mapped `.imps` files is essential when setting Kubernetes `resources.limits.memory`: 1. **JVM Heap (`-Xmx`) & `-XX:MaxDirectMemorySize` Are Untouched**: `BinarySnapshotLoader` mounts `.imps` files via `FileChannel.map(FileChannel.MapMode.READ_ONLY, ...)`. Mapped segments consume **zero bytes** of Java heap (`-Xmx`) and are **not** counted against `-XX:MaxDirectMemorySize`. 2. **Linux `cgroups v2` Counts Resident Page Cache Toward `limits.memory`**: When query threads touch `.imps` pages (or `segment.load()` issues `MADV_WILLNEED`), the Linux kernel faults those 4KB pages into the OS page cache. Under `cgroups v2`, resident file-backed pages (`file` in `/sys/fs/cgroup/memory.stat`) count directly toward the container's `memory.max` (`resources.limits.memory`) alongside anonymous memory (`anon`). !!! warning "The High-`-Xmx` `OOMKilled` Anti-Pattern" Developers accustomed to heap-based caches often set `-Xmx14g` inside a `16Gi` container. Because JVM heap (`anon` memory) **cannot** be evicted to disk when Kubernetes disables swap, a `14Gi` heap + `1Gi` Metaspace/CodeCache/stacks leaves almost zero room in `memory.max` for the page cache or temporary native arenas—triggering a kernel `OOMKilled` (`exitCode: 137`)! ### Why Clean `READ_ONLY` `mmap` Pages Are Safe When `-Xmx` Is Lean Because `.imps` segments are mapped strictly **`READ_ONLY`**, every faulted snapshot page in the OS page cache is **clean** (unmodified relative to the backing file on NVMe/EBS/ephemeral storage). When container memory approaches `limits.memory`—including during a **Blue/Green hot-swap** while Epoch A is draining and Epoch B is warming up—the Linux kernel's `cgroups v2` page reclaimer seamlessly evicts cold clean `file` pages without invoking the OOM killer, **as long as non-reclaimable anonymous memory stays well below `limits.memory`**. ### Recommended Pod Memory Sizing Formula $$\text{Pod } \texttt{limits.memory} \;\ge\; \underbrace{\texttt{-Xmx}}_{\text{2–4 GiB}} \;+\; \underbrace{\text{JVM Non-Heap \& Query Pools}}_{\text{1–2 GiB}} \;+\; \underbrace{\text{Hot Working Set of } \texttt{.imps}}_{\text{1.0x Snapshot Size (or hot slice)}}$$ * **Keep `-Xmx` Small (`2Gi–4Gi`)**: With `ImpulseVM` and AOT `RowView` cursors allocating zero hot-path objects, `-Xmx` only serves HTTP/gRPC request/response DTOs. * **Set `requests.memory == limits.memory` (`Guaranteed` QoS)**: Prevents node-level memory pressure from preempting serving pods first. * **S3/GCS Staging Storage**: Mount an NVMe-backed `emptyDir` volume (not `emptyDir: { medium: Memory }` / `tmpfs`!) for local `.imps` staging. Never store `.imps` files on `tmpfs`, because `tmpfs` pages are accounted as non-evictable `shmem`/`anon` memory rather than reclaimable disk-backed page cache! For deeper JVM flag, Transparent Huge Pages, and `VmQueryContext` pool tuning, see **[Memory & Performance Tuning](../../deployment/memory-tuning.md)** and **[Capacity Growth](../../deployment/capacity-growth.md)**. ================================================================================ FILE: docs/ecosystems/java/jvm-languages.md | URL: https://www.impulsegraph.org/ecosystems/java/jvm-languages/ ================================================================================ # Kotlin, Scala 3, Clojure & Java API Reference Because `impulse-api` exposes clean Java interfaces without checked exceptions on traversal pipelines and `impulse-codegen` emits standard Java 21+ classes and `record` types, **Kotlin**, **Scala 3**, and **Clojure** applications can combine AOT-generated typed facades directly with Impulse's idiomatic JVM language extension modules (`0.10.0` on Maven Central; aligned via `impulse-bom` in `0.11.0`). --- ## 1. Kotlin (`org.impulsegraph:impulse-kotlin`) `impulse-kotlin` provides `@JvmInline` value classes (`NodeId`, `RelationName`), `ImpulseSnapshots.withSnapshot`, operator overloads, `Sequence` bitset adapters, `@ImpulseQueryDslMarker` query builders, and **Kotlin Coroutines** `suspend` wrappers (`executeAsync`, `awaitDrainedAsync`, `drainAndCloseAsync`). ### Dependency ```kotlin dependencies { implementation(platform("org.impulsegraph:impulse-bom:$impulseVersion")) implementation("org.impulsegraph:impulse-kotlin") implementation("org.impulsegraph:impulse-storage") implementation("org.impulsegraph:impulse-vm") implementation("org.impulsegraph:impulse-compiler") } ``` ### Pairing Kotlin with AOT-Generated Classes & Coroutines ```kotlin import com.example.bank.graph.AccountAttrs import com.example.bank.graph.BankGraphSnapshot import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.impulsegraph.api.bitset.ImpulseBitSet import org.impulsegraph.kotlin.NodeId import org.impulsegraph.kotlin.RelationName import org.impulsegraph.kotlin.asSequence import org.impulsegraph.kotlin.executeAsync import org.impulsegraph.kotlin.impulseQuery import java.lang.foreign.Arena import java.nio.file.Path import java.util.UUID // 1. Reusable compiled DSL pipeline using @JvmInline NodeId & RelationName val twoHopReachability = impulseQuery { input("Account", NodeId(0L)) repeat(2) { walkEdge(RelationName("transferredTo")) } filterWithCel("balance >= 10000.0") }.collectBitSet() // 2. Suspend function combining AOT-generated BankGraphSnapshot + Coroutine execution suspend fun inspectSuspectAccounts(impsFile: Path, userUuid: UUID): List = withContext(Dispatchers.IO) { Arena.ofShared().use { arena -> BankGraphSnapshot.open(impsFile, arena).use { snap -> // Schema-typed Kleisli traversal + CEL metamodel val ownedHighBalance = snap.accounts() .from( snap.users() .fromKey(userUuid) .outOwns() .toBitSet() ) .where(AccountAttrs.BALANCE.ge(25_000.0)) .toKeyList() // Or execute pre-built Kotlin DSL query asynchronously on underlying snapshot val reachableBits = snap.underlying().executeAsync(twoHopReachability, input = 0L) val reachableCount = reachableBits.asSequence().count() ownedHighBalance } } } ``` --- ## 2. Scala 3 (`org.impulsegraph:impulse-scala_3`) `impulse-scala_3` uses Scala 3 **opaque types** (`opaque type NodeId = Long`, `opaque type RelationName = String`), **context functions** (`ImpulseQueryDsl[R] ?=> Unit`) for receiver-less DSL blocks, `Using` / `Try` resource management, and `scala.concurrent.Future` (`executeAsync`). ### Dependency (`build.sbt`) ```scala libraryDependencies ++= Seq( "org.impulsegraph" % "impulse-scala_3" % impulseVersion, "org.impulsegraph" % "impulse-storage" % impulseVersion, "org.impulsegraph" % "impulse-vm" % impulseVersion, "org.impulsegraph" % "impulse-compiler" % impulseVersion ) ``` ### Scala 3 Context-Function DSL & AOT Interop ```scala import com.example.bank.graph.{AccountAttrs, BankGraphSnapshot} import org.impulsegraph.api.bitset.ImpulseBitSet import org.impulsegraph.scala.* import java.lang.foreign.Arena import java.nio.file.Path import java.util.UUID import scala.jdk.CollectionConverters.* import scala.util.Using // 1. Receiver-less Scala 3 context-function query definition val transitiveTransfers = impulseQuery[ImpulseBitSet] { input("Account", NodeId(0L)) repeatUntilStable { walkEdge(RelationName("transferredTo")) } filter("balance >= 5000.0") }.collectBitSet() // 2. Safe Arena + AOT facade management with scala.util.Using def activeAccountKeys(impsPath: Path, userId: UUID): List[Long] = Using.Manager { use => val arena = use(Arena.ofShared()) val snap = use(BankGraphSnapshot.open(impsPath, arena)) // Execute Scala 3 DSL query on the underlying snapshot: val reachableSet: Set[Int] = snap.underlying()(transitiveTransfers, 0L).toScalaSet // Combine with AOT-generated typed traversal: snap.users() .fromKey(userId) .outOwns() .where(AccountAttrs.FROZEN_REASON.isNull()) .toKeyList() .asScala .map(_.longValue()) .toList }.get ``` --- ## 3. Clojure (`org.impulsegraph:impulse-clojure`) Because `ImpulseVM`'s canonical compiler IR (`ImpScheme`) is an S-expression AST, Clojure integrates naturally as a homoiconic frontend (`org.impulsegraph.core`). `SnapshotWrapper` implements Clojure's `ILookup` (`(:owns snap)` returns the relation's edge count), `Counted` (`(count snap)`), `IDeref` (`@snap`), and `IImpulseSnapshot`. ### Dependency (`deps.edn`) ```clojure {:deps {org.impulsegraph/impulse-clojure {:mvn/version "0.10.0"} org.impulsegraph/impulse-storage {:mvn/version "0.10.0"} org.impulsegraph/impulse-vm {:mvn/version "0.10.0"} org.impulsegraph/impulse-compiler {:mvn/version "0.10.0"}} :aliases {:run {:jvm-opts ["--add-modules" "jdk.incubator.vector" "--enable-native-access=ALL-UNNAMED"]}}} ``` ### Homoiconic Pipeline, `defquery` & Prepared Statements ```clojure (ns example.bank (:refer-clojure :exclude [in]) (:require [org.impulsegraph.core :as imp])) ;; Define a reusable domain-bound Kleisli pipeline via defquery: (imp/defquery suspect-recipients [snap domain seed] (imp/out :owns) (imp/out-filtered :transferredTo "edge.amount > $minAmount") (imp/filter-nodes "balance >= 50000.0") (imp/with-param :minAmount 10000.0)) (imp/with-snapshot [snap "datasets/bank.imps"] ;; Keyword lookup on SnapshotWrapper returns edge count: (println "OWNS edges:" (:owns snap) "Domains:" (imp/domain-names snap)) ;; Inspect emitted ImpScheme S-Expression IR or materialize persistent set: (let [pipeline (suspect-recipients snap :User 0)] (println "ImpScheme IR:" (imp/to-scm-string pipeline)) (println "Matching Account Dense IDs:" (imp/to-set pipeline))) ;; Parameterized openCypher prepared statement: (imp/with-statement [stmt snap "MATCH (u:User)-[:owns]->(a:Account) WHERE a.balance >= $min RETURN a"] (imp/bind-params stmt {:min 25000.0}) (with-open [rows (.execute stmt)] (loop [acc []] (if (.next rows) (recur (conj acc (.getNodeId rows 0))) acc))))) ``` --- ## 4. Core Java SDK Reference & Aggregated Javadocs For low-level Java engine interfaces—including `ImpulseStatement` / `RowReader`, monoidic state reducers (`:MIN`, `:MAX`, `:SUM`, `:AVG`, `:ARGMIN`, `:ARGMAX`), and Multi-Lane Bit-Sliced Execution (`VmLaneFrontier`, `0xC0..0xCB`)—see: * **[Java SDK Reference (`impulse-graph-java`)](../../reference/java-api.md)** * **[Interactive Multi-Module Javadocs (`/javadoc/index.html`)](/javadoc/index.html)** ================================================================================ FILE: docs/ecosystems/python/index.md | URL: https://www.impulsegraph.org/ecosystems/python/ ================================================================================ # Python, Data Science & ML Hub The `impulse-graph` Python SDK embeds the C++20 `ImpulseVM` kernel via `pybind11` and maps immutable `.imps` binary snapshots directly off-heap. It lets Python data scientists, quantitative researchers, and ML engineers run multi-hop traversals, `openCypher` queries, and PyTorch/SciPy sparse matrix operations without loading edge dictionaries into the Python heap or duplicating graph memory across worker processes. --- ## 1. Guide Map | Guide | Focus | | :--- | :--- | | **[From NetworkX & Parquet in 5 Minutes](../../getting-started/from-networkx-and-parquet.md)** | End-to-end quickstart exporting DataFrames or NetworkX graphs to `.imps` and querying them in Python. | | **[Snapshots from Parquet & CSV](snapshots-from-parquet-csv.md)** | Complete `manifest.json` reference, `impulse build` pipeline, and CSV/Parquet-to-`.imps` compilation. | | **[PyTorch GNN Sampling, Embeddings & Vamana Vector Search](gnn-and-vector-search.md)** | Zero-copy `torch.Tensor` views, native C-ABI neighborhood sampling, Section 2.6 Vamana ANN (`0x08`), and two-stage quantized hybrid search. | | **[Python & PyTorch SDK Reference](../../reference/python-api.md)** | Full API table for `Snapshot`, `DomainView`, `Traversal`, `impulse_graph.vm.QueryBuilder`, and `Writer`. | | **[Polyglot Workflow](../../getting-started/polyglot-workflow.md)** · **[Ecosystems Overview](../index.md)** | Sharing a single `.imps` artifact across Python ETL, Rust/C++ engines, and Java 25 microservices. | --- ## 2. Installation (Zero JVM or Server Dependencies) Install the pre-built `impulse-graph` wheel from PyPI. Wheels for Linux (`manylinux` `x86_64`/`aarch64`), macOS (`macosx_11_0_arm64`), and Windows (`win_amd64`) statically embed `libimpulse_graph_static.a` with zero external C++ runtime dependencies: ```bash pip install impulse-graph==0.10.0 ``` To compile multi-million-edge `.parquet`, `.csv`, or `.tsv` tables into `.imps` snapshots from the command line, install the standalone `impulse-graph` (`impulse`) CLI binary from [GitHub Releases](https://github.com/impulse-graph/impulse-graph-core/releases) or Cargo: ```bash # Optional standalone CLI for Parquet/CSV compilation, RCM optimization, and validation cargo install --git https://github.com/impulse-graph/impulse-graph-core impulse-cli alias impulse="impulse-graph" ``` --- ## 3. Sub-Millisecond Off-Heap Mounting (`< 1 ms`) Opening an `.imps` file calls `mmap` (`MAP_SHARED`, read-only) on 128-byte-aligned CSR/CSC topology arrays and Structure-of-Arrays (SoA) attribute columns. No Python `dict` objects are allocated, and native `ImpulseVM` execution releases the Python GIL (`py::gil_scoped_release`): ```python from impulse_graph import Snapshot with Snapshot("hetionet.imps") as snap: print(f"Domains: {snap.domain_count()}, Relations: {snap.relation_count()}") ``` In empirical benchmarks on the Hetionet biomedical graph (`47K` nodes, `2.25M` edges; see [Benchmarks](../../benchmarks.md#22-multi-language-ffi-binding-overhead-hetionet-biomedical-graph-47k-nodes-225m-edges)): * **Cold Open Latency**: `< 1 ms` (`0.224 ms`–`0.400 ms`) via `mmap`, vs. `450 ms` for PyTorch Geometric in-memory CSR loading and `1,850 ms` for NetworkX dictionary construction. * **4-Hop Drug-Repurposing Traversal**: `24.2 µs` mean latency in Python (`impulse-python`), vs. `850.0 µs` (`35x` slower) in PyTorch Geometric CSR and `42,100.0 µs` (`1,739x` slower) in NetworkX. --- ## 4. Domain-Bound Fluent Traversals & Parameterized `openCypher` Every node domain in Impulse Graph (`User`, `Account`, `Gene`, `Compound`) owns an independent `0 .. N_d - 1` dense integer ID space. Anchor queries to an explicit domain via `snap.domain(...)` so key lookups, relation transitions, and attribute filters resolve against the active domain's catalog: ```python from impulse_graph import Snapshot with Snapshot("banking.imps") as snap: users = snap.domain("User") # 1. Domain-bound Kleisli set traversal: # Resolve "usr_101" -> walk OWNS -> walk TRANSFERRED_TO -> filter active Account domain recipient_keys = ( users.from_key("usr_101") .out("OWNS") .out("TRANSFERRED_TO") .filter("account.balance >= 1000.0") .to_key_list() ) # 2. Inspect generated ImpAsm (.impas) register instructions for any pipeline asm_listing = ( users.from_key("usr_101") .out("OWNS") .out("TRANSFERRED_TO") .to_impas() ) # 3. Declarative parameterized openCypher over the same off-heap snapshot uid = users.to_dense_id("usr_101") account_dense_ids = snap.cypher( """ MATCH (u:User)-[:OWNS]->(src:Account)-[:TRANSFERRED_TO]->(dst:Account) WHERE u.id = $uid RETURN dst """, params={"uid": uid}, ) ``` !!! warning "Avoid Client-Side Imperative Point-Lookup Loops" Never iterate over node IDs in a Python `for` loop calling single-node neighbor lookups hop-by-hop. Crossing the Python/C boundary per node discards SIMD bitset vectorization and cache locality. Express multi-hop walks, CEL `.filter(...)` predicates, and fixed-point loops (`impulse_graph.vm.QueryBuilder.repeat_until_stable`) inside a single engine pipeline. --- ## 5. Multi-Process Workers & PyTorch `DataLoader` (`0 Bytes` RAM Duplication) When Python `multiprocessing` or a PyTorch `DataLoader` (`num_workers > 0`) forks worker processes over a standard Python `dict` or NumPy heap array, reference-count updates on Python objects trigger OS Copy-on-Write (`CoW`) page faults—multiplying a `20 GB` graph into `160 GB` of physical RAM across 8 workers. With `.imps`, pass only the **file path string** to workers and open `Snapshot(path)` lazily inside each worker process. The operating system maps every worker onto the **exact same read-only physical page-cache frames**: ```python import numpy as np import torch from torch.utils.data import Dataset, DataLoader from impulse_graph import Snapshot class SubgraphBatchDataset(Dataset): def __init__(self, imps_path: str, seed_nodes: np.ndarray, k_neighbors: int = 15): self.imps_path = imps_path # Pickle only the path string across processes self.seed_nodes = seed_nodes self.k_neighbors = k_neighbors self._snap: Snapshot | None = None def _ensure_open(self) -> Snapshot: if self._snap is None: # Mapped read-only (MAP_SHARED) inside each worker process; shares OS page cache self._snap = Snapshot(self.imps_path) return self._snap def __len__(self) -> int: return len(self.seed_nodes) def __getitem__(self, idx: int): snap = self._ensure_open() seed = int(self.seed_nodes[idx]) src, tgt = snap.sample_neighbors( relation_index=0, nodes=[seed], k_samples=self.k_neighbors, seed=42 + idx ) return torch.from_numpy(src.astype(np.int64)), torch.from_numpy(tgt.astype(np.int64)) if __name__ == "__main__": seeds = np.arange(0, 10_000, dtype=np.uint64) ds = SubgraphBatchDataset("citations.imps", seeds, k_neighbors=15) # 4 worker processes share one OS page-cache mapping of citations.imps loader = DataLoader(ds, batch_size=64, num_workers=4, persistent_workers=True) ``` --- ## 6. Zero-Copy NumPy, SciPy CSR & DataFrame Views All CSR/CSC arrays (`row_offsets`, `col_indices`) and fixed-width SoA attribute columns in `.imps` implement the Python buffer protocol (`memoryview` $\to$ `np.frombuffer`), exposing read-only NumPy and SciPy views directly over mapped pages: ```python import numpy as np from impulse_graph import Snapshot with Snapshot("citations.imps") as snap: # 1. Zero-copy uint32 CSR views (no heap allocation) row_offsets: np.ndarray = snap.get_row_offsets_array(relation_index=0) col_indices: np.ndarray = snap.get_col_indices_array(relation_index=0) # 2. Zero-copy SoA edge weight vector [E] or node embedding matrix [N, D] edge_count = snap.get_relation(0)["edge_count"] weights: np.ndarray = snap.get_attribute_array( relation_index=0, attribute_index=0, dtype=np.float32, shape=(edge_count,) ) # 3. Direct interop with SciPy sparse linear algebra, PyTorch, Polars, and PyArrow scipy_csr = snap.to_scipy_csr(relation_index=0) torch_csr = snap.to_torch_csr(relation_index=0) arrow_tbl = snap.to_arrow_table(relation_index=0) polars_df = snap.to_polars(relation_index=0) ``` --- ## Next Steps * **[From NetworkX & Parquet in 5 Minutes](../../getting-started/from-networkx-and-parquet.md)** — Convert an existing DataFrame or NetworkX prototype into an `.imps` snapshot. * **[Snapshots from Parquet & CSV](snapshots-from-parquet-csv.md)** — Author multi-domain `manifest.json` pipelines and optimize cache locality with `--rcm`. * **[PyTorch GNN Sampling, Embeddings & Vamana Vector Search](gnn-and-vector-search.md)** — Train GNNs on graphs larger than RAM and run embedded two-stage quantized ANN search. * **[Python & PyTorch SDK Reference](../../reference/python-api.md)** — Complete method signatures and low-level `impulse_graph.vm` register builder. ================================================================================ FILE: docs/ecosystems/python/snapshots-from-parquet-csv.md | URL: https://www.impulsegraph.org/ecosystems/python/snapshots-from-parquet-csv/ ================================================================================ # Snapshots from Parquet & CSV (`impulse build`) If you use **Python, PyTorch, C/C++, Rust, Go, C#, or Node.js**—or want to compile `.imps` snapshots from **Apache Parquet, CSV, or TSV** files without writing Java code—the standalone **`impulse` CLI (binary: `impulse-graph`, aliased as `impulse`)** in `impulse-graph-core/impulse-cli` builds, inspects, validates, and optimizes snapshots directly from declarative manifests. !!! tip "Related Guides" * **New to Impulse in Python?** Start at the **[Python, Data Science & ML Hub](index.md)** or **[From NetworkX & Parquet in 5 Minutes](../../getting-started/from-networkx-and-parquet.md)**. * **Looking for the programmatic Java `SnapshotBuilder` & streaming JDBC guide?** See **[Building Snapshots in Java](../java/building-snapshots.md)**. Both the Java `SnapshotBuilder` and the native `impulse` CLI produce 100% bitwise-compatible `.imps` files that can be memory-mapped by any language SDK. --- ## 1. How `impulse build` Works Instead of writing imperative ingestion code, you export your node and edge tables from **DuckDB, Pandas, Polars, PyArrow, Spark, Snowflake, or PostgreSQL** to **Apache Parquet (`.parquet`)** or **CSV/TSV (`.csv`, `.tsv`)**, describe your domains and relations in a declarative `manifest.json`, and run: ```bash impulse build --manifest manifest.json -o graph.imps ``` Under the hood, `impulse build` automatically: 1. **Assigns Contiguous Dense IDs ($0 \dots N_d-1$) per Domain**: Scans your node files (or derives unique node keys directly from your edge files) and builds an embedded Minimal Perfect Hash (`_domain_index`) table for $O(1)$ key-to-dense-ID resolution at query time. 2. **Sorts Edges into Forward CSR & Reorders Edge Attributes**: Sorts edges by `(src_dense_id, tgt_dense_id)` to build the Compressed Sparse Row (`row_offsets[]`, `col_indices[]`) arrays and reorders all edge attribute columns in lockstep so `edge_attr[k]` aligns with `col_indices[k]`. 3. **Optionally Builds Reverse CSC (`"include_csc": true`)**: Transposes the CSR matrix into Compressed Sparse Column arrays so reverse traversals (`.in(...)` and `<-[]-` in openCypher) run at the exact same speed as forward traversals. 4. **Aligns All Sections to 128 Bytes**: Pads every CSR/CSC array, Structure-of-Arrays (SoA) attribute column, and fixed-width vector embedding to 128-byte boundaries (2 CPU cache lines / AVX-512 / GPU `cuFile` warp alignment) and seals the snapshot with a Page 0 header and SHA-256 footer. ### Installing the `impulse` CLI ```bash # Install from source (Rust 1.80+) git clone https://github.com/impulse-graph/impulse-graph-core.git cargo install --path impulse-graph-core/impulse-cli # Alias for 'impulse': alias impulse="impulse-graph" ``` --- ## 2. Walkthrough 1: From CSV Files to Python Queries Let's build the exact same **banking graph** (`User -[:OWNS]-> Account -[:TRANSFERRED_TO {amount}]-> Account`) from the [Java Builder Guide](../java/building-snapshots.md), using CSV files and querying it in Python. ``` (User: "usr_101") ──[:OWNS]──> (Account: "acc_5001") ──[:TRANSFERRED_TO {amount: 2500.00}]──> (Account: "acc_7008") ``` ### Step 1: Prepare the CSV Files Create four CSV files in a `bank_data/` directory: === "`bank_data/users.csv`" ```csv user_id,name,age,risk_score usr_101,Alice,34,0.12 usr_102,Bob,29,0.05 usr_103,Charlie,52,0.88 ``` === "`bank_data/accounts.csv`" ```csv account_id,balance acc_5001,14200.50 acc_6004,890.00 acc_7008,53100.00 ``` === "`bank_data/owns.csv`" ```csv user_id,account_id usr_101,acc_5001 usr_102,acc_6004 usr_103,acc_7008 ``` === "`bank_data/transfers.csv`" ```csv from_account,to_account,amount,timestamp_ms acc_5001,acc_6004,450.00,1711929600000 acc_5001,acc_7008,2500.00,1711933200000 acc_6004,acc_7008,1200.00,1711936800000 ``` ### Step 2: Create `manifest.json` Create `bank_data/manifest.json` mapping the two domains (`User` = `0`, `Account` = `1`), their node attributes, and the two directed relations (`OWNS` and `TRANSFERRED_TO`). Because `impulse build` resolves `"file"` paths relative to the directory containing `manifest.json` (`bank_data/`), reference the CSV filenames directly: ```json { "domains": [ { "id": 0, "name": "User", "key_type": "string", "file": "users.csv", "id_column": "user_id", "attributes": [ { "name": "name", "column": "name", "type": "string" }, { "name": "age", "column": "age", "type": "int32" }, { "name": "risk_score", "column": "risk_score", "type": "float32" } ] }, { "id": 1, "name": "Account", "key_type": "string", "file": "accounts.csv", "id_column": "account_id", "attributes": [ { "name": "balance", "column": "balance", "type": "float64" } ] } ], "relations": [ { "name": "OWNS", "src_domain": 0, "tgt_domain": 1, "file": "owns.csv", "src_column": "user_id", "tgt_column": "account_id", "include_csc": true }, { "name": "TRANSFERRED_TO", "src_domain": 1, "tgt_domain": 1, "file": "transfers.csv", "src_column": "from_account", "tgt_column": "to_account", "include_csc": true, "attributes": [ { "name": "amount", "column": "amount", "type": "float64" }, { "name": "timestamp_ms", "column": "timestamp_ms", "type": "int64" } ] } ] } ``` ### Step 3: Build, Inspect & Validate Run `impulse build` to compile `banking.imps`, then inspect and validate it: ```bash # 1. Compile CSVs into an .imps binary snapshot impulse build --manifest bank_data/manifest.json -o banking.imps # 2. Inspect domains, relations, attribute columns, and section offsets impulse snapshot inspect banking.imps --verbose # 3. Verify alignment, monotonic CSR offsets, and SHA-256 checksum impulse snapshot validate banking.imps --strict-alignment ``` ### Step 4: Mount and Query in Python Open `banking.imps` in Python (`pip install impulse-graph`): ```python from impulse_graph import Snapshot with Snapshot("banking.imps") as snap: print(f"Domains: {snap.domain_count()}, Relations: {snap.relation_count()}") # 1. Domain-bound Fluent Traversal from User "usr_101": # Walk OWNS -> walk TRANSFERRED_TO -> return reached Account keys and dense IDs users = snap.domain("User") reached_account_keys = ( users.from_key("usr_101") .out("OWNS") .out("TRANSFERRED_TO") .to_key_list() ) print("Accounts reached from usr_101:", reached_account_keys) # 2. Parameterized openCypher Query over the same memory-mapped snapshot: high_value_recipients = snap.cypher( """ MATCH (u:User)-[:OWNS]->(src:Account)-[:TRANSFERRED_TO]->(dst:Account) WHERE u.id = $user_id RETURN dst """, params={"user_id": 0}, catalog={"OWNS": 0, "TRANSFERRED_TO": 1}, ) print("Destination Account dense IDs:", high_value_recipients) ``` --- ## 3. Walkthrough 2: From Apache Parquet to PyTorch & GNNs If your data lives in **Apache Parquet** (from PyArrow, Pandas, Polars, DuckDB, or Spark) and your destination is **PyTorch / PyG**, `impulse build` reads `.parquet` files natively—including fixed-size vector embeddings (`FixedSizeListArray`) and nullable Arrow validity bitmaps. Once compiled, PyTorch mounts the `.imps` file directly via `torch.from_numpy()` and shares the OS page cache across `DataLoader` workers (see [PyTorch GNN Sampling, Embeddings & Vamana Vector Search](gnn-and-vector-search.md) and [PyTorch & GNN Showcase](../../showcase/gnn.md)). ### Step 1: Export Node & Edge Tables to Parquet (Python / PyArrow) Here we generate a synthetic citation graph (`papers.parquet` with 128-dimensional `float32` feature vectors and `citations.parquet` with edge weights): ```python import numpy as np import pyarrow as pa import pyarrow.parquet as pq num_papers = 10_000 num_edges = 80_000 feat_dim = 128 # 1. Build papers.parquet with scalar attributes + 128-D float32 embedding column rng = np.random.default_rng(42) flat_features = rng.standard_normal(num_papers * feat_dim, dtype=np.float32) feature_list_array = pa.FixedSizeListArray.from_arrays(pa.array(flat_features), feat_dim) papers_table = pa.table({ "paper_id": pa.array([f"paper_{i}" for i in range(num_papers)], type=pa.string()), "year": pa.array(rng.integers(2015, 2026, size=num_papers, dtype=np.int32)), "label": pa.array(rng.integers(0, 10, size=num_papers, dtype=np.int32)), "features": feature_list_array, }) pq.write_table(papers_table, "papers.parquet") # 2. Build citations.parquet (directed edges: citing_id -> cited_id) src_idx = rng.integers(0, num_papers, size=num_edges) tgt_idx = rng.integers(0, num_papers, size=num_edges) citations_table = pa.table({ "citing_id": pa.array([f"paper_{i}" for i in src_idx], type=pa.string()), "cited_id": pa.array([f"paper_{i}" for i in tgt_idx], type=pa.string()), "weight": pa.array(rng.uniform(0.1, 1.0, size=num_edges).astype(np.float32)), }) pq.write_table(citations_table, "citations.parquet") ``` ### Step 2: Create `citation_manifest.json` Point `domains` and `relations` directly at the `.parquet` files. Notice `"dimension": 128` on the `features` attribute—`impulse build` writes the 128-dimensional `float32` vectors as a contiguous `[N, 128]` tensor block inside the `.imps` file: ```json { "domains": [ { "id": 0, "name": "Paper", "key_type": "string", "file": "papers.parquet", "format": "parquet", "id_column": "paper_id", "attributes": [ { "name": "year", "column": "year", "type": "int32" }, { "name": "label", "column": "label", "type": "int32" }, { "name": "features", "column": "features", "type": "float32", "dimension": 128 } ] } ], "relations": [ { "name": "CITES", "src_domain": 0, "tgt_domain": 0, "file": "citations.parquet", "format": "parquet", "src_column": "citing_id", "tgt_column": "cited_id", "include_csc": true, "attributes": [ { "name": "weight", "column": "weight", "type": "float32" } ] } ] } ``` ### Step 3: Compile & Optimize CSR Locality (`--rcm`) Compile the Parquet files into an `.imps` snapshot, and optionally run `impulse snapshot optimize --rcm` (Reverse Cuthill-McKee bandwidth reduction) so that densely connected nodes are placed adjacent to one another in memory for higher L2/L3 cache hit rates during GNN message passing: ```bash # 1. Compile Parquet files into raw .imps snapshot impulse build --manifest citation_manifest.json -o citations_raw.imps # 2. Reorder dense IDs with Reverse Cuthill-McKee (RCM) to minimize CSR cache misses impulse snapshot optimize -i citations_raw.imps -o citations.imps --rcm --csc # 3. Inspect degree distribution & supernodes (statistical Z-score threshold, default 3.0) impulse snapshot stats citations.imps --supernode-threshold 3.0 ``` ### Step 4: Mount in PyTorch (`impulse-gnn`) !!! note "Showcase Package (`impulse-gnn`)" `impulse_gnn` lives in the [impulse-gnn](https://github.com/impulse-graph/impulse-gnn) showcase repository (not published on PyPI). Install it from a local clone with `pip install -e .`. Load `citations.imps` in PyTorch. CSR arrays (`row_offsets`, `col_indices`) and node attributes are exposed as read-only `torch.Tensor` views: ```python import torch from impulse_gnn import ImpulseGnnDataset, ImpulseNeighborSampler # 1. Open citations.imps directly from disk dataset = ImpulseGnnDataset("citations.imps") print(f"Nodes: {dataset.node_count:,}, Edges: {dataset.edge_count:,}") # 2. Read-only tensor views over the CSR arrays row_offsets: torch.Tensor = dataset.row_offsets # torch.uint32 [node_count + 1] col_indices: torch.Tensor = dataset.col_indices # torch.uint32 [edge_count] # 3. Sample 2-hop GraphSAGE mini-batches (25 neighbors at hop 1, 10 at hop 2) sampler = ImpulseNeighborSampler(dataset, sizes=[25, 10]) seed_nodes = torch.arange(0, 1024, dtype=torch.int32) subgraphs = sampler.sample(seed_nodes.tolist()) print(f"Sampled {len(subgraphs)} hops; hop-0 edges: {subgraphs[0].shape[1]}") # 4. Also interoperates with SciPy / NetworkX / GraphBLAS: csr_mat = dataset.to_scipy_csr() ``` !!! tip **Want to learn more about PyTorch GNN training, embedded Vamana ANN (`0x08`), and graphs larger than RAM?** See **[PyTorch GNN Sampling, Embeddings & Vamana Vector Search](gnn-and-vector-search.md)** and the **[PyTorch & Graph Neural Networks Showcase](../../showcase/gnn.md)**. --- ## 4. `manifest.json` Complete Reference A `manifest.json` file contains two top-level arrays: `"domains"` and `"relations"`. ### 4.1 `domains[]` Schema Each object in `"domains"` defines an independent node domain with its own contiguous dense ID space ($0 \dots N_d-1$): | Field | Type | Required | Description | | :--- | :--- | :--- | :--- | | `id` | `u16` | **Yes** | Unique numeric domain ID (`0`, `1`, `2`, ...). Referenced by `src_domain` and `tgt_domain` in `relations[]`. | | `name` | `string` | **Yes** | Logical domain name used in queries (e.g., `"User"`, `"Account"`, `"Paper"`). | | `key_type` | `string` | **Yes** | Data type of the external primary key: `"string"`, `"int64"`, `"uint64"`, `"uuid"`, `"int32"`, or `"uint16"`. | | `file` | `string` | No | Path to the node table file (`.parquet`, `.pq`, `.csv`, `.tsv`), resolved relative to the directory containing `manifest.json`. If omitted, the domain's unique keys and node count are inferred automatically from the edge files that reference this domain. | | `format` | `string` | No | `"parquet"`, `"csv"`, or `"tsv"`. Auto-detected from the file extension if omitted. | | `id_column` | `string` | No | Column name containing the primary key in `file`. Defaults to `"id"` (or column `0` in headerless CSVs). | | `attributes` | `AttributeDef[]` | No | List of node attribute columns to extract from `file` into SoA columns. | ### 4.2 `relations[]` Schema Each object in `"relations"` defines a directed edge relation from `src_domain` to `tgt_domain`: | Field | Type | Required | Description | | :--- | :--- | :--- | :--- | | `name` | `string` | No | Relation name used in `.out("NAME")` / `.in("NAME")` and openCypher `[:NAME]`. Defaults to `"REL_{src}_{tgt}"` if omitted. | | `src_domain` | `u16` | **Yes** | Numeric `id` of the source domain. | | `tgt_domain` | `u16` | **Yes** | Numeric `id` of the target domain. | | `file` | `string` | **Yes** | Path to the edge table file (`.parquet`, `.pq`, `.csv`, `.tsv`, `.txt`), resolved relative to the directory containing `manifest.json`. | | `format` | `string` | No | `"parquet"`, `"csv"`, or `"tsv"`. Auto-detected from the file extension if omitted. | | `src_column` | `string` | No | Column name for the source node key. Defaults to `"src"` (or column `0` in CSV/TSV). | | `tgt_column` | `string` | No | Column name for the target node key. Defaults to `"tgt"` (or column `1` in CSV/TSV). | | `include_csc` | `bool` | No | When `true`, builds both forward **CSR** and reverse **CSC** topologies so `.in(...)` reverse walks execute in $O(1)$ offset lookup time. Defaults to `false`. | | `encoding` | `string` | No | Target adjacency list encoding: `"raw"` (default uncompressed arrays). Compressed gap encodings (`"elias_fano"`, `"bic"`) are planned for future specifications. | | `attributes` | `AttributeDef[]` | No | List of edge attribute columns to extract from `file` and reorder alongside the CSR edges. | ### 4.3 `attributes[]` Schema & Supported Data Types Both domains and relations accept an `"attributes"` array where each element has: ```json { "name": "amount", "column": "transfer_amount_usd", "type": "float64", "dimension": 1 } ``` * **`name`** *(required)*: Attribute name exposed to queries (`node.amount`, `edge.amount`). * **`column`** *(required)*: Source column name in the Parquet or CSV/TSV file. * **`type`** *(optional for Parquet, recommended for CSV)*: Explicit storage type. For Parquet inputs, `impulse build` automatically infers the Impulse type from the Arrow column schema if `"type"` is omitted. * **`dimension`** *(optional)*: Defaults to `1` (scalar). Set `"dimension": D` (e.g., `128`, `384`, `768`) for fixed-width vector embeddings stored in Parquet `FixedSizeListArray` columns. | Type String in `manifest.json` | Physical Layout in `.imps` | Parquet / Arrow Source Types | | :--- | :--- | :--- | | `"int8"`, `"int16"`, `"int32"`, `"int64"` | Signed 8 / 16 / 32 / 64-bit integer array | `Int8`, `Int16`, `Int32`, `Int64` | | `"uint8"`, `"uint16"`, `"uint32"`, `"uint64"` | Unsigned 8 / 16 / 32 / 64-bit integer array | `UInt8`, `UInt16`, `UInt32`, `UInt64` | | `"float16"`, `"float32"`, `"float64"` | IEEE-754 16 / 32 / 64-bit float array | `Float16`, `Float32`, `Float64` | | `"bool"` / `"boolean"` | 8-bit boolean array (`1 byte` per element, `INT8` `0x01`). (Note: Nullability bitmaps for nullable attributes are bit-packed at 1 bit per element). | `Boolean` | | `"timestamp_ms"`, `"timestamp_ns"`, `"date32"` | 64-bit epoch timestamp (`ms` / `ns`) or 32-bit days | `Timestamp(Millisecond/Second/Microsecond/Nanosecond)`, `Date32`, `Date64` | | `"string"` | Variable-length UTF-8 (`VAR_STRING` `0x0B`): per-column 128B-aligned `uint32_t offsets[K+1]` array + contiguous UTF-8 byte blob in Section 4 (note: Section 2 Shared String Pool stores only schema catalog identifiers) | `Utf8`, `LargeUtf8` | | `"uuid"` | 128-bit (`16-byte`) fixed-width binary UUID (`FIXED_BYTES` `0x0A`, `dim = 16`) | `FixedSizeBinary(16)` or UUID string | | **Nullable Suffix (`"?"`)** (e.g. `"float64?"`, `"int32?"`) | Prepends an aligned Arrow validity bitmap (`1` = valid, `0` = null) before the data array | Any nullable Parquet column or CSV column with empty cells | !!! note **Primary Key Catalog vs. Programmatic & Vector Secondary Indices (`Section 2.6`)**: When `impulse build` compiles a `manifest.json`, it automatically builds the primary key lookup index (`_domain_index`) and attribute min/max metadata for each domain. Embedded DiskANN/Vamana vector indices (`0x08` `IMP_INDEX_VAMANA_ANN`, `v0.10.0`) can be built directly from the CLI via `--embeddings ` and `--vector-index ` on `impulse build`, `impulse snapshot attach-embeddings`, or `impulse snapshot optimize`. Additional secondary indices (`0x01` Permutation, `0x02` ZoneMap, `0x03` InvertedBitset, `0x04` MinimalPerfectHash, `0x05` Trigram, `0x06` DomainSplitBitset, `0x07` TemporalInterval, `0x08` VamanaANN) can also be constructed programmatically via the C-ABI (`impulse_index_build_*` + `impulse_writer_add_index` in `impulse_index.h`) or Rust `SnapshotWriter::add_index` / `SnapshotWriter::add_built_vamana_index`. --- ## 5. Snapshot CLI Lifecycle Cheat Sheet Beyond `impulse build`, the `impulse` CLI provides a complete toolkit for inspecting, validating, optimizing, diffing, and exporting `.imps` snapshots: | Command | Example | Purpose | | :--- | :--- | :--- | | **`build`** | `impulse build --manifest manifest.json -o graph.imps` | Compiles CSV, TSV, or Parquet node/edge files into an `.imps` snapshot (supports `--embeddings` and `--vector-index`). Pass `-o -` to stream to `stdout` (e.g., `impulse build -m manifest.json -o - \| aws s3 cp - s3://bucket/graph.imps`). | | **`snapshot attach-embeddings`** | `impulse snapshot attach-embeddings -i base.imps -o vec.imps --embeddings "Paper.emb=vecs.npy:dim=768:norm=l2" --vector-index "Paper.emb:R=32:L=64:quant=sq8"` | Attaches external embedding files (`.npy`, `.fvecs`, `.safetensors`, `.parquet`, `.jsonl`, `.csv`) and optional Section 2.6 Vamana ANN indices (`0x08`) to an existing `.imps` snapshot. | | **`bench-vector`** | `impulse bench-vector -n 10000 -d 128 --ef-search 16,32,64 --compare-optimize` | Runs the empirical Vamana ANN (`IMP_INDEX_VAMANA_ANN = 0x08`) construction, two-stage quantized beam search (`NONE`, `FP16`, `SQ8`, `BQ1`), and `Recall@K` / QPS benchmark suite. | | **`snapshot inspect`** | `impulse snapshot inspect graph.imps --verbose` | Prints Page 0 header flags, domain cardinalities, relation encodings, attribute schemas, and byte offsets (supports `--format json`). | | **`snapshot validate`** | `impulse snapshot validate graph.imps --strict-alignment --deep-audit` | Verifies magic bytes, section alignment, monotonic CSR/CSC offset bounds, Vamana ANN invariants (`--quick-check` / `--deep-audit`), and the footer SHA-256 checksum. | | **`snapshot stats`** | `impulse snapshot stats graph.imps --supernode-threshold 3.0` | Computes min/max/mean/p99 out-degree distributions, sparsity, multiplicity, and flags high-degree supernodes exceeding the statistical Z-score threshold (default `3.0`). | | **`snapshot optimize`** | `impulse snapshot optimize -i raw.imps -o opt.imps --rcm --vamana-locality --csc` | Reorders domain dense IDs via **Reverse Cuthill-McKee (`--rcm`)**, **Vamana Medoid BFS (`--vamana-locality`)**, or **Degree Sorting (`--degree-sort`)** to maximize CPU cache locality, and optionally generates missing CSC reverse indices (`--csc`). | | **`snapshot diff`** | `impulse snapshot diff v1.imps v2.imps` | Compares two `.imps` snapshots and reports added/removed domains, relations, node/edge count deltas, and attribute layout changes. | | **`snapshot export`** | `impulse snapshot export graph.imps -o out_dir/ --format csv` | Exports the topology of an `.imps` snapshot back to `csv`, `tsv`, or `jsonl` files. | | **`snapshot convert-tensors`** | `impulse snapshot convert-tensors -i model.safetensors -o weights.imps --domain Layer` | Converts HuggingFace `.safetensors` archives into `.imps` vector attribute columns (with optional `--vector-index`). | --- ## 6. Official Programmatic Snapshot Writers & Format Compliance Always generate `.imps` snapshots using `impulse build` or the official writer APIs rather than ad-hoc scripts writing raw binary bytes: * **CLI (CSV / TSV / Apache Parquet)**: `impulse build --manifest manifest.json -o graph.imps` (or `impulse generate` for synthetic topologies). * **Java 21 LTS / Java 25 (`SnapshotBuilder`)**: `org.impulsegraph.builder.api.SnapshotBuilder` ([Building Snapshots in Java](../java/building-snapshots.md)). * **Rust (`SnapshotWriter`)**: `impulse_graph::SnapshotWriter` in `impulse-rust` ([Rust Crate Reference](../../reference/rust-api.md)). * **C / C++20 (`impulse_writer_*` C-ABI)**: `impulse_writer_create` / `impulse_writer_finalize` in `impulse_graph.h` ([C-ABI & C++20 Reference](../../reference/c-abi.md)). If you are implementing a custom writer: 1. Follow the **[Binary Snapshot Format Specification](../../reference/spec/format-specification.md)** for exact header, catalog, CSR/CSC, and footer offsets. 2. Validate output with: ```bash impulse snapshot validate output.imps --strict-alignment impulse snapshot inspect output.imps --verbose ``` 3. Cross-check against the specification test vectors (`tc01`–`tc38`; see [Polyglot Validation](../../contributing/polyglot-validation.md)). --- ## Next Steps * **[Python, Data Science & ML Hub](index.md)** — Multi-process workers, fluent traversals, and zero-copy NumPy/SciPy views. * **[PyTorch GNN Sampling, Embeddings & Vamana Vector Search](gnn-and-vector-search.md)** — Disk-backed GNN sampling and two-stage quantized vector search. * **[Changing Data & Live Updates](../../getting-started/handling-mutations.md)** — Periodic rebuilds, S3/GCS distribution, and Blue/Green swaps. * **[Building Snapshots in Java](../java/building-snapshots.md)** — Programmatic Java `SnapshotBuilder` and streaming JDBC `RelationDataSource`. * **[Python SDK Reference](../../reference/python-api.md)** & **[CLI Reference](../../reference/cli.md)** — Complete Python API and CLI command syntax. ================================================================================ FILE: docs/ecosystems/python/gnn-and-vector-search.md | URL: https://www.impulsegraph.org/ecosystems/python/gnn-and-vector-search/ ================================================================================ # PyTorch GNN Sampling, Embeddings & Vamana Vector Search Impulse Graph pairs 128-byte-aligned CSR/CSC graph topology with contiguous `[N, D]` `float32` embedding columns and embedded **Section 2.6 Vamana (DiskANN) proximity graphs (`IMP_INDEX_VAMANA_ANN = 0x08`, `v0.10.0`)** inside a single `.imps` file. PyTorch, `impulse-gnn`, and `ImpulseVM` read both graph structure and embeddings directly from the OS page cache without heap deserialization. --- ## 1. Zero-Copy CSR Topology & `[N, D]` Feature Tensors When `impulse build` compiles a Parquet `FixedSizeListArray` column (or attaches an external `.npy` / `.safetensors` matrix), the resulting `.imps` file stores node features as a contiguous, 128-byte-aligned `[N, D]` array alongside `uint32` CSR `row_offsets` and `col_indices`. In Python, `np.frombuffer` and `torch.from_numpy` wrap those mapped pages directly—avoiding the `16 bytes/edge` `[2, E]` `int64` `edge_index` expansion and decompression overhead of loading raw Parquet files on startup: | Capability | `Parquet -> PyTorch` | `Impulse (.imps) -> PyTorch` | | :--- | :--- | :--- | | **Cold Open Latency** | Seconds to minutes (decompress, hash string keys, sort edges) | Direct `mmap` (`< 1 ms`; `0.224 ms`–`0.400 ms`) | | **Topology Footprint** | `16 bytes/edge` (`[2, E]` `int64` PyG `edge_index`) | `~4 bytes/edge` (`uint32` CSR `col_indices` + `row_offsets`) | | **Multi-Worker `DataLoader`** | Forked workers trigger Python CoW page duplication | Workers share read-only OS page-cache frames (`0 bytes` duplicated) | | **Larger-Than-RAM Graphs** | Manual shard orchestration | OS demand-pages 4KB blocks from NVMe automatically | ```python import numpy as np import torch from impulse_graph import Snapshot with Snapshot("citations.imps") as snap: # 1. Zero-copy CSR topology tensors (uint32 views over mmap) row_offsets = torch.from_numpy(snap.get_row_offsets_array(relation_index=0)) col_indices = torch.from_numpy(snap.get_col_indices_array(relation_index=0)) # 2. Convert directly to torch.sparse_csr_tensor for sparse linear algebra adj_csr: torch.Tensor = snap.to_torch_csr(relation_index=0) # 3. Zero-copy edge weight or feature tensor view edge_count = snap.get_relation(0)["edge_count"] edge_weights = torch.from_numpy( snap.get_attribute_array(0, 0, dtype=np.float32, shape=(edge_count,)) ) ``` --- ## 2. Disk-Backed Neighborhood Sampling (`impulse-gnn` & C-ABI) For multi-hundred-gigabyte graphs on developer laptops or single-GPU training nodes, `Snapshot.sample_neighbors` (delegating to the C-ABI `impulse_snapshot_sample_neighbors` kernel with deterministic PCG32 seeding) and the [`impulse-gnn`](https://github.com/impulse-graph/impulse-gnn) showcase package sample $k$-hop mini-batches directly over memory-mapped CSR arrays without materializing the full graph in Python RAM. !!! note "Installing `impulse-gnn`" `impulse_gnn` is maintained in the [impulse-graph/impulse-gnn](https://github.com/impulse-graph/impulse-gnn) showcase repository (see [PyTorch & GNN Showcase](../../showcase/gnn.md)). Clone it locally and install with `pip install -e .`. ```python import torch from impulse_gnn import ImpulseGnnDataset, ImpulseNeighborSampler # Open citations.imps directly from NVMe via mmap with ImpulseGnnDataset("citations.imps", relation_index=0) as dataset: # Expose mmap-backed CSR tensors row_offsets: torch.Tensor = dataset.row_offsets col_indices: torch.Tensor = dataset.col_indices # Multi-hop GraphSAGE fanout sampler (25 neighbors at hop 1, 10 at hop 2) # Delegates each hop to C++ snapshot.sample_neighbors with deterministic per-hop seeds sampler = ImpulseNeighborSampler(dataset, sizes=[25, 10], seed=42) batch_seeds = torch.arange(0, 1024, dtype=torch.int32) hop_edge_indices: list[torch.Tensor] = sampler.sample(batch_seeds) print(f"Sampled {len(hop_edge_indices)} hops; hop-0 shape: {hop_edge_indices[0].shape}") ``` ### GPU Sliced ELLPACK (`0x05`) & Empirical SpMM Benchmarks Standard CSR (`RAW_UINT32 = 0x00`) has variable row lengths that can cause warp divergence on power-law graphs. Optimizing a snapshot with `--encoding sliced_ellpack` (`0x05`) packs rows into 2D slice tiles for coalesced GPU reads. On Apple M5 GPU (Metal) over a `100K`-node, `1M`-edge graph with `128`-dimensional `float32` features (see [PyTorch & GNN Showcase](../../showcase/gnn.md#3-empirical-benchmarks-apple-m5-gpu-metal)): * **SciPy CPU `csr_matrix`**: `0.327 ms` open, `40.860 ms` SpMM (`1.0x` baseline). * **PyTorch CPU CSR**: `0.571 ms` open, `16.515 ms` SpMM (`2.5x`). * **Impulse Mapped CSR (`RAW_UINT32`, GPU)**: `0.224 ms` open, `4.435 ms` SpMM (`9.2x`). * **Impulse Sliced ELLPACK (`0x05`, GPU)**: `0.247 ms` open, `0.005 ms` (`5 µs`) asynchronous command-buffer dispatch (`~0.8–1.2 ms` with `torch.mps.synchronize()`, `~35x–50x` faster than SciPy CPU). * **Qwen 1.5 MoE Router Index (`3.72 GB` weights)**: `.imps` mounts in `0.400 ms` and evaluates first-token routing in `0.402 ms` with `0 Bytes` heap copy, compared to `16.433 ms` open and `305.788 ms` TTFT (`~3.72 GB` heap copy) for raw `safetensors`. --- ## 3. Embedding Ingestion & Embedded Vamana ANN (`v0.10.0`, Section 2.6 `0x08`) Starting in `v0.10.0`, `.imps` natively embeds single-layer **DiskANN / Vamana proximity graphs** (`IMP_INDEX_VAMANA_ANN = 0x08`, magic `0x56414D41` `"VAMA"`) in Section 2.6 alongside `[N, D]` `float32` node attributes (see [Format Specification §3.5.2](../../reference/spec/format-specification.md)). Each Vamana index stores: 1. **64-Byte `VamanaHeader`**: Metric (`l2`, `cosine`, `dot`, `hamming`), quantization mode (`none`, `bq1`, `sq8`, `fp16`), `max_degree_r` ($R$), `medoid_node_id` ($m^*$), diversity `alpha` ($\alpha$), and `ef_construction` ($L_{\text{build}}$). 2. **128-Byte-Aligned Fixed-Degree Adjacency Slab**: $N \times (R + 1) \times 4$ bytes (`[deg, nb_0, ..., nb_{deg-1}, 0xFFFFFFFF, ...]`) for branch-predictable fixed-stride neighbor fetches. 3. **128-Byte-Aligned Quantized Routing Slab**: Compact vector codes (`BQ1` 1-bit binary, `SQ8` 8-bit scalar, or `FP16` half-precision) scanned during beam search to cut DRAM bandwidth before exact `float32` reranking. ### 3.1 Building Snapshots with Embeddings & Vamana Indices You can embed vectors and construct Section 2.6 Vamana indices in three ways via the `impulse` CLI (see [CLI Reference](../../reference/cli.md)): === "1. Build from `manifest.json` + `.npy` / `.parquet`" ```bash # Compile topology from manifest.json, attach L2-normalized 768-D NumPy embeddings, # and build an SQ8-quantized Vamana index (R=32, L=64, alpha=1.2) in a single pass: impulse build --manifest citation_manifest.json -o citations_vec.imps \ --embeddings "Paper.embedding=paper_vecs.npy:format=npy:dim=768:norm=l2" \ --vector-index "Paper.embedding:R=32:L=64:alpha=1.2:metric=cosine:quant=sq8" ``` === "2. Attach Embeddings to an Existing `.imps`" ```bash # Attach .npy, .fvecs, .bvecs, .safetensors, .parquet, .jsonl, or .csv embeddings # to an already-compiled .imps snapshot without re-ingesting edge CSVs: impulse snapshot attach-embeddings \ -i citations_base.imps \ -o citations_vec.imps \ --embeddings "Paper.embedding=paper_vecs.npy:dim=768:norm=l2" \ --vector-index "Paper.embedding:R=32:L=64:alpha=1.2:metric=cosine:quant=sq8" ``` === "3. Convert HuggingFace `.safetensors`" ```bash # Convert a .safetensors checkpoint directly into a domain with an embedded Vamana index: impulse snapshot convert-tensors \ -i embeddings.safetensors \ -o weights_vec.imps \ --domain Paper \ --vector-index "R=32:L=64:metric=cosine:quant=sq8" ``` ### 3.2 Medoid BFS Cache-Locality Optimization (`--vamana-locality`) During greedy beam search from `medoid_node_id`, consecutively visited proximity neighbors may have arbitrary original node IDs. Reordering domain dense IDs by BFS distance from the Vamana medoid co-locates early-beam neighbors onto shared CPU cache lines and remaps the Vamana graph in $O(N \cdot R + N \cdot D)$ without re-running $\alpha$-RNG construction: ```bash impulse snapshot optimize \ -i citations_vec.imps \ -o citations_vec_opt.imps \ --vamana-locality \ --csc ``` --- ## 4. Two-Stage Quantized Routing, Reranking & Hybrid Graph Search Rather than maintaining a separate vector database and joining IDs over the network against a graph database, `ImpulseVM` executes **Hybrid Vector + Graph Traversals** inside one register pipeline using opcodes `0xCA` and `0xCB` (see [VM Specification §6.11.2](../../reference/spec/vm-specification.md)): ```mermaid flowchart LR Q["Query Vector q (Float32[D])"] --> S1["Stage 1: OP_VECTOR_ANN_SEARCH (0xCA)\nGreedy beam walk over Vamana adj_slab\nusing BQ1 / SQ8 / FP16 routing codes"] S1 --> G["Multi-Hop Graph Walk & Filtering\nOP_CSR_WALK / OP_CSC_WALK / OP_LANE_CSR_WALK\n+ CEL Domain Attribute Predicates"] G --> S2["Stage 2: OP_VECTOR_RERANK_DOT (0xCB)\nExact SIMD Float32 dot-product reranking\non surviving candidate BitSet / Lanes only"] S2 --> OUT["Top-K Ranked Candidates"] ``` 1. **Stage 1 — Compact Quantized Beam Routing (`OP_VECTOR_ANN_SEARCH` `0xCA`)**: Starts at `medoid_node_id` and traverses the Vamana `adj_slab` using compact `BQ1` ($32\times$ smaller than `float32`), `SQ8` ($4\times$ smaller), or `FP16` ($2\times$ smaller) routing codes, writing the top-$k$ seed candidates directly into a `TYPE_BITSET_HANDLE` (`0x04`) or bit-sliced `TYPE_LANE_FRONTIER` (`0x10`, when `flags & 1 != 0`). 2. **Multi-Hop Graph Expansion & Constraints**: Walks CSR/CSC relations (e.g., `Paper -[:CITES]-> Paper`, `Compound -[:BINDS]-> Gene`, or ReBAC authorization checks) and applies in-domain CEL filters (`year >= 2022`) to prune unauthorized or structurally irrelevant candidates. 3. **Stage 2 — Exact SIMD `Float32` Reranking (`OP_VECTOR_RERANK_DOT` `0xCB`)**: Reads full-precision `[N, D]` `float32` vectors *only* for surviving candidate nodes in the bitset/lane frontier and computes exact SIMD dot-product scores (`TYPE_FLOAT_VECTOR`). !!! note "SDK Support for `0xCA` / `0xCB`" In `v0.10.0`, embedded Vamana search and two-stage reranking are exposed natively in C++20 (`DomainView::vectorSearch`, `MultiLaneBuilder::fromConceptVectors`, `QueryBuilder::vectorAnnSearch` / `vectorRerankDot` — see [C-ABI & C++20 Reference](../../reference/c-abi.md#51-multi-lane-bit-sliced-hybrid-vector-fluent-apis-v0100)) and Rust (`SnapshotReader::vamana_ann_search` — see [Rust Crate Reference](../../reference/rust-api.md#41-vamana-ann-graph-index-construction-permutation-two-stage-search-vamana-module-v0100)), as well as via `.impas` / `.impb` bytecode in `impulse run`. High-level Python wrapper methods on `impulse_graph.DomainView` for `0xCA`/`0xCB` are planned; Python workflows today build and benchmark Vamana snapshots via `impulse` CLI and access `[N, D]` embedding columns zero-copy via `Snapshot.get_attribute_array`. ### Benchmarking Recall, Quantization Tiers & Latency (`impulse bench-vector`) Use `impulse bench-vector` (`impulse snapshot bench-vector`) to measure `Recall@1`, `Recall@K`, `nDCG@K`, `MRR`, and `p50`/`p95`/`p99` microsecond latency across all four quantization tiers (`NONE`, `FP16`, `SQ8`, `BQ1`) and compare pre- vs. post-`optimize` (`--vamana-locality` / `--rcm`) cache behavior against an exact brute-force oracle: ```bash # 1. Synthetic community-manifold + homophily graph sweep across ef_search = 16, 32, 64 impulse bench-vector \ -n 10000 -d 128 -c 24 -q 200 -k 10 \ --max-degree 24 --ef-construction 64 --alpha 1.2 --metric cosine \ --ef-search 16,32,64 --compare-optimize --format text # 2. Benchmark an existing .imps snapshot and export structured JSON metrics impulse snapshot bench-vector \ --snapshot citations_vec_opt.imps \ --embeddings paper_vecs.npy \ -q 200 -k 10 \ --ef-search 32,64,128 \ --format json ``` --- ## Next Steps * **[Snapshots from Parquet & CSV](snapshots-from-parquet-csv.md)** — Full `manifest.json` specification for scalar and vector columns. * **[Native CLI Optimization, Deep Audits & Signing](../native/cli-reference.md)** — Deep dive into `--rcm`, `--vamana-locality`, and `--deep-audit` Vamana invariant checks. * **[PyTorch & GNN Showcase](../../showcase/gnn.md)** — Reproducing the Apple M5 GPU SpMM and Qwen 1.5 MoE router benchmarks. * **[Python & PyTorch SDK Reference](../../reference/python-api.md)** — Complete Python API reference. ================================================================================ FILE: docs/ecosystems/native/index.md | URL: https://www.impulsegraph.org/ecosystems/native/ ================================================================================ # Native Systems & Polyglot C-ABI Hub The **Impulse Graph Engine C-ABI Kernel** (`impulse-graph-core/impulse-cpp`) is a zero-dependency C++20 runtime (`libimpulse_graph_static.a` / `impulse_graph_static.lib`) providing direct `mmap` `.imps` loading, dynamic SIMD target dispatch (`AVX-512`, `AVX2`, `ARM-NEON`, `WASM-SIMD128`), OpenMP intra-opcode parallelism, and a deterministic zero-`malloc` prepared-statement execution model for **C, C++20, Rust, Go, .NET 8+, and Node.js**. --- ## 1. Guide & Reference Map | Guide / Reference | Target Audience | | :--- | :--- | | **[Native CLI Optimization, Deep Audits & Signing](cli-reference.md)** | Offline `--rcm` / `--vamana-locality` layout optimization, `--quick-check` vs. `--deep-audit` validation, and Ed25519 snapshot signing. | | **[C-ABI & C++20 Reference](../../reference/c-abi.md)** | `impulse_graph.h`, `impulse_vm.h`, `impulse_index.h`, and C++20 `SnapshotView` / `MultiLaneBuilder` (`impulse_vm_fluent.hpp`). | | **[Rust Crate Reference](../../reference/rust-api.md)** | `impulse-graph` crate (`SnapshotReader`, `Traversal`, `SnapshotWriter`, and `vamana` Section 2.6 ANN module). | | **[Go, .NET & Node.js SDKs](../../reference/polyglot-sdks.md)** | Idiomatic bindings via Go `CGo`, .NET 8+ `P/Invoke`, and Node.js/Bun/TypeScript `N-API`. | | **[CLI Reference (`impulse`)](../../reference/cli.md)** · **[Packages & Distribution](../../reference/packages.md)** | Complete command tree, static linking (`glibc` / `musl` / MSVC `/MT`), and SLSA Level 3 build attestations. | --- ## 2. Core C-ABI Architectural Contract All native bindings link statically against `libimpulse_graph_static.a` and share three low-level invariants: ### 2.1 Zero External Dependencies & Dynamic SIMD Dispatch * **Zero Runtime Dependencies**: `impulse-cpp` and `impulse-rust` depend only on the platform C/C++ standard library (`glibc >= 2.28` or static `musl-libc` on Linux, `libSystem.B.dylib` / `libc++.dylib` on macOS 11+, static `LIBCMT.lib` via `/MT` on Windows). * **Sub-40-Microsecond `mmap` Cold Start**: `impulse_snapshot_open` maps the 6.04 GB `twitter-2010.imps` snapshot (`1.47B` edges, `41.65M` nodes) in `0.038 ms` (`38 µs`) via read-only OS `mmap` and executes a 10-thread full-graph direction-optimizing BFS in `145.00 ms` (see [Benchmarks](../../benchmarks.md)). * **Hardware-Aligned Buffers**: Every CSR/CSC offset array, Structure-of-Arrays (SoA) column, validity bitmap, and Section 2.6 index slab is aligned to **128-byte file boundaries** for unaligned-penalty-free SIMD vector loads (`impulse_simd.h` / Highway) and GPU `cuFile` transfers. ### 2.2 Caller-Allocated Zero-`malloc` Prepared Statements (`impulse_vm.h`) Inspired by SQLite's `sqlite3_stmt` lifecycle—extended with caller-owned scratch memory—`impulse_vm.h` separates query compilation from execution so the hot path performs **zero internal `malloc` or `free` calls**: ```mermaid flowchart LR P["1. impulse_stmt_prepare\nCompile openCypher / ImpLog /\nImpK / ImpScheme once"] --> S["2. impulse_stmt_buffer_size\nQuery exact byte budget\nfor scratch + result columns"] S --> B["3. Caller Buffer\nStack array, thread-local\nslab, or custom arena"] B --> E["4. impulse_stmt_execute\nBind params & run ImpulseVM\nwith 0 heap allocations"] E --> F["5. impulse_stmt_finalize\nRelease compiled plan\nat shutdown"] ``` ```c #include "impulse_graph.h" #include "impulse_vm.h" #include #include int run_prepared_query(const impulse_snapshot_t* snap, uint64_t seed_user_id) { impulse_stmt_t* stmt = nullptr; impulse_status_t st = impulse_stmt_prepare( snap, "MATCH (u:User)-[:OWNS]->(a:Account) WHERE u.id = $uid RETURN a", &stmt ); if (st != IMPULSE_OK || !stmt) return -1; // Allocate exact workspace once per thread (or on stack/arena) and reuse across requests std::vector workspace(impulse_stmt_buffer_size(stmt)); impulse_stmt_bind_node(stmt, "$uid", seed_user_id); st = impulse_stmt_execute(stmt, workspace.data(), workspace.size()); size_t word_count = impulse_stmt_row_count(stmt); const auto* bitset_words = static_cast(impulse_stmt_column_data(stmt, 0)); (void)word_count; (void)bitset_words; impulse_stmt_finalize(stmt); return (st == IMPULSE_OK) ? 0 : -1; } ``` --- ## 3. Language SDK Quick-Reference Idioms In empirical benchmarks on the Hetionet biomedical graph (`47K` nodes, `2.25M` edges, 4-hop traversal returning `1,317` candidate compounds), thin FFI wrappers add single-digit microseconds over raw C++20: | SDK | Binding Mechanism | 4-Hop Mean Latency | Overhead vs. C++20 | Full Reference | | :--- | :--- | :---: | :---: | :--- | | **C / C++20** (`impulse-cpp`) | Direct C-ABI / Header-only C++20 | `18.4 µs` | `0.0 µs` (Baseline) | [C-ABI & C++20 Reference](../../reference/c-abi.md) | | **Rust** (`impulse-rust`) | Safe Rust + `ffi` crate (`0.10`) | `19.1 µs` | `+0.7 µs` | [Rust Crate Reference](../../reference/rust-api.md) | | **Go** (`impulse-go`) | Static `CGo` (`libimpulse_graph_static.a`) | `21.5 µs` | `+3.1 µs` | [Go SDK Reference](../../reference/polyglot-sdks.md#1-go-sdk-impulse-go-via-cgo) | | **.NET 8+** (`impulse-dotnet`) | `LibraryImport` P/Invoke (`IDisposable`) | `23.0 µs` | `+4.6 µs` | [.NET 8+ SDK Reference](../../reference/polyglot-sdks.md#2-net-8-c-sdk-impulsegraph-via-pinvoke) | | **Node.js / TS** (`impulse-node`) | `N-API` (`node-addon-api`) | `26.8 µs` | `+8.4 µs` | [Node.js SDK Reference](../../reference/polyglot-sdks.md#3-nodejs-bun-typescript-sdk-impulse-graph-via-n-api) | === "C++20 (`SnapshotView` & Multi-Lane)" ```cpp #include "impulse_graph.h" #include "impulse_vm_fluent.hpp" impulse_status_t st = IMPULSE_OK; impulse_snapshot_t* snap = impulse_snapshot_open("biomedical.imps", &st); impulse::vm::SnapshotView view(snap); // Bit-sliced multi-lane traversal across 8 oncology target genes (0xC0..0xC9) auto result = view.domain("Gene").multiLane() .fromKeys({"BRCA1", "BRCA2", "EGFR", "MYC", "KRAS", "PIK3CA", "BRAF", "ERBB2"}) .out("INTERACTS_GiG") .in("BINDS_CbG") .whereQuorum(4) .collect(); auto candidate_compounds = result.keysWithQuorum(4); impulse_snapshot_close(snap); ``` Full API: **[C-ABI & C++20 Reference](../../reference/c-abi.md)** === "Rust (`cargo add impulse-graph`)" ```rust use impulse_graph::reader::SnapshotReader; fn main() -> Result<(), Box> { let reader = SnapshotReader::open("rbac.imps")?; // Direct zero-copy CSR slices (&[u32]) from mmap let row_offsets: &[u32] = reader.get_row_offsets(0)?; let col_indices: &[u32] = reader.get_col_indices(0)?; assert_eq!(row_offsets.len(), (reader.relations()[0].node_count + 1) as usize); let _ = col_indices; // Fluent multi-hop topology traversal let permissions: Vec = reader .traverse(0) .out("MEMBER_OF") .in_step("MANAGES") .out("HAS_PERMISSION") .to_vec()?; println!("Permissions count: {}", permissions.len()); Ok(()) } ``` Full API: **[Rust Crate Reference](../../reference/rust-api.md)** === "Go (`CGo`)" ```go snap, err := impulse.OpenSnapshot("rbac.imps") if err != nil { log.Fatal(err) } defer snap.Close() ctx, _ := impulse.NewVMContext(snap) defer ctx.Close() state := impulse.NewVMState() state.SetQueryContext(ctx) code := impulse.NewQueryBuilder(). InputNode(0). WalkEdge(0, 1). WalkEdge(1, 2). CollectBitset(2). Compile() _ = impulse.ExecuteVM(code, state, 10) ``` Full API: **[Go, .NET & Node.js SDKs](../../reference/polyglot-sdks.md#1-go-sdk-impulse-go-via-cgo)** === ".NET 8+ (`C#`)" ```csharp using ImpulseGraph; using ImpulseGraph.Vm; using var snap = new Snapshot("rbac.imps"); using var ctx = new VmContext(snap); Query query = new QueryBuilder() .InputNode(0) .WalkEdge(relationId: 0, dstReg: 1) .WalkEdge(relationId: 1, dstReg: 2) .CollectBitset(reg: 2) .Compile(); ExecutionResult res = snap.ExecuteQuery(query, ctx, inputParam: 42UL); ``` Full API: **[Go, .NET & Node.js SDKs](../../reference/polyglot-sdks.md#2-net-8-c-sdk-impulsegraph-via-pinvoke)** === "Node.js / TypeScript (`N-API`)" ```typescript import { Snapshot, VmContext, VmState, QueryBuilder } from 'impulse-graph'; const snap = new Snapshot('rbac.imps'); const ctx = new VmContext(snap); try { const state = new VmState(); const query = new QueryBuilder() .inputNode(0) .walkEdge(0) .repeatUntilStable((b) => b.walkEdge(1)) .collectBitset() .compile(); const res = query.executeWithContext(ctx, state, 42); console.log('Group 7 reachable:', res.testBitset(ctx, 7)); } finally { ctx.destroy(); snap.close(); } ``` Full API: **[Go, .NET & Node.js SDKs](../../reference/polyglot-sdks.md#3-nodejs-bun-typescript-sdk-impulse-graph-via-n-api)** --- ## 4. Specification Boundary & Cross-Runtime Bitwise Parity (`ICTX` v1) Impulse Graph is defined by **two normative specifications** rather than a single codebase: 1. **Binary Snapshot Format Specification (`.imps`)**: Fixed 4KB Page 0 header, Section 2 catalog, 128-byte-aligned CSR/CSC/SoA arrays, and Section 2.6 secondary/Vamana indices ([Format Specification](../../reference/spec/format-specification.md)). 2. **`ImpulseVM` & `impOps` Bytecode Specification**: 64-register (`R0`..`R63`) virtual machine with 188 formal opcode contracts (`0x00`..`0xCB`) and the **`ICTX` v1 Deterministic State Hash** (`impulse_vm_state_hash_hex`, [VM Specification](../../reference/spec/vm-specification.md)). Because the format and VM semantics are specified independently of C++, the **[Pure Java 25 Engine](../java/index.md)** (`impulse-graph-java`) mounts the exact same `.imps` files via `java.lang.foreign.MemorySegment` without JNI and passes the **[Four-Way Polyglot Validation Suite](../../contributing/polyglot-validation.md)** with 100% bitwise-identical `ICTX` v1 state hashes alongside C++ (`-O3`), C++ (`-O0`), and the OCaml formal oracle. The same clean specification boundary also enables future standalone runtimes such as `wasm32-unknown-unknown` (`WASM-SIMD128`) or pure managed `.NET` without breaking `.imps` or `.impb` compatibility. --- ## Next Steps * **[Native CLI Optimization, Deep Audits & Signing](cli-reference.md)** — Optimize `.imps` layouts (`--rcm`, `--vamana-locality`), run `--deep-audit`, and sign snapshots with Ed25519. * **[C-ABI & C++20 Reference](../../reference/c-abi.md)** — Header-by-header C-ABI signatures and C++20 `SnapshotView` / `MultiLaneTraversal` guide. * **[Rust Crate Reference](../../reference/rust-api.md)** — Safe Rust reader, writer, and Vamana ANN search APIs. * **[Polyglot Workflow](../../getting-started/polyglot-workflow.md)** — Build once in Python/CLI and mount across C++, Rust, Go, and Java. ================================================================================ FILE: docs/ecosystems/native/cli-reference.md | URL: https://www.impulsegraph.org/ecosystems/native/cli-reference/ ================================================================================ # Native CLI Optimization, Deep Audits & Supply-Chain Signing The native `impulse-graph` (`impulse`) binary in `impulse-graph-core/impulse-cli` combines dataset compilation (`impulse build`) with offline physical layout optimization, multi-tier structural auditing, and Ed25519 cryptographic attestation for production CI/CD pipelines. !!! info "Full Command Syntax & Pure-JVM Alternative" * For the complete subcommand tree and flag list, see the **[CLI Reference (`impulse`)](../../reference/cli.md)**. * Working inside a strict JVM-only container where native binaries are prohibited? Use the **[Pure-Java CLI (`impulse-j`)](../java/cli-impulse-j.md)** instead. --- ## 1. Physical Graph Layout Optimization (`impulse snapshot optimize`) When `impulse build` compiles raw CSV or Parquet files, dense node IDs (`0 .. N_d - 1`) initially follow the encounter order of rows in the input files. On sparse real-world graphs, arbitrary node numbering scatters adjacent neighbors across distant memory pages, causing L2/L3 cache-line misses and TLB thrashing during multi-hop traversals or GNN message passing. `impulse snapshot optimize` computes a deterministic bijection $\pi: [0, N_d) \to [0, N_d)$ per domain, rewrites CSR/CSC indices, reorders all node/edge SoA attribute columns and key catalogs in lockstep, and permutes embedded Section 2.6 Vamana indices: | Flag | Reordering Strategy | Best For | Mechanism | | :--- | :--- | :--- | :--- | | **`--rcm`** | **Reverse Cuthill-McKee** | Multi-hop BFS, Connected Components, PageRank, GNN SpMM | Minimizes matrix bandwidth $\max_{(u,v) \in E} |\pi(u) - \pi(v)|$ so neighbors of $u$ cluster within the same 64-byte CPU cache lines. | | **`--vamana-locality`** | **Vamana Medoid BFS** | Hybrid Vector ANN (`OP_VECTOR_ANN_SEARCH` `0xCA`) | Orders domain nodes by BFS hop distance from `VamanaHeader.medoid_node_id`, co-locating early beam-search hops in memory and remapping the Vamana graph in $O(N \cdot R + N \cdot D)$ time. | | **`--degree-sort`** | **Out-Degree Descending** | Power-law hub filtering & triangle counting (`OP_TC_SWEEP_BATCH`) | Assigns dense IDs `0, 1, 2, ...` to the highest-degree hub nodes so hot adjacency lists stay pinned in L1/L2 cache. | | **`--csc`** | **Reverse CSC Materialization** | Bidirectional traversals (`.in(...)`, `<-[]-` in openCypher) | Transposes forward CSR into 128-byte-aligned Compressed Sparse Column arrays for $O(1)$ incoming offset lookups. | | **`--encoding `** | **Target Column Layout** | GPU SpMM (`sliced_ellpack`) or compact storage | Re-encodes target columns (`raw_uint32`, `sliced_ellpack`, `delta_vbyte`, `simdcomp`). | | **`--strip-mappings`**
**`--strip-properties`** | **Section Stripping** | Edge-embedded / IoT topology-only deployments | Removes string key catalogs or DTO attribute blocks when queries operate purely on dense IDs. | ```bash # 1. Optimize a general traversal / GNN snapshot with RCM bandwidth reduction + reverse CSC impulse snapshot optimize \ -i raw_graph.imps \ -o optimized_graph.imps \ --rcm \ --csc # 2. Optimize a vector-indexed snapshot with Vamana medoid BFS locality # (use --rebuild-vector-index only if you want a fresh alpha-RNG build instead of O(N*R) permutation) impulse snapshot optimize \ -i raw_vec.imps \ -o optimized_vec.imps \ --vamana-locality \ --csc ``` !!! note "Schema Evolution Safety Under Node Reordering" Because dense node IDs (`0 .. N_d - 1`) are internal per-snapshot coordinates resolved from business keys (`fromKey` / `resolve_dense_id`) at query time, applying `--rcm`, `--vamana-locality`, or `--degree-sort` requires **zero changes** to application query code. Never hardcode or persist dense IDs across snapshot rebuilds. --- ## 2. Tiered Integrity Verification & Supernode Diagnostics Before mapping an `.imps` file into a production service—or after generating one in an ETL job—`impulse snapshot validate`, `inspect`, and `stats` provide three verification tiers modeled on SQLite's `PRAGMA quick_check` and `integrity_check`: ### 2.1 Validation Tiers (`impulse snapshot validate`) | Command Flag | Complexity | What It Verifies | Recommended Stage | | :--- | :---: | :--- | :--- | | **`--quick-check`** | $O(\text{domains} + \text{relations})$ | Page 0 magic (`IMPS`), CRC-16-CCITT header checksum, section bounds against file length, 128-byte alignment, and CSR endpoint bounds. | **Pod Startup / Pre-`mmap` Gate** (sub-millisecond sanity check before swapping a downloaded S3 artifact). | | **`--strict-alignment`** *(default)* | $O(\text{file bytes})$ | Everything in `--quick-check` plus full-payload SHA-256 cryptographic digest verification and strict 128-byte hardware offset checks across every CSR, CSC, SoA, and Section 2.6 slab. | **CI / ETL Post-Build Step** immediately after `impulse build` or `impulse snapshot optimize`. | | **`--deep-audit`** | $O(V + E + N \cdot R)$ | Full structural cross-check: monotonic CSR/CSC `row_offsets`, in-bounds target IDs (`< N_tgt`), exact multiset transpose equality between CSR and CSC edges, and Vamana `adj_slab` degree/medoid/padding invariants. | **Offline Release Gate / Compiler Regression Testing** before publishing golden datasets. | ```bash # Fast pre-mount check during container init impulse snapshot validate production.imps --quick-check # Standard post-build SHA-256 + 128-byte hardware alignment check impulse snapshot validate production.imps --strict-alignment # Exhaustive CSR/CSC multiset transpose + Vamana proximity graph audit impulse snapshot validate production.imps --strict-alignment --deep-audit ``` ### 2.2 Physical Page-Map Inspection & Supernode Detection Skewed power-law graphs often contain extreme hub nodes ("supernodes") that dominate frontier expansion or cause false-positive collisions in multi-hop paths. Use `impulse snapshot stats` and `inspect` to profile topology skew and physical page alignment: ```bash # 1. Compute min/max/mean/p99 out-degrees, multiplicity, CBO sketches, # and flag supernodes exceeding Z-score >= 3.0 (supports --format json) impulse snapshot stats production.imps --supernode-threshold 3.0 --verbose # 2. Dump 4KB page / 128B cache-line physical section offsets and padding bytes impulse snapshot inspect production.imps --page-map # 3. Emit machine-readable catalog metadata for CI scripts or AI coding agents impulse snapshot inspect production.imps --format json ``` --- ## 3. Ed25519 Cryptographic Snapshot Attestation (`impulse crypto`) Because `.imps` files are memory-mapped directly into process address space across stateless worker pods or edge nodes, zero-trust deployments should verify artifact authenticity before calling `mmap`. `impulse crypto` implements detached **Ed25519** digital signatures (`.imps.sig`) over the snapshot header digest (which binds the payload SHA-256 checksum): ```mermaid flowchart LR BUILD["CI Builder\nimpulse build + validate"] --> SIGN["Sign Artifact\nimpulse crypto sign\n(-k release_key.priv)"] SIGN --> STORE["Object Storage (S3 / GCS)\ngraph.imps + graph.imps.sig"] STORE --> VERIFY["Worker Pod Pre-Mount\nimpulse crypto verify\n(-k release_key.pub)"] VERIFY --> MMAP["Safe Read-Only mmap\nSnapshotSwapManager / SnapshotReader"] ``` ```bash # 1. Generate an Ed25519 keypair once in your secure key management environment # Writes release_key.priv (keep secret in CI KMS) and release_key.pub (distribute to readers) impulse crypto keygen -o release_key # 2. Sign the compiled snapshot in CI/CD (produces production.imps.sig) impulse crypto sign production.imps -k release_key.priv # 3. Verify signature + header integrity on the target host BEFORE opening via mmap impulse crypto verify production.imps -k release_key.pub # Or combine Ed25519 signature verification with 128B alignment & SHA-256 validation in one step: impulse snapshot validate production.imps \ --strict-alignment \ --public-key release_key.pub ``` --- ## Next Steps * **[Native Systems & Polyglot C-ABI Hub](index.md)** — C-ABI prepared statements and Rust/Go/.NET/Node.js SDK idioms. * **[CLI Reference (`impulse`)](../../reference/cli.md)** — Full command hierarchy including `impulse compiler`, `impulse run --verify --never-corrupt`, and `impulse bench-vector`. * **[Pure-Java CLI (`impulse-j`)](../java/cli-impulse-j.md)** — Schema compatibility checks (`check-compat`) and snapshot inspection in JVM-only environments. * **[Snapshots from Parquet & CSV](../python/snapshots-from-parquet-csv.md)** — Authoring `manifest.json` files for `impulse build`. ================================================================================ FILE: docs/ai/index.md | URL: https://www.impulsegraph.org/ai/ ================================================================================ # AI Coding Agents, `SKILL.md` & `llms.txt` General-purpose LLMs trained primarily on Neo4j, SQL, and NetworkX codebases often hallucinate OLTP mutation queries (`CREATE`, `MERGE`), global node IDs, or slow client-side `for` loops when writing code against **Impulse Graph Engine**. To give AI coding assistants (Claude Code, Antigravity, Cursor, GitHub Copilot, Windsurf, Gemini, and ChatGPT) exact architectural context, `www.impulsegraph.org` publishes three machine-readable endpoints alongside every documentation build. --- ## 1. Hosted Machine-Readable Endpoints | Endpoint | Format | Best For | Description | | :--- | :--- | :--- | :--- | | **[`/ai/SKILL.md`](/ai/SKILL.md)** | Raw Markdown + YAML Frontmatter | **Claude Code, Antigravity, Cursor, Copilot** | Compact, drop-in Agent Skill & Rules file covering `.imps` immutability, per-domain `0 .. N_d - 1` dense IDs, Kleisli set pipelines, JVM/Python/C-ABI flags, and JSON CLI self-verification. | | **[`/llms.txt`](/llms.txt)** | Markdown Index ([llmstxt.org](https://llmstxt.org/)) | **Web-Browsing Agents & MCP Fetchers** | Concise architectural mental model plus a structured sitemap of every guide, SDK reference, and specification URL with one-line summaries. | | **[`/llms-full.txt`](/llms-full.txt)** | Single-File Markdown Corpus | **Claude Projects, Gemini, Cursor `@Docs`, NotebookLM** | Complete concatenation of all navigated Impulse Graph documentation pages, DSL guides, SDK references, and normative `.imps` / `ImpulseVM` specifications in reading order. | --- ## 2. One-Command Agent Setup Install [`SKILL.md`](/ai/SKILL.md) directly into your repository so coding agents enforce Impulse idioms automatically on every prompt: === "Claude Code (`.claude/skills/`)" ```bash mkdir -p .claude/skills/impulse-graph curl -fsSL https://www.impulsegraph.org/ai/SKILL.md \ -o .claude/skills/impulse-graph/SKILL.md ``` *(Alternatively, append to your root `CLAUDE.md`: `curl -fsSL https://www.impulsegraph.org/ai/SKILL.md >> CLAUDE.md`)* === "Antigravity / `.agents/skills`" ```bash mkdir -p .agents/skills/impulse-graph curl -fsSL https://www.impulsegraph.org/ai/SKILL.md \ -o .agents/skills/impulse-graph/SKILL.md ``` === "Cursor (`.cursor/rules/`)" ```bash mkdir -p .cursor/rules curl -fsSL https://www.impulsegraph.org/ai/SKILL.md \ -o .cursor/rules/impulse-graph.mdc ``` In Cursor **Settings $\to$ Features $\to$ Docs**, you can also index `https://www.impulsegraph.org/llms-full.txt` under `@ImpulseGraph`. === "GitHub Copilot (`.github/copilot-instructions.md`)" ```bash mkdir -p .github curl -fsSL https://www.impulsegraph.org/ai/SKILL.md \ >> .github/copilot-instructions.md ``` --- ## 3. Common LLM Hallucinations vs. Correct Impulse Idioms Without `SKILL.md`, AI assistants frequently apply mutable property-graph or imperative ORM habits that fail at compile time or degrade throughput by $100\times$–$1,000\times$. ### 3.1 Architectural Mental-Model Comparison | Dimension | Hallucinated Neo4j / Imperative Pattern (Wrong) | Idiomatic Impulse Graph Pattern (Correct) | | :--- | :--- | :--- | | **Writes & Updates** | `session.run("MERGE (u:User {id: $id}) SET u.risk = 10")` | Snapshots are immutable read-only `.imps` files; rebuild via `impulse-graph build` / `SnapshotBuilder` and hot-swap via `SnapshotLifecycleManager` / `SnapshotSwapManager`. | | **Node Identity** | Assumes a single global `nodeId` space across all labels (`User#0 == Account#0` collision). | Every domain owns an independent `0 .. N_d - 1` dense space; anchor queries via `snap.domain("User")` or AOT-generated `bank.users()`, and persist only business keys (`UUID` / `String` / `int64`). | | **Multi-Hop Traversal** | Nested client-side `for` loops fetching neighbors one node at a time (`N + 1` point lookups). | Single engine-native Kleisli set pipeline (`.out(...).filter(...).toKeyList()`) evaluated in `ImpulseVM` over SIMD bitsets. | | **Intermediate Hops** | Collects exponential multi-set path lists (`List`) in heap memory. | Collapses each hop onto a per-domain `BitSet` (or monoid state vector `SUM`/`MIN`/`MAX`), preventing path explosion. | | **Java Memory & Flags** | Sets `-Xmx64g` for a 50 GB graph and omits FFM / Vector flags. | Sets lean `-Xms2g -Xmx4g` so OS `mmap` page cache holds the `.imps` file; passes `--add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED` (plus `--enable-preview` on JDK 21). | | **PyTorch Workers** | Loads graph into a Python `dict` and forks `DataLoader(num_workers=8)`, duplicating RAM $8\times$ via CoW. | Passes only the `.imps` path string to workers and opens `Snapshot(path)` lazily per worker (`0 bytes` duplicated). | ### 3.2 Side-by-Side Code Comparison === "Java 21/25" ```java // ❌ ANTI-PATTERN (Hallucinated Imperative N+1 Point-Lookup Loop): // Crosses API boundary per node, allocates heap HashSets per hop, and mixes raw dense IDs! Set suspiciousAccounts = new HashSet<>(); for (long ownedAcc : snap.domain("User").fromKey(userUuid.toString()).out("OWNS").toList()) { for (long targetAcc : snap.domain("Account").from(ownedAcc).out("TRANSFERRED_TO").toList()) { suspiciousAccounts.add(snap.domain("Account").toKey(targetAcc)); } } // ✅ IDIOMATIC IMPULSE PATTERN (Single Zero-Allocation Kleisli Set Pipeline): // Executes entirely off-heap inside ImpulseVM via CSR bitset walks + SIMD CEL filtering: List suspiciousAccounts = snap.domain("User") .fromKey(userUuid.toString()) .out("OWNS") .out("TRANSFERRED_TO", "edge.amount >= 10000.0") .filter("node.balance >= 50000.0") .toKeyList(); ``` === "Python (`impulse-graph`)" ```python # ❌ ANTI-PATTERN (Client-Side Python Loop Over Adjacency Lists): # Re-enters pybind11 per node and materializes intermediate Python lists! reached = set() for acc_id in snap.traverse(start_node=0).out("OWNS").to_list(): for dst_id in snap.traverse(start_node=acc_id).out("TRANSFERRED_TO").to_list(): reached.add(dst_id) # ✅ IDIOMATIC IMPULSE PATTERN (Domain-Anchored Engine Pipeline): # Resolves business key in User domain, walks both CSR relations in C++20 ImpulseVM, # and resolves surviving Account dense IDs back to business keys: with Snapshot("banking.imps") as snap: reached_keys = ( snap.domain("User") .from_key("usr_101") .out("OWNS") .out("TRANSFERRED_TO") .filter("account.balance >= 1000.0") .to_key_list() ) ``` --- ## Next Steps * **[Download Raw `SKILL.md`](/ai/SKILL.md)** — Drop directly into `.claude/skills/`, `.agents/skills/`, or `.cursor/rules/`. * **[Core Concepts & Glossary](../getting-started/core-concepts.md)** — Visual primer on `.imps` snapshots, per-domain dense IDs, and Kleisli frontier propagation. * **[Java & JVM Enterprise Hub](../ecosystems/java/index.md)** · **[Python, Data Science & ML Hub](../ecosystems/python/index.md)** · **[Native Systems & C-ABI Hub](../ecosystems/native/index.md)** — Ecosystem-specific guides. ================================================================================ FILE: docs/reference/spec/format-specification.md | URL: https://www.impulsegraph.org/reference/spec/format-specification/ ================================================================================ # Formal Specification: Impulse-Graph C-ABI Binary Snapshot Format * **Document Status**: Standard Reference Specification * **Byte Order**: Little-Endian (`LE`, IEEE 754 & x86-64 / ARM64 Native) * **Memory Alignment**: 128-Byte SIMD / GPU Boundary (`(len + 127) & ~127`) & 4KB OS Page Boundary (`(offset + 4095) & ~4095`) * **Integrity Validation**: SHA-256 Checksum (32 Bytes, calculated over payload) & Ed25519 Cryptographic Signature Block --- ## 1. Specification Overview & Modular Design Principles This document defines the formal binary protocol specification for the **Impulse-Graph C-ABI Binary Snapshot Format**. The format is organized into **4KB OS page-aligned physical blocks**, structured to support **single-pass S3/cloud streaming uploads**, **$O(1)$ zero-copy `mmap` range loading**, and **AVX-512 / GPU SIMD vectorization**. ### 1.1 Physical File Layout Overview ```text ┌───────────────────────────────────────────────────────────────────────────────────┐ │ SECTION 1: Snapshot Header (4KB Page 0, Offset 0x0000) │ │ ├── Magic ("IMPS"), Version (0x000A), DataOffset (4096) │ │ └── GlobalRequiredFeatures, SnapshotUUID, HeaderChecksum │ ├───────────────────────────────────────────────────────────────────────────────────┤ │ SECTION 2: Catalog & Relation Directory Table (4KB Page 1, Offset 0x1000) │ │ ├── 1. String Table (Shared Null-Terminated UTF-8 String Pool Blob) │ │ ├── 2. Domain Catalog Array (Fixed 16-Byte POD Structs) │ │ └── 3. Sorted Relation Directory Table (Fixed 128B Entries + 44B Attr Descriptors) │ ├───────────────────────────────────────────────────────────────────────────────────┤ │ RELATION BLOCK 1 [MANDATORY, 4KB Aligned] │ │ ├── csrRowOffsets Array (128B Aligned, uint32/uint64) │ │ ├── csrColumnIndices Stream (128B Aligned, RAW 0x00 Encoding) │ │ ├── cscRowOffsets / cscColumnIndices Arrays (Optional Transpose, 128B Aligned) │ │ ├── Edge Fixed-width SoA Attribute Arrays (128B Aligned: weights, timestamps...)│ │ └── Edge Var-length Attribute Offsets & Data Blobs (128B Aligned) │ ├───────────────────────────────────────────────────────────────────────────────────┤ │ RELATION BLOCK 2 [MANDATORY, 4KB Aligned] │ │ └── (Contiguous 128B aligned topology & attribute array sequence) │ ├───────────────────────────────────────────────────────────────────────────────────┤ │ NODE DOMAIN BLOCK 1 [OPTIONAL, 4KB Aligned] │ │ ├── Node Fixed-width SoA Attribute Arrays (128B Aligned) │ │ └── Node Var-length Attribute Offsets & Data Blobs (128B Aligned) │ ├───────────────────────────────────────────────────────────────────────────────────┤ │ SECTION 4: KEY CATALOG BLOCK [OPTIONAL, 128B Aligned] │ │ ├── Minimal Perfect Hash Function (MPHF) or Sorted Array Indices │ │ └── (O(1) / O(log N) mapping of external string/int keys to dense Node IDs) │ ├───────────────────────────────────────────────────────────────────────────────────┤ │ FOOTER BLOCK [EOF, 4KB Aligned] │ │ ├── Unified UTF-8 Key/Value Custom Metadata Stream (Unlimited multi-map) │ │ ├── Final Catalog & Relation Directory Table Copy (S3 Cloud Range Reader Copy) │ │ ├── SHA-256 Payload Checksum & Ed25519 Cryptographic Signature Block │ │ └── 16-Byte Footer Trailer (footer_length [u64] + version [u32] + "IMPS" [u32]) │ └───────────────────────────────────────────────────────────────────────────────────┘ ``` --- ## 2. Section 1: Snapshot Header Layout (Fixed 4KB Page 0 Baseline) The snapshot header occupies byte offset `0x00000000` (Page 0). It contains a **64-byte active baseline** aligned to a single CPU cache line, inside a fixed 4096-byte page (`DataOffset = 4096`). ### 2.1 Header Byte Offset Table | Byte Offset | Field Name | C-ABI Type | Size | Default / Constant | Description | | :--- | :--- | :--- | :--- | :--- | :--- | | `0x0000` – `0x0003` | `Magic` | `uint32_t` | 4 Bytes | `0x494D5053` (`"IMPS"`) | Magic constant identifying Impulse-Graph binary snapshot file. | | `0x0004` – `0x0005` | `Version` | `uint16_t` | 2 Bytes | `0x000A` (`10`) | Protocol specification version number (v0.10.0 packed `0x000A`). | | `0x0006` – `0x0009` | `DataOffset` | `uint32_t` | 4 Bytes | `4096` (`0x00001000`) | Fixed constant (`4096`). Section 2 always starts at byte 4096 (Page 1). | | `0x000A` – `0x000B` | `DomainCount` | `uint16_t` | 2 Bytes | Variable | Total number of node domains in the catalog (up to 65,536). | | `0x000C` – `0x000D` | `RelationCount` | `uint16_t` | 2 Bytes | Variable | Total number of relations in the matrix (up to 65,536). | | `0x000E` – `0x0015` | `TimestampMs` | `uint64_t` | 8 Bytes | Epoch Milliseconds | Unix epoch timestamp (milliseconds) when snapshot was created. | | `0x0016` – `0x001D` | `GlobalRequiredFeatures` | `uint64_t` | 8 Bytes | Bitmask | **Global Feature-in-Use Bitmask** (64-bit feature flags). | | `0x001E` – `0x0025` | `FooterDirectoryOffset` | `uint64_t` | 8 Bytes | Absolute File Offset | File offset to Footer Directory Table (`0` if Page 1 directory is used). | | `0x0026` – `0x002D` | `FooterDirectoryBytes` | `uint64_t` | 8 Bytes | Byte Size | Byte size of Footer Directory Table (`0` if omitted). | | `0x002E` – `0x003D` | `SnapshotUUID` | `uint8_t[16]` | 16 Bytes | Random Binary UUID | Unique 128-bit Binary UUID for this snapshot build artifact. | | `0x003E` – `0x003F` | `HeaderChecksum` | `uint16_t` | 2 Bytes | CRC-16-CCITT | Fast CRC-16 checksum calculated over bytes `0x0000..0x003D`. | | `0x0040` – `0x0041` | `IndexCount` | `uint16_t` | 2 Bytes | Variable | Number of secondary index descriptors in Section 2.6. | | `0x0042` – `0x0FFF` | `ReservedPadding` | `uint8_t[4030]` | 4030 Bytes | `0x00 ...` | **Reserved Header Expansion Padding** (Aligns Header to 4KB boundary). | --- ## 3. Section 2: Catalog, String Table & Directory Table Layout Begins at byte offset `DataOffset` (byte 4096). Contains the **Shared String Table**, node domain definitions, and the **Relation Directory Table**. ### 3.1 Shared String Table (String Pool Heap) Begins at byte offset `DataOffset` (4096): * `StringTableBytes` (`uint32_t`, 4B): Total byte size of string pool blob. * `StringPool` (`byte[StringTableBytes]`): Contiguous null-terminated UTF-8 byte stream starting with `\0` at offset `0`. - String offset `0` corresponds to empty string `""`. - All domain names, relation names, and attribute names store a 32-bit `name_offset` pointing directly to their null-terminated UTF-8 byte stream in this pool. ### 3.2 Domain Catalog Array (Fixed 16 Bytes per Domain) Begins immediately after String Table, aligned to a 128-byte boundary. Contains `DomainCount` fixed-size 16-byte records: | Byte Offset | Field Name | C-ABI Type | Size | Description | | :--- | :--- | :--- | :--- | :--- | | `0x0000` – `0x0001` | `DomainID` | `uint16_t` | 2 Bytes | Zero-indexed domain identifier (`0`..`DomainCount - 1`). | | `0x0002` | `KeyType` | `uint8_t` | 1 Byte | Domain key primitive type enum (`0x01` = INT8..`0x0B` = VAR_STRING). | | `0x0003` | `Reserved` | `uint8_t` | 1 Byte | `0x00` alignment padding. | | `0x0004` – `0x0007` | `NameOffset` | `uint32_t` | 4 Bytes | 0-indexed byte offset into String Table (points to null-terminated string, e.g., `"User\0"`). | | `0x0008` – `0x000F` | `NodeCount` | `uint64_t` | 8 Bytes | Total number of nodes $N$ in this domain. | ### 3.3 Relation Directory Table (Fixed 128 Bytes per Relation) Begins immediately after Domain Catalog Array, aligned to a 128-byte boundary. Contains `RelationCount` relation descriptors, **sorted primary by `SrcDomainID` and secondary by `TgtDomainID`**: | Byte Offset | Field Name | C-ABI Type | Size | Description | | :--- | :--- | :--- | :--- | :--- | | `0x0000` – `0x0001` | `RelationID` | `uint16_t` | 2 Bytes | Zero-indexed relation identifier (`0`..`RelationCount - 1`). | | `0x0002` – `0x0003` | `SrcDomainID` | `uint16_t` | 2 Bytes | Domain ID of source nodes. | | `0x0004` – `0x0005` | `TgtDomainID` | `uint16_t` | 2 Bytes | Domain ID of target nodes. | | `0x0006` | `EncodingID` | `uint8_t` | 1 Byte | Topology encoding enum (`0x00` = `ENCODING_RAW`, `0x01` = `ZSTD`). | | `0x0007` | `NodeIDWidth` | `uint8_t` | 1 Byte | Byte width of target node IDs (`0x02` = `uint16_t`, `0x04` = `uint32_t`, `0x08` = `uint64_t`). | | `0x0008` | `EdgeIndexWidth` | `uint8_t` | 1 Byte | Byte width of CSR row offsets (`0x04` = `uint32_t`, `0x08` = `uint64_t`). | | `0x0009` – `0x000B` | `Reserved1` | `uint8_t[3]` | 3 Bytes | `0x00` alignment padding. | | `0x000C` – `0x000F` | `NameOffset` | `uint32_t` | 4 Bytes | 0-indexed byte offset into String Table (points to null-terminated string, e.g., `"FOLLOWS\0"`). | | `0x0010` – `0x0017` | `NodeCount` | `uint64_t` | 8 Bytes | Number of source nodes ($N$) in relation matrix. | | `0x0018` – `0x001F` | `EdgeCount` | `uint64_t` | 8 Bytes | Total number of directed edges ($E$) in relation matrix. | | `0x0020` – `0x0027` | `SectionFeatures` | `uint64_t` | 8 Bytes | Per-relation feature bitmask (bit 0 = CSC, bit 1 = weighted, bit 2 = virtual relation, bits 3..4 = multiplicity). | | `0x0028` – `0x002F` | `CsrRowOffOffset` | `uint64_t` | 8 Bytes | Absolute file offset to `csrRowOffsets` array (128B aligned; `0` if Virtual or `M:1`/`1:1`). | | `0x0030` – `0x0037` | `CsrRowOffBytes` | `uint64_t` | 8 Bytes | Byte size of `csrRowOffsets` array ($= (N + 1) \times \text{EdgeIndexWidth}$; `0` if Virtual or `M:1`/`1:1`). | | `0x0038` – `0x003F` | `CsrColIdxOffset` | `uint64_t` | 8 Bytes | Absolute file offset to `csrColumnIndices` array (128B aligned; `0` if Virtual). | | `0x0040` – `0x0047` | `CsrColIdxBytes` | `uint64_t` | 8 Bytes | Byte size of `csrColumnIndices` array ($= E \times \text{NodeIDWidth}$; `0` if Virtual). | | `0x0048` – `0x004F` | `CscRowOffOffset` | `uint64_t` | 8 Bytes | Absolute file offset to optional `cscRowOffsets` array (`0` if omitted, Virtual, or `1:M`/`1:1`). | | `0x0050` – `0x0057` | `CscRowOffBytes` | `uint64_t` | 8 Bytes | Byte size of `cscRowOffsets` array (`0` if omitted, Virtual, or `1:M`/`1:1`). | | `0x0058` – `0x005F` | `CscColIdxOffset` | `uint64_t` | 8 Bytes | Absolute file offset to optional `cscColumnIndices` array (`0` if omitted or Virtual). | | `0x0060` – `0x0067` | `CscColIdxBytes` | `uint64_t` | 8 Bytes | Byte size of `cscColumnIndices` array (`0` if omitted or Virtual). | | `0x0068` – `0x0069` | `AttrCount` | `uint16_t` | 2 Bytes | Number of edge attributes defined for this relation (`0` if Virtual). | | `0x006A` – `0x007F` | `Reserved2` | `uint8_t[22]` | 22 Bytes | Zero-padded for 128-byte cache-line alignment (overloaded with `ImpulseVirtualRelationPayload` when `IMP_REL_FEATURE_VIRTUAL` is set). | #### 3.3.1 Virtual Super-Relation C-ABI Payload (`Reserved2` Overload & Overflow Rules) When `IMP_REL_FEATURE_VIRTUAL` (`Bit 2`) is enabled in `SectionFeatures`: * **Inline Fast Path ($1 \le \text{component\_count} \le 10$)**: Bytes `0x006A` – `0x007F` (22 bytes) in the `RelationDirectoryEntry` are overloaded to store the constituent relation payload directly inside the fixed 128-byte entry (zero extra file reads or memory allocations): ```c struct ImpulseVirtualRelationPayload { uint16_t component_count; // Number of constituent physical relation IDs (1 <= C <= 10) uint16_t component_ids[10]; // Inline array of constituent physical RelationIDs (padded with 0x0000) }; ``` * **Overflow Extended Path ($\text{component\_count} > 10$, up to 65,536)**: For large virtual relations composed of more than 10 physical relations: 1. `component_ids[0]` is set to `0xFFFF` (Overflow Sentinel Flag). 2. `CsrColIdxOffset` (8-byte `uint64_t`) stores a 128B-aligned absolute file offset to an off-heap array of `uint16_t component_ids[component_count]`. 3. `CsrColIdxBytes` stores the byte size ($= \text{component\_count} \times 2$). * **Maximum Theoretical Capacity**: Up to **65,536 physical relations** per virtual super-relation (matching the overall `.imps` relation limit). --- #### 3.3.2 Per-Relation Feature Bitmask (`SectionFeatures` 64-bit Layout) The `SectionFeatures` field defines C-ABI flags and structural contracts for topology storage: ```c #define IMP_REL_FEATURE_CSC (1ULL << 0) // Bit 0: CSC Transpose Index Present #define IMP_REL_FEATURE_WEIGHTED (1ULL << 1) // Bit 1: Edge Weights Present #define IMP_REL_FEATURE_VIRTUAL (1ULL << 2) // Bit 2: Virtual Super-Relation (No physical arrays on disk) // Multiplicity Bitmask (Bits 3..4) #define IMP_REL_CARDINALITY_MASK (3ULL << 3) // Bitmask for relation multiplicity (Bits 3..4) #define IMP_REL_CARDINALITY_M_N (0ULL << 3) // Many-to-Many (Default full CSR/CSC layout) #define IMP_REL_CARDINALITY_M_1 (1ULL << 3) // Many-to-One (Flat target array, CsrRowOffBytes = 0) #define IMP_REL_CARDINALITY_1_M (2ULL << 3) // One-to-Many (Forward CSR, reverse flat CSC array) #define IMP_REL_CARDINALITY_1_1 (3ULL << 3) // One-to-One (Flat bi-directional direct arrays) ``` --- ### 3.4 Attribute Descriptor Structure (Fixed 44 Bytes) Every node attribute and edge attribute is defined by a fixed 44-byte POD struct: | Byte Offset | Field Name | C-ABI Type | Size | Description | | :--- | :--- | :--- | :--- | :--- | | `0x0000` – `0x0003` | `NameOffset` | `uint32_t` | 4 Bytes | 0-indexed byte offset into String Table (points to null-terminated string, e.g., `"weight\0"`). | | `0x0004` | `TypeCode` | `uint8_t` | 1 Byte | Base Primitive Type (`Bits 0..6`) + `0x80` Nullability Flag (`Bit 7`). | | `0x0005` | `Reserved1` | `uint8_t` | 1 Byte | `0x00` alignment padding. | | `0x0006` – `0x0007` | `Reserved2` | `uint16_t` | 2 Bytes | `0x00` alignment padding. | | `0x0008` – `0x000B` | `Dimension` | `uint32_t` | 4 Bytes | Element dimension $D$ ($1$ for scalar, $D \ge 1$ for fixed vectors, $0$ for variable-length). | | `0x000C` – `0x0013` | `DataOffset` | `uint64_t` | 8 Bytes | 128B-aligned absolute file offset to attribute data array / payload blob. | | `0x0014` – `0x001B` | `DataBytes` | `uint64_t` | 8 Bytes | Total byte size of attribute data array / payload blob. | | `0x001C` – `0x0023` | `OffsetsOffset` | `uint64_t` | 8 Bytes | 128B-aligned absolute file offset to `uint32_t offsets[]` array (`0` for fixed-width). | | `0x0024` – `0x002B` | `OffsetsBytes` | `uint64_t` | 8 Bytes | Total byte size of `uint32_t offsets[]` array ($= (K + 1) \times 4$; `0` for fixed-width). | --- ### 3.5 Section 2.6: Secondary Index Directory Table (Fixed 64 Bytes per Index) Begins immediately after Relation Directory Table, aligned to a 128-byte boundary. Contains `IndexCount` generic secondary index descriptors: | Byte Offset | Field Name | C-ABI Type | Size | Description | | :--- | :--- | :--- | :--- | :--- | | `0x0000` – `0x0003` | `IndexID` | `uint32_t` | 4 Bytes | Zero-indexed secondary index identifier (`0`..`IndexCount - 1`). | | `0x0004` – `0x0005` | `DomainID` | `uint16_t` | 2 Bytes | Target Node Domain ID. | | `0x0006` – `0x0007` | `RelationID` | `uint16_t` | 2 Bytes | Target Relation ID (`0xFFFF` for Node Domain attributes). | | `0x0008` – `0x0009` | `AttributeIndex` | `uint16_t` | 2 Bytes | 0-indexed Attribute index within target relation or node domain. | | `0x000A` | `IndexType` | `uint8_t` | 1 Byte | Generic Index Type enum (`0x01` = Permutation, `0x02` = ZoneMap, `0x03` = InvertedBitSet, `0x04` = MPHF, `0x05` = Trigram, `0x06` = DomainSplit, `0x07` = TemporalInterval, `0x08` = VamanaANN [`IMP_INDEX_VAMANA_ANN`, `v0.10.0`]). | | `0x000B` | `Reserved1` | `uint8_t` | 1 Byte | `0x00` alignment padding. | | `0x000C` – `0x000F` | `NameOffset` | `uint32_t` | 4 Bytes | 0-indexed byte offset into String Table (e.g., `"idx_user_email\0"`). | | `0x0010` – `0x0017` | `DataOffset` | `uint64_t` | 8 Bytes | Absolute 128B-aligned file offset to index data payload blob. | | `0x0018` – `0x001F` | `DataBytes` | `uint64_t` | 8 Bytes | Total byte size of index data payload blob. | | `0x0020` – `0x0027` | `PayloadFeatureMask` | `uint64_t` | 8 Bytes | Generic Index Feature Bitmask (e.g. hash seed, metric flags). | | `0x0028` – `0x003F` | `ReservedPadding` | `uint8_t[24]` | 24 Bytes | Reserved for future index engine parameters (`0x00`). | #### 3.5.1 Constructing & Attaching Secondary Indices (`impulse_index.h`) * **Automatic Primary Key Index (`impulse build`)**: When building an `.imps` snapshot from a `manifest.json` via `impulse build`, the compiler automatically populates the domain key catalog index (`_domain_index`) and attribute min/max metadata. * **Programmatic Secondary Index Construction (C-ABI & Rust)**: The 8 secondary index families (`0x01` Permutation, `0x02` ZoneMap, `0x03` InvertedBitSet, `0x04` MinimalPerfectHash, `0x05` Trigram, `0x06` DomainSplitBitset, `0x07` TemporalInterval, and `0x08` VamanaANN [`Planned v0.10.0`]) are constructed in `impulse_index.h` via `impulse_index_build_permutation(const void* attr_data, size_t element_count, uint8_t type_code, void** out_bytes, size_t* out_size)`, `impulse_index_build_zone_map(const void* attr_data, size_t element_count, uint8_t type_code, void** out_bytes, size_t* out_size)`, `impulse_index_build_minimal_perfect_hash(const char** keys, size_t count, void** out_bytes, size_t* out_size)` (plus `impulse_index_build_inverted_bitset`, `impulse_index_build_trigram`, `impulse_index_build_domain_split`, `impulse_index_build_temporal_interval`, and Rust `vamana::build_vamana_index` / CLI `impulse attach-embeddings`) and attached to the snapshot writer via `impulse_writer_add_index(writer, domain_id, relation_id, attribute_index, index_type, index_name, index_data, index_bytes, payload_feature_mask)` (or Rust `SnapshotWriter::add_index` / `SnapshotWriter::add_vamana_index`). * **Transient Scratch Indices & `.imps.idx` Sidecars**: Opcodes `OP_CREATE_SCRATCH_INDEX` (`0x1E`) and `OP_DROP_SCRATCH_INDEX` (`0x1F`) allocate and free transient secondary indices in the query scratch workspace; external `.imps.idx` sidecar file persistence is a reserved specification extension. #### 3.5.2 Section 2.6 Index Type `0x08`: Vamana (DiskANN) Graph Index Layout (`v0.10.0`) > **Specification Compatibility Note**: `IMP_INDEX_VAMANA_ANN = 0x08` is stored inside the Section 2.6 Secondary Index Directory alongside the `v0.10.0` Page 0 Header (`Version = 0x000A`, `Magic = "IMPS"`). When `IndexType == 0x08` (`IMP_INDEX_VAMANA_ANN`), the `IndexDirectoryEntry.DataOffset` points to a 128-byte-aligned **64-byte `VamanaHeader`** (`spec.rs:380-396`), followed by a 128-byte-aligned fixed-degree adjacency slab and an optional 128-byte-aligned quantized routing code slab: | Byte Offset | Field Name | C-ABI Type | Size | Description | | :--- | :--- | :--- | :--- | :--- | | `0x00` – `0x03` | `magic` | `uint32_t` | 4 Bytes | `0x56414D41` (`"VAMA"` in Little-Endian). | | `0x04` – `0x05` | `version` | `uint16_t` | 2 Bytes | Vamana index format version (`1`). | | `0x06` | `metric` | `uint8_t` | 1 Byte | Distance/similarity metric (`0` = `L2`, `1` = `Cosine`, `2` = `Dot`, `3` = `Hamming`). | | `0x07` | `quant_type` | `uint8_t` | 1 Byte | Routing code quantization (`0` = `None`, `1` = `BQ1`, `2` = `SQ8`, `3` = `FP16`). | | `0x08` – `0x09` | `domain_id` | `uint16_t` | 2 Bytes | Target Node Domain ID (`0`..`DomainCount - 1`). | | `0x0A` – `0x0B` | `vec_attr_id` | `uint16_t` | 2 Bytes | 0-indexed Node Domain vector attribute index (`FLOAT32`, `Dimension = D`). | | `0x0C` – `0x0F` | `dimension` | `uint32_t` | 4 Bytes | Embedding vector dimension $D \ge 1$. | | `0x10` – `0x17` | `node_count` | `uint64_t` | 8 Bytes | Number of indexed nodes $N$ in the domain. | | `0x18` – `0x1B` | `max_degree_r` | `uint32_t` | 4 Bytes | Maximum Vamana out-degree bound $R$ per node (e.g., `R = 32`). | | `0x1C` – `0x1F` | `medoid_node_id` | `uint32_t` | 4 Bytes | Dense Node ID of the dataset medoid entry point $m^* \in [0, N)$. | | `0x20` – `0x23` | `alpha` | `float` | 4 Bytes | Vamana `RobustPrune` diversity parameter $\alpha \ge 1.0$ (IEEE 754 `f32`, e.g., `1.2`). | | `0x24` – `0x27` | `ef_construction` | `uint32_t` | 4 Bytes | Build-time greedy search beam width $L_{\text{build}}$ (e.g., `100`). | | `0x28` – `0x2F` | `adj_slab_offset` | `uint64_t` | 8 Bytes | Absolute 128-byte-aligned file offset to the fixed-degree adjacency slab. | | `0x30` – `0x37` | `adj_slab_bytes` | `uint64_t` | 8 Bytes | Byte size of the adjacency slab ($= N \times (R + 1) \times 4$). | | `0x38` – `0x3F` | `quant_code_offset` | `uint64_t` | 8 Bytes | Absolute 128-byte-aligned file offset to the quantized routing slab (`0` if `quant_type == 0`). | * **128-Byte-Aligned Fixed-Degree Adjacency Slab (`adj_slab_offset`)**: Stored as $N$ contiguous fixed-stride rows of $(R + 1)$ 32-bit unsigned integers (`N * (R + 1) * 4` bytes total). Row $u \in [0, N)$ begins at `adj_slab_offset + u * (R + 1) * 4` and encodes `[deg, nb_0, nb_1, ..., nb_{deg-1}, 0xFFFFFFFF, ...]`, where `deg <= R` is the out-degree and unused neighbor slots `[deg..R)` are padded with `0xFFFFFFFF`. * **128-Byte-Aligned Quantized Routing Code Slab (`quant_code_offset`)**: Optional compact vector representations scanned during greedy beam routing (`OP_VECTOR_ANN_SEARCH` `0xCA`) to reduce DRAM bandwidth before exact `FLOAT32` reranking (`OP_VECTOR_RERANK_DOT` `0xCB`): - **`BQ1` (`quant_type = 1`)**: $\lceil D / 8 \rceil$ bytes per node; bit `(d & 7)` of byte `(d >> 3)` is `1` iff `vec[d] >= 0.0`. - **`SQ8` (`quant_type = 2`)**: $D$ bytes per node (`uint8_t[D]`); encodes normalized/clamped values in $[-1.0, 1.0]$ via `round(v * 127.0 + 128.0)` and decodes via `(code - 128.0) / 127.0`. - **`FP16` (`quant_type = 3`)**: $2 \times D$ bytes per node (`uint16_t[D]`, Little-Endian IEEE 754 binary16 half-precision). --- ## 4. Topology & Attribute Specification ### 4.1 Topology Mechanics & Multiplicity Optimizations * **Many-to-Many (`IMP_REL_CARDINALITY_M_N`)**: Topology is standard CSR (`csrRowOffsets` + `csrColumnIndices`). Target $k$ of node $i$ is read at `csrColumnIndices[csrRowOffsets[i] + k]`. * **Many-to-One (`IMP_REL_CARDINALITY_M_1`)**: Every source node has at most 1 target node. `csrRowOffsets` is omitted (`CsrRowOffBytes = 0`). `csrColumnIndices` becomes a flat direct array of length $N$. Target node ID for source node $i$ is read directly at `csrColumnIndices[i]` (where `MAX_UINT` indicates no edge). * **One-to-Many (`IMP_REL_CARDINALITY_1_M`)**: Forward CSR is standard (`csrRowOffsets` + `csrColumnIndices`). Reverse CSC transpose omits `cscRowOffsets` (`CscRowOffBytes = 0`), storing a flat direct source node ID array in `cscColumnIndices`. * **One-to-One (`IMP_REL_CARDINALITY_1_1`)**: Both `csrRowOffsets` and `cscRowOffsets` are omitted. Forward and reverse traversals use flat direct arrays in $O(1)$ single-hop dereferences. * **Virtual Super-Relations (`IMP_REL_FEATURE_VIRTUAL`)**: Contains no physical topology arrays. `ImpulseVM` resolves the relation by expanding traversals over `component_ids[0 .. component_count - 1]` and unioning intermediate bitsets via `OP_SET_UNION` or `OP_CSC_WALK`. * **Optional CSC Transpose**: An incoming transpose index (`cscRowOffsets` + `cscColumnIndices`) may be included for bidirectional traversals. * **Explicit Reverse Relations**: Reverse relations (e.g. `MEMBER_OF_REVERSE`) are represented explicitly as first-class catalog relations. ### 4.2 Attribute Storage Architecture (Structure of Arrays) Attributes are partitioned into fixed-length primitives, fixed-width vectors, and variable-length payloads stored in **Structure of Arrays (SoA)** layout. #### 4.2.1 Bitwise Nullability Flag & Base Type Mask Attribute data types are encoded in an 8-bit field (`uint8_t type_code`): ```c #define IMPULSE_TYPE_MASK 0x7F // Bits 0..6: Base Primitive Type (Up to 128 base types) #define IMPULSE_NULLABLE_FLAG 0x80 // Bit 7: Nullability Flag (1 = Nullable with Validity Bitmap, 0 = Non-Null) // Bitwise evaluation in C-ABI parsers uint8_t base_type = descriptor->type_code & IMPULSE_TYPE_MASK; bool is_nullable = (descriptor->type_code & IMPULSE_NULLABLE_FLAG) != 0; ``` * **Non-Nullable (`is_nullable == false`, Bit 7 = 0)**: Zero validity bitmap overhead. 100% of memory is allocated to contiguous data values. * **Nullable (`is_nullable == true`, Bit 7 = 1)**: A 128-byte aligned **Validity Bitmap** (`uint64_t validity_bitmap[(K + 63) / 64]`) is placed at `DataOffset`. The validity bitmap MUST be strictly padded with `0x00` to the nearest 128-byte boundary. The actual data payload array begins immediately after the padded bitmap, guaranteeing that the data array remains strictly 128-byte aligned for hardware SIMD load instructions. ($1\text{ bit per entity}$, Bit $i=1 \rightarrow$ valid value, Bit $i=0 \rightarrow$ null). #### 4.2.2 Base Data Type Table (`0x00` .. `0x7F` Base Codes) | Base Code (`0x7F`) | Base Type Name | Non-Null Code | Nullable Code (`0x80`) | Dimension (`dim`) | Memory Layout | | :--- | :--- | :--- | :--- | :--- | :--- | | `0x01` | `INT8` | `0x01` | `0x81` | $\ge 1$ | $1 \times \text{dim}$ Bytes (`int8_t` / `uint8_t`) | | `0x02` | `INT16` | `0x02` | `0x82` | $\ge 1$ | $2 \times \text{dim}$ Bytes (`int16_t` / `uint16_t`) | | `0x03` | `INT32` | `0x03` | `0x83` | $\ge 1$ | $4 \times \text{dim}$ Bytes (`int32_t` / `uint32_t`) | | `0x04` | `INT64` | `0x04` | `0x84` | $\ge 1$ | $8 \times \text{dim}$ Bytes (`int64_t` / `uint64_t`) | | `0x05` | `FLOAT16` | `0x05` | `0x85` | $\ge 1$ | $2 \times \text{dim}$ Bytes (bfloat16 / fp16) | | `0x06` | `FLOAT32` | `0x06` | `0x86` | $\ge 1$ | $4 \times \text{dim}$ Bytes (IEEE 754 float, **edge weights**) | | `0x07` | `FLOAT64` | `0x07` | `0x87` | $\ge 1$ | $8 \times \text{dim}$ Bytes (IEEE 754 double, high precision) | | `0x08` | `TIMESTAMP_MS` | `0x08` | `0x88` | $\ge 1$ | $8 \times \text{dim}$ Bytes (uint64 epoch ms) | | `0x09` | `TIMESTAMP_NS` | `0x09` | `0x89` | $\ge 1$ | $8 \times \text{dim}$ Bytes (uint64 epoch ns) | | `0x0A` | `FIXED_BYTES` | `0x0A` | `0x8A` | $\ge 1$ | $\text{dim}$ Bytes (dim=16 for UUID, dim=32 for SHA-256) | | `0x0B` | `VAR_STRING` | `0x0B` | `0x8B` | Ignored (`0`) | Variable UTF-8 (`uint32_t offsets[]` + Data Blob) | | `0x0C` | `VAR_BYTES` | `0x0C` | `0x8C` | Ignored (`0`) | Variable Binary (`uint32_t offsets[]` + Data Blob) | | `0x0D` | `INTERVAL_SEC_32` | `0x0D` | `0x8D` | $\ge 1$ | 8 Bytes packed struct (`uint32_t start_sec`, `uint32_t duration_sec`) | | `0x0E` | `INTERVAL_MS_64` | `0x0E` | `0x8E` | $\ge 1$ | 16 Bytes packed struct (`uint64_t start_ms`, `uint64_t duration_ms`) | --- ### 4.3 Detailed Physical Storage Rules for Attributes Attribute storage layout depends on whether the attribute is fixed-width (scalar / vector) or variable-length. #### 4.3.1 Fixed-Width Primitives & Vector Attributes ($D \ge 1$) * **Location**: Edge attributes sit in the **Relation Block** immediately following topology arrays; Node attributes sit in **Node Domain Blocks**. * **Offset & Alignment**: Data array begins at absolute file offset `DataOffset`, aligned to a 128-byte boundary. * **Element Indexing**: Element $i$ ($0 \le i < K$, where $K = E$ for edges or $K = N$ for nodes) starts at byte offset: $$\text{ByteOffset}(i) = \text{DataOffset} + (i \times D \times \text{sizeof(BaseType)})$$ * **Hybrid Vector ANN Pairing (`v0.10.0`)**: Fixed-width `[N, D]` `FLOAT32` (`0x06`) Node Domain vector columns pair directly with Section 2.6 `IMP_INDEX_VAMANA_ANN` (`0x08`, see §3.5.2) via `VamanaHeader.vec_attr_id`. During query execution, `OP_VECTOR_ANN_SEARCH` (`0xCA`) traverses the Vamana adjacency and quantized routing slabs (`BQ1`/`SQ8`/`FP16`) to seed a `TYPE_BITSET_HANDLE` or `TYPE_LANE_FRONTIER`, and `OP_VECTOR_RERANK_DOT` (`0xCB`) evaluates exact SIMD dot-product scores against the 128-byte-aligned `[N, D]` `FLOAT32` column for only the surviving candidate nodes. #### 4.3.2 Variable-Length String & Binary Attributes (`VAR_STRING` 0x0B, `VAR_BYTES` 0x0C) * **Offsets Array**: Stored at 128B-aligned `OffsetsOffset` containing an array of $K + 1$ 32-bit unsigned integers (`uint32_t offsets[K + 1]`), where `offsets[0] = 0`. * **Data Payload Blob**: Stored at 128B-aligned `DataOffset` containing the raw concatenated UTF-8 text or binary bytes. * **Slice Extraction**: Payload bytes for element $i$ are extracted from `DataOffset + offsets[i]` with byte length `offsets[i + 1] - offsets[i]`. --- ### 4.4 Optional Snapshot Topology & Topology Inspection Opcodes (`0x19` .. `0x1C`) In accordance with the Impulse Graph Engine physical snapshot format specification, **all structural topology representations (CSR, CSC, COO) and Key Catalogs are fully optional**: * **CSR (Forward Out-Edges $u \to v$)**: Optional. Opcodes `OP_CSR_*` fail-fast with `IMPULSE_VM_ERR_NULL_SNAPSHOT` if absent. * **CSC (Reverse In-Edges $v \leftarrow u$)**: Optional. Opcodes `OP_CSC_*` fail-fast with `IMPULSE_VM_ERR_NULL_SNAPSHOT` if absent. * **COO (Coordinate Edge List $[E, 2]$)**: Optional. Opcodes `OP_COO_*` fail-fast with `IMPULSE_VM_ERR_NULL_SNAPSHOT` if absent. * **Key Catalogs (Dense Node ID $\leftrightarrow$ String Key / UUID)**: Optional. Opcodes `OP_MAP_KEYS_TO_DENSE` fail-fast if absent. To enable dynamic adaptive query execution without runtime exception traps, `ImpulseVM` provides 4 dedicated **Topology Inspection Opcodes**: | Opcode ID | Instruction Signature | Description | Result & Flags | | :--- | :--- | :--- | :--- | | **`0x19`** | **`OP_HAS_CSR R_DST, REL_ID`** | Inspects if relation `REL_ID` has CSR forward offsets installed | `R_DST = 1` if present, `0` if absent.
Sets `ZF = 0` (present) or `ZF = 1` (absent). | | **`0x1A`** | **`OP_HAS_CSC R_DST, REL_ID`** | Inspects if relation `REL_ID` has CSC reverse offsets installed | `R_DST = 1` if present, `0` if absent.
Sets `ZF = 0` (present) or `ZF = 1` (absent). | | **`0x1B`** | **`OP_HAS_COO R_DST, REL_ID`** | Inspects if relation `REL_ID` has COO edge list installed | `R_DST = 1` if present, `0` if absent.
Sets `ZF = 0` (present) or `ZF = 1` (absent). | | **`0x1C`** | **`OP_HAS_KEY_CATALOG R_DST, DOMAIN_ID`** | Inspects if domain `DOMAIN_ID` has String/UUID key catalog installed | `R_DST = 1` if present, `0` if absent.
Sets `ZF = 0` (present) or `ZF = 1` (absent). | | **`0x1D`** | **`OP_DENSE_WALK R_DST, R_SRC, REL_ID`** | Dense bitmask grid matrix traversal | Traverses `ENCODING_DENSE` bitmask grid relation. | | **`0x1E`** | **`OP_CREATE_SCRATCH_INDEX DOMAIN, ATTR, TYPE`** | Idempotently creates secondary index in transient scratch memory | Builds scratch index in RAM / `.imps.idx` sidecar if absent. | | **`0x1F`** | **`OP_DROP_SCRATCH_INDEX DOMAIN, ATTR, TYPE`** | Idempotently drops secondary index from transient scratch memory | Frees transient scratch index. | | **`0x20`** | **`OP_HAS_DENSE R_DST, REL_ID`** | Inspects if relation `REL_ID` is encoded as a `ENCODING_DENSE` bitmask grid | `R_DST = 1` if present, `0` if absent.
Sets `ZF = 0` (present) or `ZF = 1` (absent). | --- ## 5. Section 4: Key Catalogs & ID Mappings Section 4 stores the off-heap index structures required to resolve external business keys (Strings, UUIDs, Integers) to internal dense `0` to `N-1` Node IDs, and vice-versa. In accordance with the physical specification, $O(N)$ linear scans or heap allocations for key resolution are prohibited. All mappings MUST be performed in $O(1)$ or $O(\log N)$ using 128-byte aligned zero-copy memory mapped structures. ### 5.1 Dense ID to Key Resolution ($O(1)$ Array Lookup) The forward mapping (Dense ID $\to$ External Key) is implemented natively by storing the keys as a standard **Node Domain Attribute** (often implicitly named `_key` or identified via `IndexType = 0xFFFF`). - For fixed-width keys (e.g. `INT64`), the dense ID is simply used to directly index the 128B-aligned `data_ptr` array ($O(1)$ lookup). - For variable-length keys (e.g. `VAR_STRING`, `UUID128`), the dense ID indexes the `offsets_ptr` array to locate the slice within the `data_ptr` blob ($O(1)$ lookup). ### 5.2 Key to Dense ID Resolution ($O(1) / O(\log N)$ Reverse Index) The reverse mapping (External Key $\to$ Dense ID) requires a **Secondary Index Directory Entry** targeting the Node Domain. The structural format of the Section 4 index block depends on the `key_type` defined in the Domain Catalog: * **Variable Length Strings & UUIDs (`VAR_STRING`, `UUID128`)**: - Requires **IndexType `0x04` (IMP_INDEX_MINIMAL_PERFECT_HASH)**. - Resolves string keys to dense IDs in $O(1)$ time with $\approx 2-3$ bits/key overhead. * **Fixed-Width Integers (`INT32`, `INT64`)**: - Requires **IndexType `0x01` (IMP_INDEX_PERMUTATION)** or a direct sorted array. - Resolves integer keys to dense IDs in $O(\log N)$ time via binary search. --- ## 6. Footer Block & S3 Streaming Upload Specification ### 6.1 Single-Pass S3 Ingestion For unseekable S3 multi-part uploads, signatures, SHA-256 digests, and catalog directories are serialized into the **Footer Block at EOF**. ### 6.2 16-Byte Footer Trailer Specification Every compliant snapshot MUST terminate with exactly 16 bytes at EOF: ```c typedef struct impulse_footer_trailer { uint64_t footer_length; // 8 Bytes: Byte size of Footer Block uint32_t spec_version; // 4 Bytes: Protocol version (0x000A) uint32_t footer_magic; // 4 Bytes: "IMPS" (0x494D5053) } impulse_footer_trailer_t; // Exactly 16 Bytes at EOF ``` --- ## 7. Hardware Alignment & C-ABI Macros ```c // 128-Byte Alignment for AVX-512 SIMD & GPU Warp Coalescing #define IMPULSE_ALIGN_128(offset) (((offset) + 127ULL) & ~127ULL) // 4KB Page Alignment for OS Virtual Memory Area (VMA) Isolation #define IMPULSE_ALIGN_4K(offset) (((offset) + 4095ULL) & ~4095ULL) ``` ================================================================================ FILE: docs/reference/spec/schema-specification.md | URL: https://www.impulsegraph.org/reference/spec/schema-specification/ ================================================================================ # Schema & Manifest Specification (`manifest.yaml` / `schema.yaml`) This document defines the declarative schema and multi-tablespace manifest format (`manifest.yaml` / `schema.yaml` / `manifest.json`, originating from the Layer 0 normative `.imps.schema.yaml` specification) used across the Impulse Graph Engine ecosystem. A schema file serves four roles: 1. **Snapshot Compilation (`impulse-graph build` & `SnapshotBuilder`)**: Configures per-domain integer widths (`uint16`, `uint32`, `uint64`), key catalogs, CSR/CSC indices, relation multiplicities, and 128-byte-aligned Structure-of-Arrays (SoA) attributes. File-based batch compilation in `impulse-graph build` parses `manifest.json` ingestion manifests. 2. **Compile-Time Query Validation**: Verifies domain names, relation endpoints (`SrcDomainID` $\to$ `TgtDomainID`), and attribute types before emitting `impOps` bytecode. 3. **Code Generation (`impulse-codegen`, Maven/Gradle plugins)**: Generates strongly-typed domain views and `QueryBuilder` classes. 4. **Multi-Tablespace Composite Loading**: Maps logical domains and relations across multiple `.imps` files (supported in the Java 25 engine via `BinarySnapshotLoader.loadFromManifest(Path manifestPath, Arena arena)`, while C-ABI `impulse_snapshot_open` maps single `.imps` files directly and multi-snapshot federated C-ABI queries are targeted for post-`v1.0`). --- ## 1. Complete Schema Example ```yaml graphName: "EnterpriseKnowledgeGraph" tablespaces: core_identity: file: "chunks/core_identity.imps" commerce_events: file: "chunks/commerce_events.imps" domains: User: tablespace: core_identity denseId: uint32 # 0..N_d-1 addressing width (uint16 | uint32 | uint64) key: uuid # External primary key type (int32 | int64 | uuid | string | bytes) attributes: account_status: "FixedString(8)" display_name: "VarString" embedding: "Float32" Product: tablespace: core_identity denseId: uint32 key: string attributes: price: "Float32" category_code: "Int16?" relations: PURCHASED: source: User target: Product tablespace: commerce_events direction: [out, in] # Generates both CSR (forward) and CSC (reverse) cardinality: many_to_many # many_to_many | many_to_one | one_to_many | one_to_one attributes: timestamp: "TimestampMs" amount: "Float32" virtual_relations: ENGAGED_WITH: components: - PURCHASED - VIEWED - WISHLISTED ``` --- ## 2. Node Domains (`domains`) Every Node Domain owns an **independent 0-indexed dense integer space $0 \dots N_d-1$**. Dense ID `0` in `User` is distinct from Dense ID `0` in `Product`. | Property | Allowed Values | Description | | :--- | :--- | :--- | | **`denseId` / `idWidth`** | `uint16`, `uint32` *(default)*, `uint64` | Physical integer width used to store dense node IDs for this domain (`uint16`: up to `65,536` nodes; `uint32`: up to `4,294,967,296` nodes; `uint64`: up to $1.84 \times 10^{19}$ nodes). | | **`key`** | `int32`, `int64`, `uuid`, `string`, `bytes` | External business identifier format indexed in Section 4 (MPHF for `string`/`uuid`; sorted array for integers). | | **`tablespace`** | `` *(optional)* | Physical `.imps` chunk file hosting this domain in multi-file deployments. | | **`attributes`** | Map of attribute definitions | Contiguous 128-byte-aligned SoA columns attached to nodes in this domain. | --- ## 3. Edge Relations (`relations`) & Multiplicity Layouts Every directed relation explicitly binds a `source` domain and `target` domain: | Property | Allowed Values | Physical Storage & Optimizer Impact | | :--- | :--- | :--- | | **`source` / `target`** | Domain names | Maps source dense IDs ($0 \dots N_{\text{src}}-1$) to target dense IDs ($0 \dots N_{\text{tgt}}-1$). | | **`direction`** | `[out]`, `[in]`, `[out, in]` | `out` builds forward **CSR**; `in` builds reverse **CSC** transpose. | | **`cardinality`** | `many_to_many` *(default)*
`many_to_one`
`one_to_many`
`one_to_one` | - **`many_to_many` (`M:N`)**: Standard CSR/CSC (`row_offsets` + `col_indices`).
- **`many_to_one` (`M:1`)**: Format supports omitting `csrRowOffsets` for flat target arrays `col_indices[N]` (runtime engines currently evaluate traversals via CSR/CSC).
- **`one_to_many` (`1:M`)**: Forward CSR; reverse CSC layout.
- **`one_to_one` (`1:1`)**: Format supports bi-directional direct arrays (runtime engines currently evaluate traversals via CSR/CSC). | | **`virtual_relations`** | List of `1..65,536` physical relations | Zero-storage super-relation; expands across constituent relations and unions bitsets at query time. | --- ## 4. Attribute Data Types & Physical Limits | Schema Type | C-ABI Code | Element Size | Physical Storage & Maximum Limits | | :--- | :--- | :--- | :--- | | **`Int8` / `UInt8` / `Bool`** | `0x01` | $1 \times D$ bytes | Contiguous 128B-aligned array | | **`Int16` / `UInt16` / `Float16`** | `0x02` / `0x05` | $2 \times D$ bytes | Contiguous 128B-aligned array | | **`Int32` / `UInt32` / `Float32`** | `0x03` / `0x06` | $4 \times D$ bytes | Contiguous 128B-aligned array | | **`Int64` / `UInt64` / `Float64`** | `0x04` / `0x07` | $8 \times D$ bytes | Contiguous 128B-aligned array | | **`TimestampMs` / `TimestampNs`** | `0x08` / `0x09` | $8 \times D$ bytes | 64-bit Unix epoch timestamp | | **`FixedString(D)` / `FixedBytes(D)`**| `0x0A` | $D$ bytes | Fixed-stride array ($D = 16$ for UUID; max $D = 2^{32}-1$) | | **`VarString` / `VarBytes`** | `0x0B` / `0x0C` | Variable | `uint32_t offsets[K+1]` + payload blob (up to **4 GB** per column) | * **Nullable Columns (`nullable: true`)**: Prepends a 128-byte-aligned Arrow-compatible validity bitmap (`1` = valid, `0` = null) before the data array; non-nullable columns (`nullable: false`) have **0 bits** of bitmap overhead. --- ## 5. Schema Evolution Rules: Name is Identity In Impulse Graph, the **String Name** of a domain, relation, or attribute (stored in the Section 2 Shared String Table) is the semantic contract; the numeric `DomainID` or `RelationID` (`0..65,535`) is an internal per-snapshot detail resolved when a query is prepared or rebound. | Schema Change Across Snapshot Rebuilds | Impact on Queries | Safe? | | :--- | :--- | :--- | | **Add a new domain, relation, or attribute** | Ignored by existing queries | ✅ **Safe** | | **Add/remove nodes or edges** | Handled automatically via catalog cardinalities | ✅ **Safe** | | **Reorder `RelationID` or apply RCM node reordering** | Resolved by name during `prepare` / `rebind` | ✅ **Safe** | | **Rename or delete a referenced relation/attribute** | Fails fast at query `prepare` time | ❌ **Breaking** | | **Change a relation's `source` or `target` domain** | Fails domain type-check at `prepare` time | ❌ **Breaking** | ================================================================================ FILE: docs/reference/spec/vm-specification.md | URL: https://www.impulsegraph.org/reference/spec/vm-specification/ ================================================================================ # 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 `R0` through `R63`. - 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 `pc` register represents the zero-indexed instruction array offset of the currently executing instruction. - The `pc` **MUST** 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), the `pc` remains 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`–`0x80` reserved 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-bit `SafeExtendedInstruction`. --- ## 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: 1. `impulse_vm_context_create(const impulse_snapshot_t* snapshot)`: Allocates and pre-indexes an execution context. 2. `impulse_vm_context_destroy(impulse_vm_context_t* ctx)`: Safely deallocates all off-heap arenas. 3. `impulse_vm_context_acquire_bitset(impulse_vm_context_t* ctx)`: Returns a free BitSet slot handle index. 4. `impulse_vm_context_release_bitset(impulse_vm_context_t* ctx, size_t handle)`: Clears and frees a BitSet handle for reuse. 5. `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 pooled `TYPE_LANE_FRONTIER` (`0x10`) slots in the VM context (`v0.10.0`), paired with C-ABI inspection accessors `impulse_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)`, and `impulse_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 to `false`. - Nulls are considered unknown states. `NULL == NULL` evaluates to `false`, and `NULL != VALUE` evaluates to `false`. - If the `INVERT` flag is set on the instruction, null elements **MUST STILL** evaluate to `false`. 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_SUM` over weights `[5.0, NULL, 3.0]` yields `8.0`. - `OP_SET_CARDINALITY` or counting reductions over `[A, NULL, B]` yields `2`. - **Empty/Null State**: If a reduction operates entirely over null values (or an empty set), the VM **MUST** set the `ZF` (Zero Flag) to `1` and set the destination register to a default empty value (e.g., `0` for sums, `MAX_INT` for mins, `MIN_INT` for 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_reg` type tag **MUST** become `TYPE_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_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. - **`OP_LOAD_CONST_INT`** (`0x04`) - **Behavior**: Load a 64-bit integer into `dst_reg`. If the `OFFHEAP` modifier is set, the payload represents a pointer or offset; otherwise, it is loaded directly. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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 struct `impulse_vm_input_keys` with external string or integer keys. It matches these keys against the primary key attribute array of the domain specified by `domain_id` (retrieved from `payload & 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 execute `OP_HAS_KEY_CATALOG` (`0x1C`). - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. Sets `flags[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_reg` type tag **MUST** become `TYPE_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_reg` type tag **MUST** become `TYPE_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 at `offset_bytes` (lower 16 bits of payload) and copies them into a newly acquired float vector register. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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 by `dst_reg`) using raw row offsets and column targets from the inline data binding at byte offset `off_bytes` (lower 16 bits of payload) with node count `node_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 `.imps` snapshot file). This is used primarily for isolated assembly unit testing of traversal opcodes. - **Outcome**: Bypasses the need to mmap a physical `.imps` snapshot 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_reg` type tag **MUST** become `TYPE_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 the `flags` register. 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 the `ACCUMULATE` modifier flag is set on the instruction, the result set is unioned directly into the existing BitSet in `dst_reg` without 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's `attribute_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 `src` **MUST** be `TYPE_BITSET_HANDLE` or `TYPE_NODE_ID`. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. - **`OP_CSR_WALK_STATE`** (`0x0F`) - **Behavior**: State-propagating CSR walk updating attached node frontier state vectors. - **Type Requirements**: Source nodes register `src` **MUST** be `TYPE_BITSET_HANDLE` or `TYPE_NODE_ID`. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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 relation `rel` (upper 16 bits of payload), and writes target nodes into `dst_reg`. - **Usage**: If `src` contains a BitSet handle or single Node ID, it retrieves offsets and column targets from relation slot `rel` and performs a union of targets into `dst_reg`. Respects `ACCUMULATE` modifier flag to append targets. - **Type Requirements**: Source nodes register `src` **MUST** be `TYPE_BITSET_HANDLE` or `TYPE_NODE_ID`. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. - **`OP_CSR_WALK_FILTERED`** (`0x11`) - **Behavior**: Walk CSR applying attribute filter constraints. - **Usage**: Performs a CSR walk over relation `rel` from source `src` while validating a filter condition on edge or target node attributes. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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 node `u` in `src`. Attributes are pre-configured in `vm_state->query_context->attribute_slots[rel_id][attr_id]`, which are resolved from target snapshot Structure-of-Arrays (SoA) attribute blocks (with `src` = `payload & 0xFF`, `val_reg` = `(payload >> 8) & 0xFF`, `attr_id` = `(payload >> 16) & 0xFF`, `rel_id` = `(payload >> 24) & 0xFF`). - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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 by `reduce_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 specialized `0x16` opcode. - **`OP_CSC_WALK`** (`0x18`) - **Behavior**: Traverse relationship edges backwards using Compressed Sparse Column topology. - **Type Requirements**: Source nodes register **MUST** be `TYPE_BITSET_HANDLE` or `TYPE_NODE_ID`. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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_reg` type tag **MUST** become `TYPE_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_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. Sets `flags[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_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. Sets `flags[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_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. Sets `flags[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_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. Sets `flags[ZF]` if result is empty. - **`OP_MASK_AND`** (`0x24`) - **Behavior**: Bitwise AND of two SIMD masks / BitSets. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. - **`OP_MASK_OR`** (`0x25`) - **Behavior**: Bitwise OR of two SIMD masks / BitSets. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_BITSET_HANDLE`. - **`OP_MASK_NOT`** (`0x26`) - **Behavior**: Bitwise NOT (inversion) of a SIMD mask / BitSet up to active domain cardinality. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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_POINT` if 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-add `fma`). #### 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 to `dst_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 to `dst_reg` (transitioning it to `TYPE_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_reg` type tag **MUST** become `TYPE_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 is `0` with the fallback value. The resulting `dst_reg` vector **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_reg` and `src_reg` (the nullable vector). If `src_reg` is nullable, creates a BitSet handle in `dst_reg` wrapping the validity bitmap (yielding an $O(1)$ `IS NOT NULL` mask). If `src_reg` is not nullable, returns a BitSet containing all `1`s for the length of the vector. - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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_reg` and `ts_reg`. The `ts_reg` can 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 specify `rel_id` (upper 16 bits of base payload), `attr_id_start` (lower 16 bits of extension word), and `attr_id_end` (upper 16 bits of extension word). Returns a BitSet containing all target nodes where `attr_start <= ts_val < attr_end`. If an attribute bound is missing/null, it is treated as open (infinity). - **Type Transition**: `dst_reg` type tag **MUST** become `TYPE_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 `pc` to execution offset in payload. - **`OP_JZ`** (`0x51`) - **Behavior**: If `flags[ZF]` is set to 1, set `pc` to payload execution offset. - **`OP_JNZ`** (`0x52`) - **Behavior**: If `flags[ZF]` is set to 0, set `pc` to payload execution offset. - **`OP_LOOP_DECR`** (`0x53`) - **Behavior**: Decrement `dst_reg` (which **MUST** be `TYPE_INT64`). If result > 0, set `pc` to 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 `pc` to subroutine stack, then set `pc` to 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 `R0` as a `TYPE_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 in `impulse_vm_context_t` (`impulse_vm_context_set_fuel`), the VM halts execution safely and returns status code `IMPULSE_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_reg` value to 0 and type tag to `TYPE_NULL`. - **`OP_LOAD_INDIRECT`** (`0x72`) - **Behavior**: Load value into `dst_reg` from 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_28`** through **`OP_RESERVED_29`** (`0x28`–`0x29`) and **`OP_RESERVED_2B`** through **`OP_RESERVED_2C`** (`0x2B`–`0x2C`) - **`OP_RESERVED_3E`** through **`OP_RESERVED_3F`** (`0x3E`–`0x3F`; `0x3A`–`0x3D` are allocated to `OP_PROJECT_STATE`, `OP_COALESCE`, `OP_EXTRACT_VALIDITY`, and `OP_VECTOR_TIME_VALID_AT`) - **`OP_RESERVED_4C`** through **`OP_RESERVED_4F`** (`0x4C`–`0x4F`) - **`OP_RESERVED_59`** (`0x59`) - **`OP_RESERVED_5D`** through **`OP_RESERVED_5F`** (`0x5D`–`0x5F`) - **`OP_RESERVED_6D`** through **`OP_RESERVED_6F`** (`0x6D`–`0x6F`) - **`OP_RESERVED_76`** through **`OP_RESERVED_7F`** (`0x76`–`0x7F`; `0x80`–`0x8F` are allocated to columnar gather and multiplicity fast-path opcodes) - **`OP_RESERVED_96`** through **`OP_RESERVED_9F`** (`0x96`–`0x9F`; `0x90`–`0x95` are allocated to output materialization and dense walk opcodes) - **`OP_RESERVED_CC`** through **`OP_RESERVED_FE`** (`0xCC`–`0xFE`; `0xA0`–`0xBF` are allocated to §6.10 Edge Stream Shader instructions, `0xC0`–`0xCB` are allocated in `v0.10.0` to §6.11 Multi-Lane Bit-Sliced Execution & Hybrid Vector ANN instructions, and `0xFF` is reserved for the 128-bit `OP_EXTENSION_PAYLOAD` marker 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 via `OP_INIT_MOCK_GRAPH` or similar), `src_reg` (source vector or node set passed in `payload_low`), `rel_id` (relationship ID in `payload_high`), and `flags` containing the `shader_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_reg` points to the destination shader register. Payload indicates the `attr_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_reg` is 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**: `DIV` and `MOD` **MUST** adhere to `SAFE_DIV` semantics (if the divisor is `0.0`, the result evaluates to `0.0` instead of `Infinity` or 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`. The `func_id` **MUST** strictly correlate to the canonical subset declared in `impulse_math_ops.h` (e.g. `0x01` = ABS, `0x02` = SQRT, `0x34` = ISNAN). Out of domain bounds (e.g. `SQRT(-1.0)`) **MUST** yield an IEEE-754 `NaN` propagating natively without throwing an exception. - **`OP_STREAM_CMP_EQ`** (`0xB0`), **`NEQ`** (`0xB1`), **`GT`** (`0xB2`), **`LT`** (`0xB3`) - **Behavior**: Binary comparison ops. Evaluate to `1.0` if true, `0.0` if 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.0` or `1.0`). If `0.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 `v` into the destination BitSet handle when `S[src]` is non-zero (`!= 0.0` and `!NaN`). - **`OP_STREAM_SCATTER_REDUCE`** (`0xBF`) - **Behavior**: Scatters and accumulates `S[src]` into `float_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.0` freezes the baseline `0x00`..`0xBF` ISA and activates the `0xC0`..`0xCB` instruction block and `TYPE_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$), or `WIDTH_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 requiring `TYPE_LANE_FRONTIER` (`0x10`), or passing a `TYPE_LANE_FRONTIER` to a 1-bit set/walk opcode without an explicit bridge (`OP_LANE_FILTER_QUORUM`), **MUST** trap with `IMPULSE_VM_ERR_INVALID_REGISTER` (`6`). - **Unused Upper Bits Invariant**: For every node $u \in [0, N)$, `(lanes[u] & ~active_mask) == 0` **MUST** hold after every instruction. #### 6.11.2 Multi-Lane & Hybrid ANN Opcodes - **`OP_LANE_INIT_SEEDS`** (`0xC0`) - **Behavior**: Initializes a `TYPE_LANE_FRONTIER` handle in `dst_reg` by 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_reg` Types**: - `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) != 0` and `k_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_reg` becomes `TYPE_LANE_FRONTIER`. Sets `flags[ZF] = 1` iff all `lanes[u] == 0`. - **`OP_LANE_INIT_GROUPS`** (`0xC1`) - **Behavior**: Initializes a `TYPE_LANE_FRONTIER` handle in `dst_reg` where 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_reg` Types**: `TYPE_NODE_VECTOR` / `TYPE_UINT64_VECTOR` (paired with `groups_reg` vector or packed `(group_id << 32) | node_id` when `groups_reg == 0` or `flags & 1 != 0`) or `TYPE_NULL`. - **Type Transition**: `dst_reg` becomes `TYPE_LANE_FRONTIER`. Sets `flags[ZF] = 1` iff no lane bits are set. - **`OP_LANE_SET_EDGE_MASK`** (`0xC2`) - **Behavior**: Clones the source `TYPE_LANE_FRONTIER` and 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 subsequent `OP_LANE_CSR_WALK` / `OP_LANE_CSC_WALK` traversals. - **Encoding**: `src_reg = payload & 0xFF`, `edge_reg = (payload >> 8) & 0xFF`, `rel_id = (payload >> 16) & 0xFFFF`. - **Allowed `edge_reg` Types**: `TYPE_INT64` / `TYPE_NODE_ID` (trips edge `registers[edge_reg]` in lane `flags & 0x3F`), `TYPE_NODE_VECTOR` / `TYPE_UINT64_VECTOR` (if `(flags & 1) != 0`, unpacks `(lane_b << 32) | edge_idx`; else trips `vec[b]` in lane $b$), or `TYPE_NULL`. - **Type Transition**: `dst_reg` becomes `TYPE_LANE_FRONTIER`. - **`OP_LANE_CSR_WALK`** (`0xC3`) & **`OP_LANE_CSC_WALK`** (`0xC4`) - **Behavior**: Executes a bit-sliced forward (`0xC3` CSR) or reverse (`0xC4` CSC) 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** be `TYPE_LANE_FRONTIER`), `rel_id = (payload >> 16) & 0xFFFF`. - **Modifier Flags**: - `flags & 0x03 != 0` (`ACCUMULATE`): Preserves existing `current_lanes[u]` bits in `next_lanes[u]`. - `flags & 0x04 != 0` (`FIXPOINT`): Iterates delta-frontier propagation (`newly_reached = step_out[v] & ~out_lanes[v]`) until `newly_reached == 0` for all $v \in [0, N)$, with zero per-iteration heap allocations. - **Type Transition**: `dst_reg` becomes `TYPE_LANE_FRONTIER`. Sets `flags[ZF] = 1` iff all `out_lanes[u] == 0`. - **`OP_LANE_PRUNE_MASK`** (`0xC5`) - **Behavior**: Prunes lane bits from a `TYPE_LANE_FRONTIER` according to `mode = flags & 0x03`: - **Mode `0` (Explicit Deny Set / Per-Node Mask)**: Clears all lanes on nodes in a `TYPE_BITSET_HANDLE`, or clears `lanes[u] &= ~deny_vec[u]` for a vector, or clears `lanes[u] &= ~scalar_mask` for `TYPE_INT64`. - **Mode `1` (Disjoint Split-Half Collision Prune)**: Splits active lanes into low half $[0, \text{half})$ and high half $[\text{half}, k)$; zeroes `lanes[u]` if node $u$ is not reached by at least one lane in both halves. - **Mode `2` (Degree-Gated Hub Quorum Prune)**: For `max_deg = (payload >> 8) & 0xFF`, `min_quorum = (payload >> 16) & 0xFF`, `rel_id = (payload >> 24) & 0xFF`, zeroes `lanes[u]` whenever $\text{deg}(u) > \text{max\_deg}$ and $\text{popcount}(\text{lanes}[u]) < \text{min\_quorum}$. - **Type Transition**: `dst_reg` becomes `TYPE_LANE_FRONTIER`. Sets `flags[ZF] = 1` iff all `out_lanes[u] == 0`. - **`OP_LANE_FILTER_QUORUM`** (`0xC6`) - **Behavior**: Bridges from `TYPE_LANE_FRONTIER` (`0x10`) to a 1-bit `TYPE_BITSET_HANDLE` (`0x04`) by selecting nodes $u$ where at least `min_k` required 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 to `1` if `0`). 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_reg` becomes `TYPE_BITSET_HANDLE`. Sets `flags[ZF] = 1` iff the output BitSet is empty. - **`OP_LANE_REDUCE_AND`** (`0xC7`) - **Behavior**: Reduces a `TYPE_LANE_FRONTIER` across $n_{\text{check}} = (\text{payload\_high} > 0) \text{ ? } \min(N, \text{payload\_high}) \text{ : } N$ nodes into a 64-bit integer in `dst_reg`: - `flags == 0`: Bitwise AND of `lanes[u] & active_mask` across all $u \in [0, n_{\text{check}})$ (mask of lanes reaching *every* checked node). - `(flags & 1) != 0`: Complement `active_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_reg` becomes `TYPE_INT64`. Sets `flags[ZF] = 1` iff result is `0`. - **`OP_LANE_REDUCE_ATTR`** (`0xC8`) - **Behavior**: Performs a single-pass bit-sliced reduction of a node attribute array (`attr_id` or 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`): Outputs `TYPE_FLOAT_VECTOR` of length $k$. Untouched lanes receive `0.0f`. `NaN` attribute values are skipped. - `6` (`BINARY_OP_ARGMIN`), `7` (`BINARY_OP_ARGMAX`): Outputs `TYPE_UINT64_VECTOR` / `TYPE_NODE_VECTOR` of length $k$ containing the witness node ID for each lane (`-1` if untouched). **Deterministic Tie-Breaking**: Strictly uses `<` (for `ARGMIN`) or `>` (for `ARGMAX`) 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 to `max_k`), selects the node $u$ that covers the maximum number of remaining uncovered lanes in `uncovered_mask` (with optional positive cost weighting from `cost_reg` when `(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_reg` becomes `TYPE_NODE_VECTOR` containing the selected witness node IDs. Sets `flags[ZF] = 1` iff `uncovered_mask != 0` after 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 a `TYPE_LANE_FRONTIER` with $k = \text{top\_k}$ lanes; otherwise outputs a `TYPE_BITSET_HANDLE`. - **`OP_VECTOR_RERANK_DOT`** (`0xCB`) - **Behavior**: Computes exact dot-product reranking scores for candidate nodes in `cand_reg` (`TYPE_BITSET_HANDLE` or `TYPE_LANE_FRONTIER`) against query vector `q_reg` (`TYPE_FLOAT_VECTOR`). - **Encoding**: `cand_reg = payload & 0xFF`, `q_reg = (payload >> 8) & 0xFF`, `attr_id = (payload >> 16) & 0xFFFF`. - **Type Transition**: `dst_reg` becomes `TYPE_FLOAT_VECTOR`. Sets `flags[ZF] = 1` iff 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_dop` is configured to `1` (single-threaded mode), the interpreter **MUST** execute standard, sequential loop bodies without using atomic instructions (e.g., `bitset_add` instead of `bitset_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`/`free` or C++ `new`/`delete` calls). - **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 `MemorySegment` pointers 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 = `** / **`.vrel = `**: Binds a physical or virtual relation ID. * **`.fuel `**: Sets the instruction execution gas/fuel limit (e.g., `.fuel 1000`). * **`.csr_inline = { : [, ...], ... }`**: Defines an inline mock CSR adjacency matrix for isolated opcode testing without an external `.imps` file. * **`.array_float` / `.array_int` / `.array_node = [...]`**: Defines inline typed arrays in the VM context. * **`.set` / `.set_roaring` / `.set_dense = [, ...]`**: Defines inline polymorphic BitSet fixtures. ### 8.2 `.text` Section & `{{EXPECT: ...}}` Directives Instructions follow `[address]: , , ...` 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: ```nasm ; {{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: 1. **`TYPE_BITSET_HANDLE` (`0x04`)**: - `cardinality` (`uint64_t` LE): 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 = 0` is serialized. 2. **`TYPE_FLOAT_VECTOR` (`0x0C`)**: - `length` (`uint32_t` LE): Number of float elements. - `values` (`float32[length]` LE): IEEE 754 single-precision floats. - **Canonical Float Normalization**: All `NaN` representations are normalized to `0x7FC00000`. Negative zero (`-0.0f`) is normalized to positive zero (`+0.0f`). - If handle is invalid, `length = 0` is serialized. 3. **`TYPE_DOUBLE_VECTOR` (`0x0D`)**: - `length` (`uint32_t` LE): Number of double elements. - `values` (`float64[length]` LE): IEEE 754 double-precision floats. - **Canonical Double Normalization**: All `NaN` representations are normalized to `0x7FF8000000000000ULL`. Negative zero (`-0.0`) is normalized to positive zero (`+0.0`). - If handle is invalid, `length = 0` is serialized. 4. **`TYPE_NODE_VECTOR` (`0x05`) & `TYPE_UINT64_VECTOR` (`0x0E`)**: - `length` (`uint32_t` LE): Number of 64-bit integer elements. - `values` (`uint64_t[length]` LE): Contiguous 64-bit elements. - If handle is invalid, `length = 0` is serialized. 5. **`TYPE_LANE_FRONTIER` (`0x10`)**: - `num_lanes` (`uint32_t` LE): Number of configured logical lanes ($1 \le k \le 64$). - `max_lanes` (`uint32_t` LE): Physical bit-slice capacity (`8`, `16`, `32`, or `64`). - `active_mask` (`uint64_t` LE): Active bitmask indicating live lanes. - `node_count` (`uint32_t` LE): 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. 6. **`TYPE_STRING_VECTOR` (`0x0B`)**: - `count` (`uint32_t` LE): Number of strings. - For each string $j = 0 \dots \text{count}-1$: length `slen` (`uint32_t` LE) followed by `slen` raw UTF-8 bytes. 7. **`TYPE_VALUE_MAP` (`0x0A`)**: - `count` (`uint32_t` LE): Number of key-value pairs. - For each entry $j = 0 \dots \text{count}-1$: key length `klen` (`uint32_t` LE), `klen` UTF-8 key bytes, and `float32` LE value. 8. **Scalar and Null Registers**: No extra bytes are appended. ### 9.3 C-ABI State Hash Functions ```c /* 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: ```cpp 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_*`): ```cpp #define IMP_TYPE_BIT(t) (1u << static_cast(t)) #define IMPULSE_CHECK_REG_TYPE(vm_state, reg, allowed_mask) \ do { \ if (IMPULSE_UNLIKELY(((1u << static_cast((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: 1. **Pass 1: Disallowed Register Type Rejection**: - Synthesizes instructions with each of the 17 possible register dynamic types (`TYPE_NULL` through `TYPE_LANE_FRONTIER`) injected into `src`, `aux1`, and `aux2`. - Verifies that any type excluded by `allowed_src_types`, `allowed_aux1_types`, or `allowed_aux2_types` immediately returns `IMPULSE_VM_ERR_INVALID_REGISTER`. 2. **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]` matches `output_dst_types`. 3. **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_REGISTER` without memory access violations. 4. **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. 5. **Pass 5: Null Context & Snapshot Safety**: - For opcodes where `requires_context == true`, executes the instruction with `query_context = nullptr`. - Verifies that the VM safely returns `IMPULSE_VM_ERR_NULL_SNAPSHOT` without null-pointer dereferences. ================================================================================ FILE: docs/deployment/dynamic-service.md | URL: https://www.impulsegraph.org/deployment/dynamic-service/ ================================================================================ # Archetype 1: Long-Lived Dynamic Service The **Long-Lived Dynamic Service** archetype is designed for environments where upstream data changes over time and you need to serve sub-microsecond, read-only graph queries concurrently without interruption. !!! tip **The Near-Real-Time (< 5 Min) & Blob Storage Sweet Spot** Because an `.imps` file is essentially a collection of flat, contiguous arrays, most reasonably sized graphs can be rebuilt from scratch in just a few seconds. Periodically building a fresh `.imps` file, pushing it to **Blob Storage (S3/GCS)**, and performing an atomic Blue/Green swap across stateless pods is the sweet spot for near-real-time graph services. See **[Changing Data & Live Updates: "Wait—My Data Isn't Read-Only!"](../getting-started/handling-mutations.md)** for the full breakdown. ## Architecture Overview To guarantee 100% lock-free, SIMD-accelerated traversal speed, Impulse Graph never mutates an active graph in place. Instead, it separates **read-only query execution** from **out-of-band snapshot compilation**: 1. **Active Read-Only Snapshot (`Snapshot A`)**: Memory-mapped (`mmap`) into the service with zero locks and zero GC overhead. 2. **Out-of-Band Streaming Compiler**: Consumes upstream CDC events and streams a new immutable `.imps` snapshot (`Snapshot B`) direct to disk or object storage. 3. **Atomic A/B Pointer Swap (`SnapshotSwapManager`)**: Atomically redirects new queries to `Snapshot B` once ready, draining in-flight queries on `Snapshot A` before unmapping. ```mermaid graph TD Client[gRPC / HTTP Clients] --> Server[Application Service] Server --> Swap[SnapshotSwapManager] Swap --> SnapA["Active Snapshot A (mmap Read-Only)"] Swap -.->|Atomic A/B Swap| SnapB["New Snapshot B (mmap Read-Only)"] Kafka[Kafka / CDC Stream] --> Builder[Streaming SnapshotBuilder] Builder --> SnapB ``` ## Atomic A/B Snapshot Swap Because memory-mapping large `.imps` files is an $O(1)$ OS operation, rotating to a fresh snapshot never blocks active reader threads: 1. **Out-of-Band Build**: A background worker (using the `impulse-graph build` CLI or `SnapshotBuilder` ingestion pipeline) writes a new `.imps` snapshot file (`Snapshot B`) to disk. 2. **Atomic Reference Swap**: The application memory-maps `Snapshot B` and calls `swapManager.swap(newSnapshot)`, atomically updating the active reference. 3. **Zero Downtime & Lock-Free Draining**: Queries already in flight complete against `Snapshot A`. Once the last reader releases its reference, `Snapshot A`'s `Arena` is closed and unmapped. === "Java 25" ```java SnapshotSwapManager swapManager = new SnapshotSwapManager<>(initialSnapshot); // Reader thread: zero-lock acquisition var holder = swapManager.acquireCurrent(); if (holder != null) { try { GraphSnapshot active = holder.getResource(); // Execute read-only traversal... } finally { holder.release(); } } // Background updater thread: atomic A/B pointer swap swapManager.swap(newlyLoadedSnapshot); ``` ================================================================================ FILE: docs/deployment/fixed-snapshot.md | URL: https://www.impulsegraph.org/deployment/fixed-snapshot/ ================================================================================ # Archetype 2: Fixed-Snapshot Analytical Process The **Fixed-Snapshot Analytical Process** archetype is built for heavy offline compute workloads where the graph topology does not change during the execution run. This pattern is widely used in High-Performance Computing (HPC), machine learning pipelines, and complex systems simulations like the **Electrical Power Grid N-2 Contingency Simulation**. This architecture typically leverages **C++20** or **Rust** to achieve maximum instruction throughput, utilizing compile-time query plans and stack-allocated scratch space. ## The Consistent World Assumption In a fixed-snapshot environment, the engine memory-maps the base `.imps` file exactly once at startup. Because there is no concurrent writer mutating a delta layer, the engine enjoys a **consistent world assumption**: - **No Locks**: No read-write locks or concurrency checks on the hot path. - **No Tombstone Masking**: Traversals read directly from the contiguous Compressed Sparse Row (CSR) arrays. - **Cache Friendly**: Hardware prefetchers can aggressively stream adjacency lists. ## Pre-Compiled `ImpulseVM` Bytecode Execution When the schema is fixed for an analytical run, queries are compiled once into an immutable `CompiledQuery` (`impulse::vm::CompiledQuery` in C++20 or `MethodHandle` in Java 25) and executed across thousands of simulation seeds with zero per-query compilation overhead: === "C++20 (`impulse_vm_fluent.hpp`)" ```cpp #include "impulse_graph.h" #include "impulse_vm_fluent.hpp" using namespace impulse::vm; // Compile the island detection pipeline once at startup CompiledQuery islandDetector = QueryBuilder() .inputNode(0) .repeatUntilStable([](QueryBuilder& b) { b.walkEdge(/*BUS_TO_BUS=*/ 0); }) .collectBitset() .compile(); ``` ## Reusable Thread-Local Execution Contexts Because analytical processes often run parallel simulations (e.g., Monte Carlo or N-1/N-2 contingency sweeps across OpenMP threads), avoiding per-iteration heap allocation is critical. In C++ and Java, each worker thread reuses its own `impulse_vm_context_t` / `VmQueryContext` and stack-allocated `impulse_vm_state_t` register frame: === "C++20" ```cpp // Allocated once per worker thread impulse_vm_context_t* ctx = impulse_vm_context_create(snap); impulse_vm_state_t state{}; // Hot simulation loop: 640-byte stack frame + reusable bitset pool for (uint64_t seedBusId : contingencySeeds) { QueryResult res = islandDetector.executeWithContext(ctx, &state, seedBusId); } impulse_vm_context_destroy(ctx); ``` ================================================================================ FILE: docs/deployment/capacity-growth.md | URL: https://www.impulsegraph.org/deployment/capacity-growth/ ================================================================================ # Capacity Growth & Scratch Arena Sizing Because Impulse Graph Engine operates over **immutable `.imps` binary snapshots**, graph capacity growth and per-query scratch memory sizing are handled deterministically without in-place array resizing, stop-the-world reallocations, or JVM heap GC pressure. --- ## 1. Per-Domain Node Cardinality & `PrimitiveWidth` Boundaries Every node domain in an `.imps` snapshot defines an independent 0-indexed dense integer ID space ($0 \dots N_d - 1$) with a fixed `nodeCount` ($N_d$) and physical integer width (`PrimitiveWidth`): | `PrimitiveWidth` | Physical Type | Bytes per ID | Max Domain Cardinality ($N_d$) | | :--- | :--- | :---: | :--- | | **`PrimitiveWidth.UINT16`** | `uint16_t` | 2 bytes | Up to `65,536` nodes | | **`PrimitiveWidth.UINT32`** | `uint32_t` | 4 bytes | Up to `4,294,967,296` nodes | | **`PrimitiveWidth.UINT64`** | `uint64_t` | 8 bytes | $> 4.29\text{ billion}$ nodes | ### Growing Domain Cardinality via Out-of-Band Snapshot Rotation An active `.imps` snapshot is never mutated or resized in place. When upstream data grows—or when a domain's cardinality crosses a `PrimitiveWidth` boundary (for example, growing past `65,536` nodes from `UINT16` to `UINT32`): 1. **Out-of-Band Compilation**: `SnapshotBuilder` (Java) or `impulse snapshot build` (CLI) streams a new `.imps` snapshot generation to disk with the updated domain `nodeCount` and `PrimitiveWidth`: ```java SnapshotBuilder.create() .withStagingDirectory(Path.of("/tmp/staging")) .addDomain("User", DomainDefinition.builder(newCardinality) .idWidth(newCardinality <= 65_536 ? PrimitiveWidth.UINT16 : PrimitiveWidth.UINT32) .build()) // ... .writeTo(Path.of("graph_next.imps")); ``` 2. **Atomic A/B Swap (`SnapshotSwapManager`)**: The service memory-maps the newly built `.imps` file into a fresh `Arena.ofShared()` and atomically swaps the active snapshot reference via `SnapshotSwapManager.swap(newSnapshot)`: ```java // Reader threads acquire an epoch-counted reference var holder = swapManager.acquireCurrent(); if (holder != null) { try { GraphSnapshot snap = holder.getResource(); // Execute lock-free read-only query... } finally { holder.release(); } } // Background updater atomically swaps in the new snapshot generation swapManager.swap(newGraphSnapshot); ``` 3. **Zero-Downtime Draining**: In-flight queries on the previous snapshot complete normally. Once the previous holder's `getActiveReaders()` count reaches `0`, `SnapshotSwapManager` automatically closes the old `GraphSnapshot` and unmaps its off-heap `Arena`. --- ## 2. Bounded Off-Heap Query Scratch Memory (`VmQueryContext`) Because every `.imps` snapshot encodes the exact node cardinality $N_d$ per domain in its catalog header, intermediate traversal bitsets ($\lceil N_d / 64 \rceil$ 64-bit words) and register state vectors are sized deterministically from the snapshot metadata. ### 2.1 Java 25 `VmQueryContext` & `OffHeapBitSet` Pooling In `impulse-vm`, `VmQueryContext` manages off-heap scratch memory and reusable bitset handles bound to a `java.lang.foreign.Arena`: * **Bounded Scratch Capacity**: `VmQueryContext` tracks off-heap scratch allocations (`DEFAULT_SCRATCH_BYTES = 64 KB` baseline, `512 MB` default maximum cap) via `setMaxScratchCapacityBytes(long bytes)`, `getMaxScratchCapacityBytes()`, and 64-byte-aligned `allocateScratch(long bytes)` calls (validated at runtime by `OP_ALLOC_SCRATCH` and `OP_ASSERT_SCRATCH_BYTES`). * **Reusable `OffHeapBitSet` Handle Pool**: Calling `ctx.acquireBitset()` allocates an `OffHeapBitSet` inside the context's `Arena` sized to the snapshot's maximum domain node count (or recycles a cleared bitset from `freeBitsetHandles` without allocating new off-heap memory). Calling `ctx.releaseBitset(handle)` clears the bitset and returns its handle to the free pool for subsequent hops. * **L1-Aligned VM Register Frame**: `ctx.allocateStateSegment()` allocates the fixed 640-byte `VmStateLayout.VM_STATE_LAYOUT` register file (`R0`..`R63`) directly inside the `Arena`. ```java try (Arena queryArena = Arena.ofConfined(); VmQueryContext ctx = new VmQueryContext(snapshot, queryArena)) { // Enforce a strict per-query off-heap scratch ceiling (e.g., 64 MB) ctx.setMaxScratchCapacityBytes(64L * 1024 * 1024); // Acquire and recycle off-heap frontier bitsets across traversal steps int frontierHandle = ctx.acquireBitset(); ImpulseBitSet frontier = ctx.getBitset(frontierHandle); // ... ctx.releaseBitset(frontierHandle); } ``` ### 2.2 Native C-ABI Deterministic Scratch Buffer (`impulse_stmt_buffer_size`) In the C-ABI runtime (`impulse_vm.h`), prepared statements compute their exact scratch and output buffer requirement at `prepare` time based on the active snapshot's domain cardinalities: ```c // Query exact buffer requirement for the current snapshot generation size_t required_bytes = impulse_stmt_buffer_size(stmt); void* scratch_buf = aligned_alloc(128, required_bytes); // Execute with zero internal heap allocations impulse_status_t status = impulse_stmt_execute(stmt, scratch_buf, required_bytes); ``` When a larger `.imps` snapshot is swapped in, worker threads simply re-query `impulse_stmt_buffer_size(stmt)` (or create a fresh `VmQueryContext` bound to the new snapshot) and grow their thread-local scratch buffer if `required_bytes` exceeds the previously allocated size. ================================================================================ FILE: docs/deployment/concurrency.md | URL: https://www.impulsegraph.org/deployment/concurrency/ ================================================================================ # Concurrency Model The Impulse Graph Engine is designed for extreme concurrency, aiming to support thousands of simultaneous query threads with sub-microsecond latency. The core philosophy is **Zero Shared Mutable State on the Hot Path**. ## Lock-Free Reads via Mmap All query traversals operate over `ImpulseGraphSnapshot` (`GraphSnapshot` in Java 25, `impulse_snapshot_t` in C-ABI). A snapshot handle is a lightweight descriptor containing slices/pointers into memory-mapped (`mmap`) regions representing the Compressed Sparse Row (CSR) and Structure-of-Arrays (SoA) segments of the `.imps` file. Because the underlying `.imps` file on disk is immutable, these memory regions are completely read-only. - **No Read/Write Locks**: There are no locks acquired during traversal. - **Page Cache Driven**: The operating system's page cache handles parallel I/O and memory management transparently. - **Hardware Threading**: Scales perfectly linearly with the number of CPU cores. ## Atomic Snapshot Reference Swaps (`SnapshotSwapManager`) In a dynamic service environment, new data arrives continuously. Rather than locking the graph to update the base structure, an out-of-band builder writes a new `.imps` file. When the new file is ready, an atomic pointer swap (`SnapshotSwapManager` utilizing `AtomicReference` in Java, or `std::atomic` in C++) redirects new queries to the new memory map while reference-counting and draining in-flight queries on the previous snapshot: ```java SnapshotSwapManager swapManager = new SnapshotSwapManager<>(initialSnapshot); // Atomically swap active snapshot and asynchronously drain/close the old generation swapManager.swap(newSnapshot); ``` Queries that started before the swap continue reading from the old mapped memory. Once their `holder.release()` count reaches zero, the old `Arena` is closed and unmapped. ## Zero-Allocation Hot Path To prevent Java Garbage Collection (GC) pauses from ruining predictable latency, the engine enforces a strict zero-allocation rule during query execution. - No objects are allocated per-step. - Node arrays and bitsets are updated in place. ## Allocation Budget & `VmQueryContext` / Caller Buffer Every concurrent query requires temporary scratch space (e.g., off-heap bitsets for intermediate unions or intersections). To satisfy the zero-allocation rule, this scratch space is pre-allocated in an off-heap `Arena` (`VmQueryContext` in Java 25, or the caller-provided buffer in C-ABI `impulse_stmt_execute`): === "Java 25" ```java // Pre-compiled MethodHandle pipeline MethodHandle compiled = ImpulseMethodHandleCompiler.compile(prog, instructionCount); // Worker or Virtual Thread reuses an off-heap Arena / VmQueryContext try (Arena workerArena = Arena.ofConfined()) { ImpulseBitSet result = (ImpulseBitSet) compiled.invokeExact(graph, (Object) seedNodeId, workerArena); } ``` === "C-ABI (`impulse_stmt_t`)" ```c // Allocated once per worker thread based on deterministic prepare-time size size_t buf_len = impulse_stmt_buffer_size(stmt); void* thread_buf = malloc(buf_len); // Hot request loop: zero internal mallocs impulse_stmt_bind_node(stmt, "$seed", seed_id); impulse_stmt_execute(stmt, thread_buf, buf_len); ``` ================================================================================ FILE: docs/deployment/memory-tuning.md | URL: https://www.impulsegraph.org/deployment/memory-tuning/ ================================================================================ # Memory & Performance Tuning Guide — Impulse Graph Engine (Java) This guide covers FFM `Arena` lifecycle management, JVM heap sizing, Transparent Huge Pages, primitive integer width selection, and Vector API tuning for **`impulse-graph-java`** on Java 21 LTS and Java 22+/25. --- ## 1. FFM Off-Heap Architecture & Storage Structures (`impulse-storage`) Impulse Graph stores graph topology and attributes completely off-heap via FFM `MemorySegment` buffers bound to a `java.lang.foreign.Arena`. The engine operates directly over memory-mapped `.imps` files without deserializing data into Java heap objects. ### 1.1 Off-Heap Segment Hierarchy When a snapshot is loaded via `BinarySnapshotLoader.loadSnapshot(...)`: 1. **Memory Mapping**: The `.imps` file is mapped via `FileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size, arena)`, producing an off-heap `MemorySegment`. 2. **Kernel Prefetching (`MADV_WILLNEED`)**: `BinarySnapshotLoader` immediately invokes `segment.load()`. At the OS level, this issues an `madvise(..., MADV_WILLNEED)` call, prefetching pages into the OS page cache asynchronously to eliminate soft page fault stalls during cold start. 3. **Relation Slices**: The root segment is sliced into sub-segments encapsulated inside `RelationSnapshot`: * `rowOffsetsSegment`: CSR row offsets array (`(N + 1) * edgeIndexWidth` bytes). * `columnTargetsSegment`: CSR target node IDs (`E * nodeIdWidth` bytes). * `cscRowOffsetsSegment` & `cscColumnTargetsSegment`: Optional CSC reverse transpose index buffers. * `attributeSegments`: Structure-of-Arrays (SoA) contiguous primitive and vector arrays. * `validitySegments`: Aligned bitmasks for nullable attributes. 4. **Container**: `GraphSnapshot` aggregates all domain relation snapshots and string catalog metadata. --- ## 2. FFM Arena Lifecycle Management (`java.lang.foreign.Arena`) FFM arenas govern off-heap memory lifetimes. Choosing the proper arena determines thread-safety and memory unmapping behavior: ### 2.1 `Arena.ofShared()` vs. `Arena.ofConfined()` | Arena Type | Thread Concurrency Model | Engine Usage | Lifecycle & Deallocation | | :--- | :--- | :--- | :--- | | **`Arena.ofShared()`** | Multi-Threaded | Active Graph Snapshots & SWMR Query Engines | Safe for concurrent worker and virtual carrier threads. Memory is unmapped when `close()` or `drainAndClose()` is explicitly called. | | **`Arena.ofConfined()`** | Single-Threaded | Snapshot Builders & Scratch Computations | Strictly confined to allocating thread. Automatically unmaps memory upon `try-with-resources` block exit. Used internally by `SnapshotBuilder`. | ### 2.2 Production SWMR Snapshot Swapping & Safe Draining In high-throughput 24/7 environments, incoming CDC streams or scheduled updates generate new `.imps` snapshots. To avoid JVM segmentation faults from unmapping off-heap memory while query threads are reading: 1. **Active Query Accounting**: `GraphSnapshot` maintains an off-heap reader count via `LongAdder`: * `enterQuery()`: Increments active query count. * `exitQuery()`: Decrements active query count. * `awaitDrained(timeout, unit)`: Non-blocking spin-wait until active reader count drops to 0. * `drainAndClose(timeout, unit)`: Waits for readers to complete, then unmaps the arena. 2. **Atomic Pointer Swapping**: Use `SnapshotSwapManager` for atomic A/B pointer swaps: ```java // Initialize swap manager with active snapshot SnapshotSwapManager swapManager = new SnapshotSwapManager<>(initialSnapshot); // Query Path (Multi-Threaded Readers) var holder = swapManager.acquireCurrent(); if (holder != null) { try { GraphSnapshot snap = holder.getResource(); // Execute vector queries... } finally { holder.release(); // Decrements epoch reader count } } // Ingestion / Refresh Path (Atomic Pointer Swap) // Note: The new Arena must NOT be closed in a try-with-resources block here. // SnapshotSwapManager takes ownership of the arena/snapshot reference and // asynchronously closes it once all active queries on the prior generation have drained. Arena newArena = Arena.ofShared(); var newLoaded = BinarySnapshotLoader.loadSnapshot(Path.of("graph_v2.imps"), newArena); GraphSnapshot newSnapshot = newLoaded.graph(); // Atomically swap current pointer. Spawns a virtual thread that awaits // until the old epoch activeReaders reaches 0, then cleanly calls close(). swapManager.swap(newSnapshot); ``` --- ## 3. Alignment & Page Layout All CSR/CSC arrays, SoA attribute columns, and nullable validity bitmaps are padded to **128-byte boundaries** for SIMD vector loads and GPU transfers, and payload sections sit on 4KB OS page boundaries. See the [Binary Snapshot Format Specification](../reference/spec/format-specification.md) for exact byte offsets and validity bitmap padding formulas. --- ## 4. Recommended JVM Tuning Flags Because graph topology and attributes reside completely off-heap in memory-mapped files, JVM heap sizing and configuration differ fundamentally from traditional graph database engines. ### 4.1 Production JVM Command Line ```bash java --enable-preview \ --add-modules jdk.incubator.vector \ --enable-native-access=ALL-UNNAMED \ -XX:+UnlockDiagnosticVMOptions \ -XX:UseAVX=3 \ # x86-64 only; omit on ARM64 / Apple Silicon -XX:+UseLargePages \ -XX:LargePageSizeInBytes=2m \ -XX:+UseZGC \ -XX:+ZGenerational \ -Xms2g -Xmx4g \ -jar your-application.jar ``` ### 4.2 Flag Rationale & Analysis | JVM Argument | Purpose & Architectural Impact | | :--- | :--- | | **`--enable-preview`** | Enables preview features (FFM on Java 21 LTS baseline). Mandatory for preview compilation. | | **`--add-modules jdk.incubator.vector`** | Binds the SIMD Vector API module for AVX-512, AVX2, and ARM Neon vector instruction synthesis. | | **`--enable-native-access=ALL-UNNAMED`** | Grants zero-overhead off-heap native memory segment access and unmapping permissions. | | **`-XX:UseAVX=3`** | Enables AVX-512 instruction generation on Intel/AMD x86-64 processors (omit on ARM64 / Apple Silicon / AWS Graviton). Sets `PREFERRED_VECTOR_BIT_WIDTH = 512`. | | **`-XX:+UseLargePages`**
**`-XX:LargePageSizeInBytes=2m`** | Configures 2MB huge pages for JVM metadata and code cache, reducing TLB miss latency. | | **`-XX:+UseZGC -XX:+ZGenerational`** | Low-latency generational garbage collection with sub-millisecond pauses for carrier and query threads. | | **`-Xms2g -Xmx4g`** | **Lean Heap Sizing**: Keep the JVM heap small (2–4 GB) so remaining physical RAM stays free for the OS page cache backing `.imps` files. | !!! note "Off-Heap Memory, `-XX:MaxDirectMemorySize`, and Kubernetes `cgroups v2`" `FileChannel.map` creates memory-mapped segments backed directly by the operating system page cache. Memory-mapped I/O is governed by OS virtual memory limits (`vm.max_map_count`) and available physical RAM, and is **not** bounded or constrained by the JVM's `-XX:MaxDirectMemorySize` flag. Note that inside Kubernetes containers, Linux `cgroups v2` accounts resident file-backed page cache toward pod `memory.max` (`resources.limits.memory`); see **[Day-2 Kubernetes, Hot-Swap Lifecycle & Schema Evolution](../ecosystems/java/kubernetes-and-lifecycle.md)** for container sizing formulas. ### 4.3 Engine Optimization Thresholds (`OptimizerConfig`) The following Java system properties tune compiler heuristic thresholds: ```bash # Minimum node degree required to activate 512-bit SIMD Vector API fused edge attribute filters -Dimpulse.optimizer.simd.min_degree=64 # Multiplicity threshold for fusing 2-hop traversals directly in CPU registers (OP_CSR_WALK_2HOP) -Dimpulse.optimizer.2hop.max_multiplicity=1.5 # Master toggle for experimental compiler optimization passes -Dimpulse.optimizer.experimental=false # Intra-query OpenMP-style degree of parallelism (default: Available CPU cores) export IMPULSE_MAX_DOP=16 ``` --- ## 5. OS & Linux Kernel Memory Tuning For high-concurrency production deployments hosting multi-gigabyte or terabyte snapshots: ### 5.1 Virtual Memory Mapping Limits (`vm.max_map_count`) By default, Linux limits a process to 65,530 memory mappings. Large multi-domain graphs with many relations and tablespace partitions will fail with `java.io.IOException: Map failed` if this limit is reached. ```bash # Persist in /etc/sysctl.conf sudo sysctl -w vm.max_map_count=1048576 ``` ### 5.2 Transparent Huge Pages (THP) for Snapshot Mappings Traversing sparse graphs (e.g. billion-edge BFS or PageRank) involves random edge offset lookups. Under standard 4KB pages, a 100GB graph requires over 26 million TLB entries, resulting in severe TLB cache thrashing. With 2MB huge pages, the TLB footprint drops 512x to ~51,200 entries: ```bash # Enable madvise-based transparent hugepages echo madvise | sudo tee /sys/kernel/mm/transparent_hugepage/enabled echo advise | sudo tee /sys/kernel/mm/transparent_hugepage/shmem_enabled ``` ### 5.3 Page Cache & Swappiness Because `.imps` files are opened in read-only mode, pages in the OS page cache are clean. Under memory pressure, the Linux kernel can drop clean pages instantly without writing them to disk swap: ```bash # Minimize kernel swapping aggressiveness sudo sysctl -w vm.swappiness=10 ``` --- ## 6. Primitive Node ID Width Selection (`uint16_t`, `uint32_t`, `uint64_t`) In Impulse Graph, each Node Domain possesses an independent 0-indexed dense integer space ($0 \dots N_d-1$). Setting the domain ID width based on cardinality maximizes CPU cache density and memory bus utilization: ``` 64-Byte CPU Cache Line Packing Density Comparison ───────────────────────────────────────────────────────────────────────── • 16-bit (uint16_t): [ID0][ID1][ID2] ... [ID31] (32 Node IDs / 64B Line) • 32-bit (uint32_t): [ ID0 ][ ID1 ] ... [ ID15 ] (16 Node IDs / 64B Line) • 64-bit (uint64_t): [ ID0 ] ... [ ID7 ] (8 Node IDs / 64B Line) ───────────────────────────────────────────────────────────────────────── ``` ### 6.1 Width Selection Matrix | Width | Primitive | Max Domain Capacity | L1 Cache Density (64B) | Vector Tile (512-bit) | Memory (1B Edges) | | :--- | :--- | :--- | :--- | :--- | :--- | | **`2` Bytes** | `uint16_t` | 65,536 nodes | **32 IDs** / line | **32 IDs** / tile | **2.0 GB** | | **`4` Bytes** | `uint32_t` | 4,294,967,296 nodes | **16 IDs** / line | **16 IDs** / tile | **4.0 GB** | | **`8` Bytes** | `uint64_t` | >4.29 Billion nodes | **8 IDs** / line | **8 IDs** / tile | **8.0 GB** | To configure domain width during snapshot compilation with `SnapshotBuilder`: ```java SnapshotBuilder.create() .addDomain("User", DomainDefinition.builder(65_000L) .idWidth(PrimitiveWidth.UINT16) // Configured with uint16 target width .build()); ``` --- ## 7. Zero Garbage Collection (GC) Guarantee & Verification Because traversal frontiers propagate through pre-allocated `MemorySegment` buffers and `OffHeapBitSet` instances using `LongVector.SPECIES_PREFERRED`, the core engine query loop produces **zero heap allocations per traversal step**. ### 7.1 Microbenchmark & GC Verification !!! note Modern JVMs (Java 9+) replace the legacy `-XX:+PrintGCDetails` option with unified JVM logging (`-Xlog:gc*`). To verify zero-GC execution in continuous integration or microbenchmarks: ```bash mvn test -pl impulse-vm -Dtest=BlueGreenDrainAndUnloadTest \ -DargLine="--enable-preview --add-modules jdk.incubator.vector --enable-native-access=ALL-UNNAMED -Xlog:gc*" ``` ### 7.2 Zero-Allocation Enforcement with Epsilon GC For deterministic latency and allocation profiling, run microbenchmarks with the no-op Epsilon GC. Any accidental heap allocation during traversal will cause immediate JVM termination: ```bash java --enable-preview \ --add-modules jdk.incubator.vector \ --enable-native-access=ALL-UNNAMED \ -XX:+UnlockExperimentalVMOptions \ -XX:+UseEpsilonGC \ -Xms1g -Xmx1g \ -jar your-benchmark.jar ``` ================================================================================ FILE: docs/reference/packages.md | URL: https://www.impulsegraph.org/reference/packages/ ================================================================================ # Packages & Distribution Impulse Graph `v0.10.0` is published on **Maven Central**, **PyPI**, **crates.io**, and **GitHub Releases**. | Ecosystem | Registry | Package / Coordinate | Status | Description | | :--- | :--- | :--- | :--- | :--- | | **Java 21/25 (JVM Core)** | Maven Central | `org.impulsegraph:impulse-spec`, `impulse-api`, `impulse-storage`, `impulse-vm`, `impulse-compiler`, `impulse-builder` | Live (`0.10.0`) | Pure Java FFM snapshot engine, VM/JIT, compiler suite, and streaming builder (see [Java & JVM Hub](../ecosystems/java/index.md)). | | **Java Developer & Build Tooling** | Maven Central | `org.impulsegraph:impulse-bom`, `impulse-codegen`, `impulse-cli` (`impulse-j`), `impulse-maven-plugin` | Staged (`v0.11`) | Maven/Gradle BOM, v2 AOT schema codegen, pure-Java `impulse-j` CLI, and 7-Mojo Maven build/compatibility suite (see [Java & JVM Hub](../ecosystems/java/index.md)). | | **Kotlin / Scala 3 / Clojure** | Maven Central | `org.impulsegraph:impulse-kotlin`, `impulse-scala_3`, `impulse-clojure` | Live (`0.10.0`) | Idiomatic JVM language DSL extensions (see [JVM Languages](../ecosystems/java/jvm-languages.md)). | | **Python / PyTorch** | PyPI | `impulse-graph` | Live (`0.10.0`) | Pre-built `pybind11` wheels (Linux, macOS arm64, Windows) with NumPy & PyTorch interop. | | **Rust** | crates.io | `impulse-graph` | Live (`0.10.0`) | Self-contained Rust crate (bundled C++20/Highway sources, optional `IMPULSE_SDK_DIR` override). | | **CLI & C/C++20 SDK** | GitHub Releases | `impulse-cli`, `impulse-sdk` | Live (`v0.10.0`) | Pre-built CLI binaries, C-ABI headers (`impulse_graph.h`, `impulse_vm.h`), and static/shared libs. | | **Go (CGo)** | Go Modules | `github.com/impulse-graph/impulse-graph/go` | Active | CGo bindings linked against `libimpulse_graph_static.a`. | | **.NET 8+ (C# / F#)** | NuGet.org | `ImpulseGraph`, `ImpulseGraph.Native` | Staged (`v1.0`) | Managed .NET P/Invoke API and native binaries. | | **Node.js / Bun** | npm | `impulse-graph` | Staged (`v1.0`) | TypeScript definitions and N-API native bindings. | | **Containers** | GHCR | `ghcr.io/impulse-graph/impulse-tools`, `impulse-platform-server` | In Progress | CLI and platform server container images. | --- ## Static Linking & Build Attestations Native CLI binaries (`impulse-cli`), Python wheels, and Node.js N-API add-ons statically embed `libimpulse_graph_static.a` / `.lib` and are built in GitHub Actions CI with SLSA Level 3 build provenance attestations (`actions/attest-build-provenance`): * **Linux (`.deb` / `.rpm` / `tar.gz`)**: Standard packages target `glibc >= 2.28`; container tarballs target static `musl-libc`. * **macOS (`.pkg` / Homebrew)**: Embeds the static kernel, links system `libc++.dylib` and `libSystem.B.dylib` (macOS 11.0+), and is signed and notarized via Apple Developer ID. * **Windows (`.msi` / `.zip`)**: Built with MSVC `/MT` and signed with Authenticode (`signtool.exe`), requiring no Visual C++ Redistributable installer. ================================================================================ FILE: docs/reference/cli.md | URL: https://www.impulsegraph.org/reference/cli/ ================================================================================ # CLI Reference (`impulse` / `impulse-graph`) Official reference for the `impulse` (`impulse-graph`) command-line utility and compiler suite (`impulse-graph-core/impulse-cli`). The CLI is implemented in Rust and statically links the core C++ engine kernel (`libimpulse_graph_static.a`). !!! tip "Operational Guide & Pure-JVM CLI (`impulse-j`)" * For practical guidance on `--rcm` / `--vamana-locality` optimization, `--quick-check` vs. `--deep-audit` validation, and Ed25519 signing, see **[Native CLI Optimization, Deep Audits & Supply-Chain Signing](../ecosystems/native/cli-reference.md)**. * Running in a JVM-only container without native binaries? Use the **[Pure-Java CLI (`impulse-j`)](../ecosystems/java/cli-impulse-j.md)**. !!! important **Command Naming Convention**: - **`impulse build`** (`impulse snapshot build`) **ONLY builds `.imps` data snapshots** from CSV/Parquet/TSV manifests. - **`impulse compile`** (`impulse compiler compile`) **ONLY compiles query code** (`.impscm`, `.impk`, `.implog`, `.cypher`) into `.impas` assembly or `.impb` bytecode. --- ## 1. Command Hierarchy ```text impulse-graph (symlinked as `impulse`) ├── impulse run # Execute a query or .impb bytecode against an .imps snapshot ├── impulse build # Shorthand for `impulse snapshot build` ├── impulse bench-vector # Shorthand for `impulse snapshot bench-vector` (Vamana ANN harness) ├── impulse compile # Shorthand for `impulse compiler compile` ├── impulse inspect # Shorthand for `impulse snapshot inspect` ├── impulse assemble # Shorthand for `impulse compiler assemble` ├── impulse disassemble # Shorthand for `impulse compiler disassemble` ├── impulse generate # Shorthand for `impulse snapshot generate` ├── impulse stats # Shorthand for `impulse snapshot stats` │ ├── impulse snapshot # Binary Snapshot (.imps) Data Lifecycle │ ├── build # Stream-compile Parquet/CSV/TSV manifest (+ embeddings/Vamana) -> .imps │ ├── attach-embeddings # Attach external embedding files & Vamana ANN indices to an .imps file │ ├── bench-vector # Empirical Vamana ANN indexing & two-stage quantized search benchmark │ ├── inspect # Print header, domain/relation catalog, and section offsets │ ├── validate # Verify 128B alignment, CRC-16, SHA-256, --quick-check, & --deep-audit │ ├── stats # Compute degree distributions, multiplicity, and CBO sketches │ ├── optimize # Offline RCM / Vamana-BFS node reordering, degree sort, and CSC generation │ ├── diff # Compare structural diffs between two .imps snapshots │ ├── export # Export .imps relations to CSV/TSV/JSONL │ ├── convert-tensors # Ingest HuggingFace .safetensors weights (+ Vamana ANN) into .imps │ └── generate # Synthesize synthetic graphs (graph500, social, grid, etc.) │ ├── impulse compiler # Query Compiler & Bytecode Toolchain │ ├── compile (or build) # Compile DSL (.impscm/.impk/.implog/.cypher) -> .impas or .impb │ ├── assemble # Assemble .impas text -> .impb binary bytecode │ ├── disassemble # Disassemble .impb binary bytecode -> annotated .impas │ └── inspect # Disassemble and inspect .impb bytecode instructions │ └── impulse crypto # Ed25519 Cryptographic Attestation ├── keygen # Generate Ed25519 keypair (.priv / .pub) ├── sign # Sign an .imps snapshot footer with Ed25519 private key └── verify # Verify Ed25519 signature and SHA-256 digest of an .imps file ``` --- ## 2. Snapshot Data Commands (`impulse snapshot`) ### `impulse snapshot build` (or `impulse build`) Compiles CSV, TSV, or Apache Parquet files into a 4KB-page-aligned, 128-byte-section-aligned `.imps` snapshot using a declarative `manifest.json` (see [Snapshots from Parquet & CSV](../ecosystems/python/snapshots-from-parquet-csv.md)). Optionally attaches external embedding matrices (`--embeddings `) and builds embedded Section 2.6 Vamana ANN indices (`--vector-index `, `IMP_INDEX_VAMANA_ANN = 0x08`, `v0.10.0`): ```bash # Standard build from manifest.json impulse snapshot build --manifest manifest.json -o production.imps # Build with external embeddings and a two-stage SQ8 quantized Vamana ANN index # --embeddings : Domain.attr=path[:format=npy|fvecs|bvecs|ivecs|safetensors|parquet|jsonl|csv|tsv][:dim=D][:norm=l2] # --vector-index : Domain.attr[:R=32][:L=64][:alpha=1.2][:metric=cosine|l2|dot][:quant=sq8|fp16|bq1|none] impulse build --manifest manifest.json -o production.imps \ --embeddings "Paper.embedding=embeddings.npy:format=npy:dim=768:norm=l2" \ --vector-index "Paper.embedding:R=32:L=64:alpha=1.2:metric=cosine:quant=sq8" ``` ### `impulse snapshot inspect`, `validate` & `stats` Inspects domain/relation catalogs, verifies strict spec compliance and checksum integrity, or calculates structural graph statistics: ```bash # Print human-readable or JSON catalog summary impulse snapshot inspect production.imps --format json # Verify 128-byte section alignment, CRC-16 header, and SHA-256 payload digest impulse snapshot validate production.imps --strict-alignment # Fast structural header, alignment, and CSR monotonicity check (SQLite PRAGMA quick_check equivalent) impulse snapshot validate production.imps --quick-check # Deep O(V + E + N*R) cross-index, CSC transpose multiset, and Vamana ANN graph audit impulse snapshot validate production.imps --deep-audit # Compute degree percentiles, multiplicity, and supernodes (Z-score threshold, default 3.0) impulse snapshot stats production.imps --supernode-threshold 3.0 ``` ### `impulse snapshot optimize` Applies offline layout transformations—such as **Reverse Cuthill-McKee (RCM)** bandwidth reduction (`--rcm`), **Vamana Medoid BFS Locality** reordering (`--vamana-locality` for beam-search cache locality), degree sorting (`--degree-sort`), reverse **CSC** generation (`--csc`), or attaching/rebuilding Vamana ANN indices (`--embeddings`, `--vector-index`, `--rebuild-vector-index`): ```bash # Reorder dense IDs with Reverse Cuthill-McKee (RCM) and generate CSC reverse indices impulse snapshot optimize -i raw.imps -o optimized.imps --rcm --csc # Reorder domain nodes by BFS traversal order from the Vamana medoid (or attach/rebuild Vamana index) impulse snapshot optimize -i raw.imps -o vamana_opt.imps --vamana-locality \ --embeddings "Paper.embedding=vecs.fvecs:dim=128:norm=l2" \ --vector-index "Paper.embedding:R=32:L=64:alpha=1.2:metric=cosine:quant=sq8" \ --rebuild-vector-index ``` ### `impulse snapshot diff`, `export`, `convert-tensors`, `attach-embeddings`, `bench-vector` & `generate` ```bash # Compare domain/edge count deltas between two snapshots impulse snapshot diff v1.imps v2.imps # Export snapshot edge lists back to CSV, TSV, or JSONL (--format csv|tsv|jsonl) impulse snapshot export production.imps --out-dir ./exported_csv/ --format csv # Ingest HuggingFace .safetensors weights into an .imps snapshot domain (with optional Vamana index) impulse snapshot convert-tensors -i model.safetensors -o weights.imps --domain ModelWeightNode \ --vector-index "R=32:L=64:metric=cosine:quant=sq8" # Attach external embeddings (.npy, .fvecs, .safetensors, .parquet, .jsonl, .csv) & Vamana index to an existing .imps impulse snapshot attach-embeddings -i base.imps -o with_vecs.imps \ --embeddings "Doc.embedding=doc_vecs.npy:dim=384:norm=l2" \ --vector-index "Doc.embedding:R=32:L=64:alpha=1.2:metric=cosine:quant=sq8" # Run empirical Vamana ANN indexing & two-stage quantized search benchmark (NONE, FP16, SQ8, BQ1) impulse bench-vector -n 10000 -d 128 -c 24 -q 200 -k 10 \ --max-degree 24 --ef-construction 64 --alpha 1.2 --metric cosine \ --ef-search 16,32,64 --compare-optimize --format text # Or benchmark an existing snapshot / external embedding file: impulse snapshot bench-vector --snapshot with_vecs.imps --embeddings doc_vecs.npy -q 100 -k 10 --format json # Generate a synthetic Graph500 (R-MAT) snapshot (scale 14 = 16,384 nodes, edge factor 16) impulse generate --profile graph500 --scale 14 --edge-factor 16 -o synthetic.imps ``` !!! note **Note on `impulse snapshot merge`**: While the CLI taxonomy reserves an `impulse snapshot merge` subcommand stub (`--base --deltas ... -o `), production updates in Impulse Graph are performed by streaming fresh `.imps` snapshots from updated tables via `impulse build` (or Java `SnapshotBuilder`) and executing an atomic Blue/Green pointer swap (see [Changing Data & Live Updates](../getting-started/handling-mutations.md)). --- ## 3. Query Execution & Compiler Commands (`impulse run` & `impulse compiler`) ```bash # 1. Compile openCypher, ImpLog, ImpK, or ImpScheme to annotated .impas assembly impulse compile query.impscm -o query.impas # 2. Assemble .impas text into binary .impb bytecode (-i / --input required) impulse assemble -i query.impas -o query.impb # 3. Disassemble or inspect binary .impb bytecode impulse disassemble -i query.impb impulse compiler inspect query.impb # 4. Execute compiled bytecode or assembly against a snapshot impulse run --snapshot production.imps --bytecode query.impb --input-val 42 # 5. Execute with static bytecode verification, SQLite-style NEVER_CORRUPT assertions, # differential optimized-vs-unoptimized checking, and branch coverage telemetry impulse run --snapshot production.imps --bytecode query.impb \ --verify --never-corrupt --diff-opt --branch-cov ``` --- ## 4. Cryptographic Signing (`impulse crypto`) ```bash # Generate Ed25519 keypair, sign snapshot, and verify signature before mmap impulse crypto keygen -o release_key impulse crypto sign production.imps -k release_key.priv impulse crypto verify production.imps -k release_key.pub ``` ================================================================================ FILE: docs/reference/java-api.md | URL: https://www.impulsegraph.org/reference/java-api/ ================================================================================ # Java 25 SDK Reference (`impulse-graph-java`) !!! tip "Looking for Enterprise JVM Guides, AOT Codegen, Maven Plugin, or Kubernetes Lifecycle?" Visit the **[Java & JVM Enterprise Hub](../ecosystems/java/index.md)** for full walkthroughs on `impulse-bom` & JDK 21/25 flags, **[Building Snapshots in Java](../ecosystems/java/building-snapshots.md)**, **[Schema-First AOT Code Generation](../ecosystems/java/aot-codegen.md)**, **[Maven Plugin (7 Mojos)](../ecosystems/java/maven-and-build-tooling.md)**, **[Pure-Java CLI (`impulse-j`)](../ecosystems/java/cli-impulse-j.md)**, **[Kubernetes & Hot-Swap Lifecycle](../ecosystems/java/kubernetes-and-lifecycle.md)**, and **[Kotlin, Scala 3 & Clojure](../ecosystems/java/jvm-languages.md)**. The **Pure Java 21 LTS / 25+ Engine** (`impulse-graph-java`) is a standalone, zero-dependency implementation of the Impulse Graph Engine and `ImpulseVM`. It uses the Java Foreign Function & Memory (FFM) API (`MemorySegment`, `Arena`) to mount `.imps` binary snapshots directly off-heap, combined with the Vector API (`jdk.incubator.vector`) and `MethodHandle` C2 JIT combinators. Because graph traversals over 128-byte-aligned CSR/CSC arrays are primarily **memory-bandwidth and cache-line bound**, `impulse-graph-java` executes within **`1.5x–2.0x` of the Native C++20 kernel** (specifically **`1.65x`** on 1.47B-edge `twitter-2010` BFS: `240.29 ms` Java vs. `145.00 ms` C++) with a **JFR-verified zero-allocation hot path** (`0.00 ms` GC pauses). In enterprise microservice benchmarks simulating multi-hop ReBAC authorization queries against a realistic directory corpus of 600,000 users, JFR profiling shows that Jackson JSON serialization of the query response (`1.91 µs – 2.56 µs`) consumes **`3.5x to 73x` more CPU time** than the Impulse Graph query itself (`0.026 µs – 0.552 µs`)—making Pure Java 25 wholly suitable for demanding enterprise workloads without JNI wrappers or inherited CVEs. See **[Benchmarks](../benchmarks.md)** for full details. !!! info "Interactive Aggregated Javadocs" Browse the full multi-module HTML Javadoc site at [**`/javadoc/index.html`**](/javadoc/index.html). | Javadoc Package | Module | Description | | :--- | :--- | :--- | | [**`org.impulsegraph.api`**](/javadoc/org/impulsegraph/api/package-summary.html) | `impulse-api` | `ImpulseGraphSnapshot`, `RelationSnapshot`, `ImpulseGraphQuery`, `IdMapper` | | [**`org.impulsegraph.api.schema`**](/javadoc/org/impulsegraph/api/schema/package-summary.html) · [**`lifecycle`**](/javadoc/org/impulsegraph/api/lifecycle/package-summary.html) | `impulse-api` | `GraphManifest`, `SchemaYamlCodec`, `SchemaValidator`, `SnapshotResolver`, `ConsumerSchemaContext`, `SwapResult` *(v0.11)* | | [**`org.impulsegraph.api.traversal`**](/javadoc/org/impulsegraph/api/traversal/package-summary.html) | `impulse-api` | Kleisli frontier pipeline (`DomainView`, `Traversal`, `Reducer`) | | [**`org.impulsegraph.api.statement`**](/javadoc/org/impulsegraph/api/statement/package-summary.html) | `impulse-api` | SQLite-style prepared statements (`ImpulseStatement`, `RowReader`) | | [**`org.impulsegraph.api.bitset`**](/javadoc/org/impulsegraph/api/bitset/package-summary.html) | `impulse-api` | Zero-copy off-heap bitsets (`ImpulseBitSet`, `OffHeapBitSet`) | | [**`org.impulsegraph.compiler.ast`**](/javadoc/org/impulsegraph/compiler/ast/package-summary.html) | `impulse-api` | AST node representations and lexical bindings | | [**`org.impulsegraph.storage.csr`**](/javadoc/org/impulsegraph/storage/csr/package-summary.html) · [**`schema`**](/javadoc/org/impulsegraph/storage/schema/package-summary.html) | `impulse-storage` | `BinarySnapshotLoader`, `GraphSnapshot`, `SnapshotSwapManager`, `ImpulseHealthIndicator`, `SnapshotContractValidator`, `SnapshotSchemaExtractor` | | [**`org.impulsegraph.vm`**](/javadoc/org/impulsegraph/vm/package-summary.html) · [**`lifecycle`**](/javadoc/org/impulsegraph/vm/lifecycle/package-summary.html) | `impulse-vm` | `ImpulseVmInterpreter`, `ImpulseVmValidator`, `ImpulseMethodHandleCompiler`, `CompiledQuery`, `VmQueryContext`, `VmLaneFrontier`, `SnapshotLifecycleManager` | | [**`cypher`**](/javadoc/org/impulsegraph/compiler/cypher/package-summary.html) · [**`cel`**](/javadoc/org/impulsegraph/compiler/cel/package-summary.html) · [**`passes`**](/javadoc/org/impulsegraph/compiler/passes/package-summary.html) · [**`emitter`**](/javadoc/org/impulsegraph/compiler/emitter/package-summary.html) | `impulse-compiler` | Multi-pass `ImpScheme` / `openCypher` / `CEL` compiler, Stage 1 & Stage 2 passes, and bytecode emitter | | [**`org.impulsegraph.builder.api`**](/javadoc/org/impulsegraph/builder/api/package-summary.html) | `impulse-builder` | Streaming `SnapshotBuilder`, `DomainDefinition`, `RelationDefinition` | | [**`org.impulsegraph.spec.v0_9`**](/javadoc/org/impulsegraph/spec/v0_9/package-summary.html) | `impulse-spec` | Binary Snapshot Format FFM memory layouts and protocol constants | --- ## 1. Maven & Gradle Coordinates (`org.impulsegraph`) !!! note "Maven Central (`0.10.0`)" `org.impulsegraph:*:0.10.0` is published on Maven Central (`impulse.version = 0.10.0`). For local snapshot builds from source, run `mvn clean install -DskipTests` in `impulse-graph-java`. === "Maven (`pom.xml`)" ```xml org.impulsegraph impulse-api ${impulse.version} org.impulsegraph impulse-storage ${impulse.version} org.impulsegraph impulse-vm ${impulse.version} org.impulsegraph impulse-compiler ${impulse.version} ``` === "Gradle (`build.gradle.kts`)" ```kotlin dependencies { implementation("org.impulsegraph:impulse-api:$impulseVersion") implementation("org.impulsegraph:impulse-storage:$impulseVersion") implementation("org.impulsegraph:impulse-vm:$impulseVersion") implementation("org.impulsegraph:impulse-compiler:$impulseVersion") } ``` --- ## 2. Snapshot Loading & Domain-Bound Traversals ### 2.1 `BinarySnapshotLoader` & `ImpulseGraphSnapshot` Mounts an immutable `.imps` file directly off-heap inside a `java.lang.foreign.Arena`: ```java import java.lang.foreign.Arena; import java.nio.file.Path; import org.impulsegraph.api.ImpulseGraphSnapshot; import org.impulsegraph.storage.csr.BinarySnapshotLoader; try (Arena arena = Arena.ofShared()) { ImpulseGraphSnapshot snap = BinarySnapshotLoader.loadSnapshot(Path.of("social.imps"), arena).getGraph(); System.out.printf("Domains: %s, Relations: %d, Off-Heap Bytes: %d%n", snap.getDomainNames(), snap.getRelationCount(), snap.getOffHeapMemorySizeBytes()); } ``` ### 2.2 `DomainView` & `Traversal` Every traversal anchors to an explicit domain (`snap.domain("User")`), establishing the 0-indexed dense ID space $0 \dots N_d-1$: ```java DomainView users = snap.domain("User"); // 1. Seed from business key, walk edge, and filter with CEL List friendKeys = users.fromKey("usr_alice") .out("FOLLOWS") .filter("node.age >= 21 && node.active == true") .toKeyList(); // 2. Unbounded fixed-point reachability (transitive closure) Set reachableGroups = users.from(42L) .out("MEMBER_OF") .repeatUntilStable("PARENT_GROUP") .toSet(); // 3. Monoidic state projection and reduction ImpulseBitSet highSpendProducts = users.from(1L, 2L, 3L) .outWithState("PURCHASED", "state.total_spend:SUM = edge.amount") .project("state.spend_with_tax = state.total_spend * 1.08") .filter("state.spend_with_tax >= 100.0") .toBitSet(); ``` See [State Projections, Reducers & Loops](../query-api/advanced-querying.md) for the full list of monoidic `:MIN`, `:MAX`, `:SUM`, `:AVG`, `:ARGMIN`, and `:ARGMAX` reducers. | Interface | Core Methods | | :--- | :--- | | **`DomainView`** | `all()`, `from(long...)`, `from(ImpulseBitSet)`, `fromKey(String)`, `fromKeys(String...)`, `first(int)`, `fromRandom(int)`, `toDenseId(String)`, `toKey(long)` | | **`Traversal`** | `.filter(cel)`, `.project(cel)`, `.withParam(k, v)`, `.out(rel)`, `.out(rel, cel)`, `.out(rel, Reducer)`, `.outWithState(rel, stateExpr)`, `.in(rel)`, `.repeatUntilStable(rel)`, `.repeatUntilStable(rel, cel)`, `.repeat(n, rel)`, `.toBitSet()`, `.toList()`, `.toSet()`, `.toKeyList()`, `.toKeySet()`, `.count()`, `.toImpAsm()` | --- ## 3. Prepared Statements (`ImpulseStatement` & `RowReader`) `snap.prepare(String query)` compiles an `openCypher`, `ImpScheme`, or `CEL` query once into a reusable `ImpulseStatement`: ```java try (ImpulseStatement stmt = snap.prepare( "MATCH (u:User)-[:PURCHASED]->(p:Product) " + "WHERE u._key = $userKey AND p.price <= $maxPrice " + "RETURN p")) { stmt.bindString("userKey", "usr_alice") .bindDouble("maxPrice", 99.95); try (RowReader rows = stmt.execute()) { while (rows.next()) { long productDenseId = rows.getNodeId(0); } } } ``` --- ## 4. Multi-Lane Bit-Sliced Execution & Pool Management (`org.impulsegraph.vm`) (v0.10.0) In `v0.10.0`, `org.impulsegraph.vm` implements the **Multi-Lane Bit-Sliced Execution (`0xC0..0xC9`)** and **Hybrid Vector ANN (`0xCA..0xCB`)** ISA extensions with zero hot-path heap allocations via thread-local `VmQueryContext` buffer pools. ### 4.1 `VmLaneFrontier` & `LaneWidth` (`TYPE_LANE_FRONTIER = 0x10`) `VmLaneFrontier` represents a pooled vertical bit-sliced frontier where each node $u \in [0, N_d)$ holds up to 64 parallel lane bits alongside optional per-relation counterfactual edge trip masks: * **`VmLaneFrontier.LaneWidth`**: Hardware width tiers **`WIDTH_8(8)`**, **`WIDTH_16(16)`**, **`WIDTH_32(32)`**, and **`WIDTH_64(64)`**. * **`VmLaneFrontier.selectLaneWidth(int k)`**: Selects the narrowest tier capable of holding `k` active lanes (`WIDTH_8` for $k \le 8$, `WIDTH_16` for $k \le 16$, `WIDTH_32` for $k \le 32$, `WIDTH_64` for $k > 32$). * **`VmLaneFrontier.NORMATIVE_BOUNDARY_SEED_COUNTS`**: The 17 normative boundary lane counts `{0, 1, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127, 128, 129}` used across polyglot verification suites to guard width transitions and 32/64-bit shift boundaries. * **Counterfactual Edge Trip Masks**: `ensureEdgeTripMask(VmQueryContext ctx, int relId, int minEdges)` (or `setEdgeTripMask`), `getEdgeTripMask(int relId)`, `getEdgeTripMaskLength(int relId)`, and `copyEdgeTripMasksFrom(VmQueryContext ctx, VmLaneFrontier src)` manage per-edge bitmasks (`tripArr[e] |= (1L << laneB)`) for simultaneous $N-1$/$N-2$ outage screening (`OP_LANE_SET_EDGE_MASK` `0xC2`). ### 4.2 `VmQueryContext` Pooling & `VmMultiLaneHandlers` `VmQueryContext` pools `VmLaneFrontier` instances via thread-local arenas (`TL_BUFFER_POOL`) so multi-lane steps execute with zero GC pressure: ```java try (VmQueryContext ctx = VmQueryContext.acquire(snap, arena)) { int k = 16; VmLaneFrontier.LaneWidth width = VmLaneFrontier.selectLaneWidth(k); // WIDTH_16 long activeMask = VmRegisterType.VmRegType.makeActiveMaskU64(k); // 0xFFFFL int handle = ctx.acquireLaneFrontier(width, k, activeMask, nodeCount); VmLaneFrontier frontier = ctx.getLaneFrontier(handle); // Execute 0xC0..0xCB instructions via VmMultiLaneHandlers.handleMultiLaneOpcode(state, ctx, instr, pc) } ``` | Class / Method | Purpose | | :--- | :--- | | **`VmQueryContext.acquireLaneFrontier(width, numLanes, activeMask, nodeCount)`** | Acquires and resets a pooled `VmLaneFrontier` from the thread-local buffer pool and returns its integer handle. | | **`VmQueryContext.getLaneFrontier(int handle)`** | Resolves a `TYPE_LANE_FRONTIER` (`0x10`) register handle to its `VmLaneFrontier` instance. | | **`VmMultiLaneHandlers.requireLaneFrontier(state, ctx, regIndex)`** | Exhaustive switch-checked extractor that validates `T_LANE_FRONTIER` (`0x10`) in `R[regIndex]` or traps with `IMPULSE_VM_ERR_INVALID_REGISTER`. | | **`VmMultiLaneHandlers.handleMultiLaneOpcode(state, ctx, instr, pc)`** | Executes opcodes `0xC0` (`OP_LANE_INIT_SEEDS`) through `0xCB` (`OP_VECTOR_RERANK_DOT`) with 100% bitwise parity against C++20 and the OCaml oracle. | --- ## 5. Streaming Snapshot Builder & Blue/Green Swaps ### 5.1 `SnapshotBuilder` (`org.impulsegraph:impulse-builder`) Streams page-aligned, 128-byte-aligned `.imps` snapshots direct-to-disk in $O(\text{chunk})$ memory (see [Building Snapshots in Java](../ecosystems/java/building-snapshots.md)): ```java SnapshotBuilder.create() .withStagingDirectory(Path.of("/tmp/staging")) .addDomain("User", DomainDefinition.builder(100_000L).idWidth(PrimitiveWidth.UINT32).build()) .addRelation("KNOWS", RelationDefinition.builder("User", "User") .addTopology(Topology.CSR, CompressionScheme.RAW) .dataSource(edgeDataSource).build()) .writeTo(Path.of("graph.imps")); ``` ### 5.2 `SnapshotSwapManager` (`org.impulsegraph:impulse-storage`) Epoch-tracked atomic A/B pointer swap manager for rotating live `.imps` snapshots without blocking active reader threads: ```java SnapshotSwapManager swapManager = new SnapshotSwapManager<>(initialGraph); // Reader thread: zero-lock epoch acquisition var holder = swapManager.acquireCurrent(); if (holder != null) { try { GraphSnapshot current = holder.getResource(); // Execute lock-free traversal... } finally { holder.release(); } } // Background updater thread: atomic pointer swap swapManager.swap(newGraphSnapshot); ``` --- ## 6. JVM Languages (Kotlin, Scala 3 & Clojure) & Build Plugins Because `impulse-api` uses standard Java interfaces without checked exceptions or runtime lambdas, it is directly usable from **Kotlin** (`org.impulsegraph:impulse-kotlin`), **Scala 3** (`org.impulsegraph:impulse-scala_3`), and **Clojure** (`org.impulsegraph:impulse-clojure`). See **[Kotlin, Scala 3, Clojure & Java API](../ecosystems/java/jvm-languages.md)** for full language examples. ### Maven Schema Code Generation (`impulse-codegen` & `impulse-maven-plugin`) To generate strongly-typed domain views, `Id` records, CEL metamodels, and zero-allocation `RowView` cursors from a declarative [`.imps.schema.yaml`](spec/schema-specification.md) file during your build (see **[Schema-First AOT Codegen](../ecosystems/java/aot-codegen.md)** and **[Maven Plugin & Build-Time AOT Pipeline](../ecosystems/java/maven-and-build-tooling.md)** for all 7 `v0.11` Mojos): ```xml org.impulsegraph impulse-maven-plugin ${impulse.version} generate ${project.basedir}/src/main/resources/schema.yaml ${project.build.directory}/generated-sources/impulse com.example.graph.generated ``` ================================================================================ FILE: docs/reference/python-api.md | URL: https://www.impulsegraph.org/reference/python-api/ ================================================================================ # Python & PyTorch SDK Reference (`impulse-graph`) The `impulse-graph` Python SDK embeds the C++20 `ImpulseVM` kernel via `pybind11` and exposes `.imps` snapshots directly to NumPy (`np.frombuffer`) and PyTorch (`torch.from_numpy`, `torch.sparse_csr_tensor`). !!! tip "Python Guides & Workflows" For multi-process PyTorch `DataLoader` patterns, Parquet/CSV ingestion, and Vamana ANN vector search, visit the **[Python, Data Science & ML Hub](../ecosystems/python/index.md)** and **[PyTorch GNN Sampling, Embeddings & Vamana Vector Search](../ecosystems/python/gnn-and-vector-search.md)**. --- ## 1. Installation ```bash pip install impulse-graph # Or build from a local clone: pip install ./impulse-graph-core/impulse-python ``` Pre-built wheels (`manylinux` `x86_64`/`aarch64`, `macosx_11_0_arm64`, `win_amd64`) statically embed `libimpulse_graph_static.a`. --- ## 2. Opening Snapshots & Fluent Traversals ```python from impulse_graph import Snapshot with Snapshot("commerce.imps") as snap: print("Domains:", snap.domain_count(), "Relations:", snap.relation_count()) # 1. Fluent multi-hop traversal (User 0 -> PURCHASED -> <-PURCHASED -> PURCHASED) recommended_items = ( snap.traverse(start_node=0, catalog={"PURCHASED": 0}) .out("PURCHASED") .in_("PURCHASED") .out("PURCHASED") .to_list() ) # 2. Declarative openCypher query execution buyers = snap.cypher( "MATCH (u:User)-[:PURCHASED]->(p:Product) WHERE u.id = $uid RETURN p", params={"uid": 0}, catalog={"PURCHASED": 0}, ) ``` ### `Snapshot` Methods | Method | Description | | :--- | :--- | | **`Snapshot(path: str)`** | Memory-map `.imps` file read-only (`MAP_SHARED`). Supports `with` context manager. | | **`domain(name_or_id: str \| int) -> DomainView`** | Bind an explicit node domain (`from_key`, `from_keys`, `from_node`, `from_nodes`, `all`, `to_dense_id`, `to_key`). | | **`domain_count() -> int`** | Total node domains in Section 2 catalog. | | **`relation_count() -> int`** | Total edge relations in Section 2 directory. | | **`get_relation(index: int) -> dict`** | Relation metadata dictionary (`node_count`, `edge_count`, `src_domain_id`, `tgt_domain_id`). | | **`is_reachable(rel_idx: int, src_id: int, tgt_id: int) -> bool`** | Direct $O(\log d)$ / $O(1)$ CSR adjacency check. | | **`traverse(start_node: int, catalog=None) -> Traversal`** | Start a fluent multi-hop traversal from `start_node` (`.out(rel)`, `.in_(rel)`, `.filter(...)`, `.to_list()`, `.to_set()`, `.count()`, `.contains(id)`, `.to_impas()`). | | **`cypher(query: str, params=None, catalog=None) -> List[int]`** | Compile and execute a read-only `openCypher` query, returning surviving target node IDs. | | **`get_row_offsets_array(rel_idx: int) -> np.ndarray`** | NumPy view (`uint32`) over CSR `row_offsets`. | | **`get_col_indices_array(rel_idx: int) -> np.ndarray`** | NumPy view (`uint32`) over CSR `col_indices`. | | **`get_attribute_array(rel_idx: int, attr_idx: int, dtype=np.float32, shape=None) -> np.ndarray`** | NumPy view over a relation SoA attribute column. | | **`sample_neighbors(relation_index: int, nodes, k_samples: int, seed: int = 42)`** | Native SIMD neighborhood sampler returning `(sampled_src, sampled_tgt)` NumPy arrays. | | **`to_torch_csr(rel_idx: int)` / `to_torch_edge_index(rel_idx: int)`** | Export relation directly to PyTorch `sparse_csr_tensor` or `[2, E]` `edge_index` tensor. | | **`to_scipy_csr(rel_idx: int)` / `to_networkx(rel_idx: int)`** | Export relation to `scipy.sparse.csr_matrix` or `networkx.DiGraph`. | | **`to_arrow_table(rel_idx: int)` / `to_polars(rel_idx: int)` / `to_pandas(rel_idx: int)`** | Export relation edge list to PyArrow Table, Polars DataFrame, or Pandas DataFrame. | --- ## 3. Zero-Copy PyTorch & NumPy Integration Because `.imps` aligns all CSR topology arrays and Structure-of-Arrays (SoA) attribute columns to **128-byte boundaries**, PyTorch and NumPy read them directly from the OS page cache with **0 bytes of heap serialization**: ```python import numpy as np import torch from impulse_graph import Snapshot with Snapshot("ogbn_papers100M.imps") as snap: # 1. Zero-copy float32 relation attribute column via NumPy buffer protocol edge_count = snap.get_relation(0)["edge_count"] attr_np = snap.get_attribute_array(0, 0, dtype=np.float32, shape=(edge_count,)) edge_weights = torch.from_numpy(attr_np) # 2. Zero-copy CSR topology tensors csr_tensor = snap.to_torch_csr(0) # 3. Native SIMD neighborhood sampling for GNN mini-batches seed_nodes = np.array([10, 42, 105, 891], dtype=np.uint64) sampled_src, sampled_tgt = snap.sample_neighbors( relation_index=0, nodes=seed_nodes, k_samples=15, seed=42 ) ``` --- ## 4. Low-Level VM Bytecode Builder (`impulse_graph.vm`) For custom register-level `impOps` pipelines (such as `repeat_until_stable`, set intersections, or GraphBLAS `matrix_vector_mul`), use `impulse_graph.vm.QueryBuilder`: ```python from impulse_graph import Snapshot, vm with Snapshot("commerce.imps") as snap: with vm.VmContext(snap) as ctx: state = vm.VmState() qb = vm.QueryBuilder() query = ( qb.input_node(0) .walk_edge(0) .repeat_until_stable(lambda b: b.walk_edge(0)) .collect_bitset() .compile() ) res = query.execute_with_context(ctx, state, input_param=0) ``` --- ## 5. Streaming Snapshot Writer (`Writer`) For programmatic `.imps` construction in Python (see also `impulse build` in [Snapshots from Parquet & CSV](../ecosystems/python/snapshots-from-parquet-csv.md)): ```python import numpy as np from impulse_graph import Writer with Writer("graph.imps") as writer: writer.add_domain(domain_id=0, key_type=4, name="User") writer.add_relation( src_domain_id=0, tgt_domain_id=0, encoding_type=0, node_count=4, edge_count=4, section_features=0, row_offsets=np.array([0, 2, 3, 3, 4], dtype=np.uint32), col_indices=np.array([1, 2, 3, 0], dtype=np.uint32), ) writer.finalize() ``` ================================================================================ FILE: docs/reference/c-abi.md | URL: https://www.impulsegraph.org/reference/c-abi/ ================================================================================ # C-ABI & C++20 Reference (`impulse-cpp`) The **Impulse Graph Engine C-ABI Kernel** (`impulse-graph-core/impulse-cpp/include/`) provides the zero-dependency native foundation for C, C++20, Python (`pybind11`), Rust (`ffi`), Go (`CGo`), .NET (`P/Invoke`), and Node.js (`N-API`). !!! info "Generated Doxygen Reference" For header-level symbol documentation, open the [**Generated Doxygen HTML Reference (`/doxygen/index.html`)**](/doxygen/index.html). --- ## 1. Header Map & Linkage | Header File | Scope | | :--- | :--- | | **`impulse_format_v0_9.h`** | Packed 1-byte-aligned C-ABI POD structures (`#pragma pack(push, 1)`), feature flags, and enumeration constants for the [Binary Snapshot Format (`.imps`)](spec/format-specification.md). | | **`impulse_graph.h`** | Snapshot `mmap` loader, domain/relation catalog inspection, direct CSR/CSC/SoA attribute buffer pointers, key catalog resolution, streaming snapshot writer, and SIMD neighbor sampling. | | **`impulse_vm.h`** | 64-bit bytecode instruction layout (`impulse_instruction_t`), 640-byte execution state frame (`impulse_vm_state_t`), `TYPE_LANE_FRONTIER` (`0x10`) context accessors, in-kernel multi-language compiler, and SQLite-style prepared statements (`impulse_stmt_t`). | | **`impulse_index.h`** | Secondary index construction and lookup functions (`0x01` Permutation, `0x02` 2-Tier Zone Map, `0x03` Inverted Bitset, `0x04` Minimal Perfect Hash, `0x05` Trigram, `0x06` Domain-Split Bitset, `0x07` Temporal Interval, and `0x08` Vamana ANN in `v0.10.0`). | | **`impulse_simd.h`** | Dynamic SIMD target dispatch (`AVX-512`, `AVX2`, `ARM-NEON`, `WASM-SIMD128`) for float32 vector operations and sorted `uint32_t` array intersections. | | **`impulse_vm_fluent.hpp`** | C++20 fluent bytecode builder (`impulse::vm::QueryBuilder`, `CompiledQuery`, `QueryResult`) and domain-bound traversal DSL (`SnapshotView`, `DomainView`, `Traversal`, `MultiLaneBuilder`, `MultiLaneTraversal`, `MultiLaneResult`). | --- ## 2. Snapshot Lifecycle & Zero-Copy Buffer Accessors (`impulse_graph.h`) ```c /* 1. Open and memory-map (.imps) file */ IMPULSE_API impulse_snapshot_t* impulse_snapshot_open( const char* file_path, impulse_status_t* out_status ); IMPULSE_API void impulse_snapshot_close(impulse_snapshot_t* snapshot); /* 2. Catalog inspection */ IMPULSE_API uint16_t impulse_snapshot_domain_count(const impulse_snapshot_t* snapshot); IMPULSE_API uint16_t impulse_snapshot_relation_count(const impulse_snapshot_t* snapshot); /* 3. Direct zero-copy CSR & CSC buffer pointers (128-byte aligned) */ IMPULSE_API impulse_status_t impulse_snapshot_get_relation_buffers( const impulse_snapshot_t* snapshot, uint16_t relation_index, const uint32_t** out_offsets, const uint32_t** out_targets, uint64_t* out_node_count, uint64_t* out_edge_count ); IMPULSE_API impulse_status_t impulse_snapshot_get_relation_csc_buffers( const impulse_snapshot_t* snapshot, uint16_t relation_index, const uint32_t** out_csc_offsets, const uint32_t** out_csc_targets, uint64_t* out_csc_row_count, uint64_t* out_csc_edge_count ); /* 4. Direct zero-copy SoA attribute column pointers (128-byte aligned) */ IMPULSE_API impulse_status_t impulse_snapshot_get_attribute_buffers( const impulse_snapshot_t* snapshot, uint16_t relation_index, uint16_t attribute_index, const void** out_data, uint64_t* out_data_bytes, const void** out_offsets, uint64_t* out_offsets_bytes, uint8_t* out_type_code, uint32_t* out_dimension ); /* 5. Bi-directional Key Catalog resolution & SIMD neighbor sampling */ IMPULSE_API impulse_status_t impulse_snapshot_resolve_key( const impulse_snapshot_t* snapshot, uint16_t domain_id, const void* key_bytes, size_t key_len, uint32_t* out_node_id ); IMPULSE_API impulse_status_t impulse_snapshot_resolve_dense_id( const impulse_snapshot_t* snapshot, uint16_t domain_id, uint32_t node_id, const void** out_key_bytes, size_t* out_key_len ); IMPULSE_API bool impulse_snapshot_is_reachable( const impulse_snapshot_t* snapshot, uint16_t relation_index, uint64_t src_id, uint64_t tgt_id ); IMPULSE_API impulse_status_t impulse_snapshot_sample_neighbors( const impulse_snapshot_t* snapshot, uint16_t relation_index, const uint64_t* src_nodes, size_t num_nodes, int k_samples, uint64_t seed, uint64_t* out_src, uint64_t* out_tgt, size_t out_capacity, size_t* out_count ); ``` --- ## 3. Prepared Statements & Caller-Provided Buffer C-ABI (`impulse_vm.h`) Compiles any supported query dialect (`openCypher`, `ImpScheme`, `ImpLog`, `ImpK`, `CEL`) once and executes it inside a **Caller-Provided Memory Buffer** (`impulse_stmt_buffer_size`) with zero internal `malloc` calls: ```c typedef struct impulse_stmt impulse_stmt_t; /* 1. Prepare & Exact Buffer Sizing */ IMPULSE_API impulse_status_t impulse_stmt_prepare( const impulse_snapshot_t* snapshot, const char* query_text, impulse_stmt_t** out_stmt ); IMPULSE_API size_t impulse_stmt_buffer_size(const impulse_stmt_t* stmt); IMPULSE_API void impulse_stmt_finalize(impulse_stmt_t* stmt); /* 2. Parameter Bindings */ IMPULSE_API impulse_status_t impulse_stmt_bind_node(impulse_stmt_t* stmt, const char* param, uint64_t node_id); IMPULSE_API impulse_status_t impulse_stmt_bind_nodes(impulse_stmt_t* stmt, const char* param, const uint64_t* node_ids, size_t count); IMPULSE_API impulse_status_t impulse_stmt_bind_bitset(impulse_stmt_t* stmt, const char* param, const uint64_t* words, size_t word_count); IMPULSE_API impulse_status_t impulse_stmt_bind_roaring(impulse_stmt_t* stmt, const char* param, const uint8_t* bytes, size_t len); IMPULSE_API impulse_status_t impulse_stmt_bind_int(impulse_stmt_t* stmt, const char* param, int64_t val); IMPULSE_API impulse_status_t impulse_stmt_bind_uint(impulse_stmt_t* stmt, const char* param, uint64_t val); IMPULSE_API impulse_status_t impulse_stmt_bind_float(impulse_stmt_t* stmt, const char* param, double val); IMPULSE_API impulse_status_t impulse_stmt_bind_str(impulse_stmt_t* stmt, const char* param, const char* str); IMPULSE_API impulse_status_t impulse_stmt_bind_uuid(impulse_stmt_t* stmt, const char* param, const uint8_t uuid_bytes[16]); IMPULSE_API impulse_status_t impulse_stmt_bind_vector(impulse_stmt_t* stmt, const char* param, const float* data, size_t dim); /* 3. Execute in Caller-Provided Buffer & Read Contiguous Arrow-Aligned Columns */ IMPULSE_API impulse_status_t impulse_stmt_execute(impulse_stmt_t* stmt, void* buffer, size_t buffer_size); IMPULSE_API size_t impulse_stmt_row_count(const impulse_stmt_t* stmt); IMPULSE_API uint32_t impulse_stmt_column_count(const impulse_stmt_t* stmt); IMPULSE_API const void* impulse_stmt_column_data(const impulse_stmt_t* stmt, uint32_t col_idx); IMPULSE_API bool impulse_stmt_column_is_null(const impulse_stmt_t* stmt, uint32_t col_idx, size_t row_idx); ``` --- ## 4. Single-Pass Streaming Snapshot Writer (`impulse_writer_t`) Writes `.imps` files directly to local disk or unseekable cloud streams (`impulse_write_fn` callback for S3/GCS multipart uploads) in $O(\text{chunk})$ RAM: ```c IMPULSE_API impulse_writer_t* impulse_writer_create(const char* output_file_path, uint64_t global_features); IMPULSE_API impulse_writer_t* impulse_writer_create_stream(impulse_write_fn write_cb, void* user_data, uint64_t global_features); IMPULSE_API impulse_status_t impulse_writer_add_domain(impulse_writer_t* writer, uint16_t domain_id, uint8_t key_type, const char* name); IMPULSE_API impulse_status_t impulse_writer_add_relation( impulse_writer_t* writer, uint16_t src_domain_id, uint16_t tgt_domain_id, uint8_t encoding_id, uint64_t node_count, uint64_t edge_count, uint64_t section_features, const void* row_offsets_data, uint64_t row_offsets_bytes, const void* col_indices_data, uint64_t col_indices_bytes ); IMPULSE_API impulse_status_t impulse_writer_add_attribute( impulse_writer_t* writer, uint16_t relation_index, const char* name, uint8_t type_code, uint32_t dimension, const void* data, uint64_t data_bytes, const void* offsets, uint64_t offsets_bytes ); IMPULSE_API impulse_status_t impulse_writer_finalize(impulse_writer_t* writer); IMPULSE_API void impulse_writer_destroy(impulse_writer_t* writer); ``` --- ## 5. C++20 Fluent Bytecode Builder (`impulse_vm_fluent.hpp`) Provides type-safe C++20 classes (`impulse::vm::QueryBuilder`, `impulse::vm::CompiledQuery`, `impulse::vm::QueryResult`) with automatic register allocation for constructing and executing `impOps` bytecode programs: ```cpp #include "impulse_graph.h" #include "impulse_vm_fluent.hpp" #include #include int main() { impulse_status_t status = IMPULSE_OK; impulse_snapshot_t* snap = impulse_snapshot_open("rbac.imps", &status); if (status != IMPULSE_OK || !snap) return 1; // 1. Fluent C++20 bytecode builder with fixed-point transitive closure using namespace impulse::vm; CompiledQuery query = QueryBuilder() .inputNode(0) // R0 = seed user ID .walkEdge(/*MEMBER_OF=*/ 0) // Step to direct groups .repeatUntilStable([](QueryBuilder& b) { b.walkEdge(/*PARENT_GROUP=*/ 1); }) .collectBitset() .compile(); impulse_vm_context_t* ctx = nullptr; QueryResult res = query.execute(snap, /*input_param=*/ 42, &ctx); if (res.isOk()) { std::cout << "Group 7 reachable: " << res.testBitset(ctx, 7) << "\n"; } if (ctx) impulse_vm_context_destroy(ctx); // 2. Prepared statement with caller-allocated workspace buffer impulse_stmt_t* stmt = nullptr; impulse_stmt_prepare( snap, "MATCH (u:User)-[:PURCHASED]->(p:Product) WHERE u.id = $userId RETURN p", &stmt ); std::vector workspace(impulse_stmt_buffer_size(stmt)); impulse_stmt_bind_node(stmt, "$userId", 42); impulse_stmt_execute(stmt, workspace.data(), workspace.size()); const auto* bitset_words = static_cast(impulse_stmt_column_data(stmt, 0)); std::cout << "Result bitset words: " << impulse_stmt_row_count(stmt) << "\n"; impulse_stmt_finalize(stmt); impulse_snapshot_close(snap); return 0; } ``` ### 5.1 Multi-Lane Bit-Sliced & Hybrid Vector Fluent APIs (v0.10.0) In `v0.10.0`, `impulse_vm_fluent.hpp` and `impulse_vm.h` add support for **Multi-Lane Bit-Sliced Execution (`0xC0..0xC9`)** and **Hybrid Vamana ANN Search & SIMD Reranking (`0xCA..0xCB`)** at three levels: #### 1. Low-Level `impulse::vm::QueryBuilder` Bytecode Emitters (`0xC0..0xCB`) ```cpp // Multi-Lane Bit-Sliced Execution (0xC0..0xC9) & Hybrid Vector Search (0xCA..0xCB) QueryBuilder& laneInitSeeds(uint16_t seed_reg, uint8_t width_flag = 0); // 0xC0 OP_LANE_INIT_SEEDS QueryBuilder& laneInitGroups(uint16_t pairs_reg, uint16_t num_groups); // 0xC1 OP_LANE_INIT_GROUPS QueryBuilder& laneSetEdgeMask(uint16_t pairs_reg, uint16_t relation_id); // 0xC2 OP_LANE_SET_EDGE_MASK QueryBuilder& laneWalkCsr(uint16_t relation_id, bool fixed_point = false); // 0xC3 OP_LANE_CSR_WALK QueryBuilder& laneWalkCsc(uint16_t relation_id, bool fixed_point = false); // 0xC4 OP_LANE_CSC_WALK QueryBuilder& lanePruneMask(uint8_t mode, uint16_t arg0, uint16_t arg1 = 0); // 0xC5 OP_LANE_PRUNE_MASK QueryBuilder& laneFilterQuorum(uint16_t min_quorum, uint16_t mask_reg = 0xFF); // 0xC6 OP_LANE_FILTER_QUORUM QueryBuilder& laneReduceAnd(); // 0xC7 OP_LANE_REDUCE_AND QueryBuilder& laneReduceAttr(uint16_t attr_id, uint8_t reduce_op = 0); // 0xC8 OP_LANE_REDUCE_ATTR QueryBuilder& laneSetCover(uint16_t mask_reg = 0xFF, uint8_t mode = 0); // 0xC9 OP_LANE_SET_COVER QueryBuilder& vectorAnnSearch(uint16_t query_reg, uint16_t top_k, uint16_t index_or_attr_id = 0, bool fused_lane_frontier = false); // 0xCA OP_VECTOR_ANN_SEARCH QueryBuilder& vectorRerankDot(uint16_t query_reg, uint16_t attr_id = 0, uint8_t metric = 0); // 0xCB OP_VECTOR_RERANK_DOT ``` #### 2. High-Level Domain-Bound `SnapshotView`, `DomainView`, `MultiLaneBuilder` & `MultiLaneTraversal` `SnapshotView` wraps an `impulse_snapshot_t*` to provide domain-bound traversals (`snap_view.domain("Gene")`) across both single-lane `Traversal` (including `DomainView::vectorSearch` and `Traversal::rerank`) and multi-lane `MultiLaneBuilder`: | C++20 Class (`impulse::vm`) | Core Methods | | :--- | :--- | | **`SnapshotView`** | `domain(const std::string& domain_name)`, `domain(uint16_t domain_id)`, `raw()` | | **`DomainView`** | `all()`, `from(node_ids)`, `fromKey(key)`, `fromKeys(keys)`, `vectorSearch(index_or_attr, query_vector, top_k)`, `multiLane()` | | **`MultiLaneBuilder`** | `fromSeeds(node_ids)`, `fromKeys(keys)`, `fromGroups(concept_groups)`, `fromConceptVectors(index_or_attr, concept_vectors, hits_per_concept)`, `fromOutages(relation, tripped_edge_ids_per_lane)` | | **`MultiLaneTraversal`** | **Walks**: `out(rel)`, `out(rel, edge_cel)`, `in(rel)`, `in(rel, edge_cel)`, `repeat(n, rel)`, `repeatUntilStable(rel)`
**Filters & Pruning**: `filter(node_cel)`, `project(cel)`, `pruneWhere(deny_cel)`, `pruneDeniedBy(deny_rel)`, `pruneHubs(max_degree, min_quorum)`, `whereQuorum(min_lanes)`, `whereMask(required_any_mask, forbidden_mask)`, `mustHitAtLeast(min_lanes, subset_seed_keys)`, `mustAvoidAll(forbidden_seed_keys)`
**Terminal Collectors**: `collect()`, `toQuorumTraversal(min_lanes)`, `reducePerLane(node_attr, ReducerOp)`, `argMinNodesPerLane(node_attr)`, `argMaxNodesPerLane(node_attr)`, `argMinKeysPerLane(node_attr)`, `argMaxKeysPerLane(node_attr)`, `checkAllNodesReachedPerLane()`, `toSteinerSubgraph(min_concept_quorum)` | | **`MultiLaneResult`** | `laneCount()`, `domainNodeCount()`, `laneMaskFor(node_id)`, `lanePopcountFor(node_id)`, `attributionFor(node_id)`, `keyAttributionFor(node_key)`, `nodesWithQuorum(min_lanes)`, `keysWithQuorum(min_lanes)`, `findSetCoverPairs(target_mask)`, `findGreedySetCover(target_mask, max_nodes)` | ```cpp SnapshotView view(snap); // 10-gene oncology panel with safety exclusion and 2-drug cocktail cover MultiLaneResult res = view.domain("Gene").multiLane() .fromKeys({"BRCA1", "BRCA2", "EGFR", "MYC", "KRAS", "PIK3CA", "BRAF", "ERBB2", "KCNH2_SAFE", "SCN5A_SAFE"}) .out("INTERACTS_GiG") .in("BINDS_CbG") .mustHitAtLeast(5, {"BRCA1", "BRCA2", "EGFR", "MYC", "KRAS", "PIK3CA", "BRAF", "ERBB2"}) .mustAvoidAll({"KCNH2_SAFE", "SCN5A_SAFE"}) .collect(); auto quorum_drugs = res.keysWithQuorum(5); auto cocktail_pairs = res.findSetCoverPairs(0x00FFULL); ``` #### 3. C-ABI `impulse_vm_context_t` Lane Frontier Accessors (`impulse_vm.h`) For FFI bindings and custom native callers inspecting `TYPE_LANE_FRONTIER` (`0x10`) handles directly: ```c IMPULSE_API int impulse_vm_context_acquire_lane_frontier(impulse_vm_context_t* ctx); IMPULSE_API void impulse_vm_context_release_lane_frontier(impulse_vm_context_t* ctx, size_t handle); IMPULSE_API uint32_t impulse_vm_context_lane_frontier_num_lanes(const impulse_vm_context_t* ctx, size_t handle); IMPULSE_API uint32_t impulse_vm_context_lane_frontier_width(const impulse_vm_context_t* ctx, size_t handle); IMPULSE_API uint64_t impulse_vm_context_lane_frontier_active_mask(const impulse_vm_context_t* ctx, size_t handle); IMPULSE_API size_t impulse_vm_context_lane_frontier_node_count(const impulse_vm_context_t* ctx, size_t handle); IMPULSE_API const uint64_t* impulse_vm_context_lane_frontier_data(const impulse_vm_context_t* ctx, size_t handle); ``` --- ## 6. In-Kernel Multi-Language Compiler & Secondary Index Builder (`impulse_vm.h` & `impulse_index.h`) ### In-Kernel Multi-Frontend Compiler (`impulse_vm.h`) Compiles `ImpScheme` (`IMPULSE_LANG_IMPSCM = 0`), `ImpK` (`IMPULSE_LANG_IMPK = 1`), `ImpLog` (`IMPULSE_LANG_IMPLOG = 2`), `openCypher` (`IMPULSE_LANG_CYPHER = 3`), or `CEL` (`IMPULSE_LANG_CEL = 4`) strings directly into `impOps` bytecode or `.impas` assembly text: ```c typedef enum { IMPULSE_LANG_IMPSCM = 0, IMPULSE_LANG_IMPK = 1, IMPULSE_LANG_IMPLOG = 2, IMPULSE_LANG_CYPHER = 3, IMPULSE_LANG_CEL = 4 } impulse_language_t; IMPULSE_API impulse_status_t impulse_compile_query( const impulse_snapshot_t* snapshot, const char* script, impulse_language_t lang, impulse_instruction_t* out_instructions, size_t out_capacity, size_t* out_count ); IMPULSE_API impulse_status_t impulse_compile_to_impas( const impulse_snapshot_t* snapshot, const char* script, impulse_language_t lang, char* out_impas_buffer, size_t out_capacity, size_t* out_bytes_written ); IMPULSE_API impulse_vm_status_t impulse_compile_and_execute( const impulse_snapshot_t* snapshot, const char* script, impulse_language_t lang, impulse_vm_state_t* state, uint64_t input_seed ); ``` ### Secondary Index Construction & Attachment (`impulse_index.h` & `impulse_graph.h`) Builds secondary index blobs (`0x01` Permutation, `0x02` ZoneMap, `0x03` InvertedBitset, `0x04` MinimalPerfectHash, `0x05` Trigram, `0x06` DomainSplitBitset, `0x07` TemporalInterval) and embeds them into `.imps` Section 2.6: ```c /* Build secondary index payload in memory (impulse_index.h) */ IMPULSE_API impulse_status_t impulse_index_build_permutation( const void* attr_data, size_t element_count, uint8_t type_code, void** out_bytes, size_t* out_size ); IMPULSE_API impulse_status_t impulse_index_build_zone_map( const void* attr_data, size_t element_count, uint8_t type_code, void** out_bytes, size_t* out_size ); IMPULSE_API impulse_status_t impulse_index_build_minimal_perfect_hash( const char** keys, size_t count, void** out_bytes, size_t* out_size ); IMPULSE_API void impulse_index_free(void* ptr); /* Attach built index blob to SnapshotWriter (impulse_graph.h) */ IMPULSE_API impulse_status_t impulse_writer_add_index( impulse_writer_t* writer, uint16_t domain_id, uint16_t relation_id, uint16_t attribute_index, uint8_t index_type, const char* index_name, const void* index_data, uint64_t index_bytes, uint64_t payload_feature_mask ); ``` --- ## 7. Deterministic State Hashing & Formal Opcode Contracts (`impulse_vm.h` & `impulse_opcode_contracts.hpp`) ### 7.1 Deterministic Execution State Hash (`ICTX` v1) To verify bitwise consensus across C++ (`-O3`), C++ (`-O0`), Pure Java 25, Rust, and the OCaml reference oracle without floating-point drift or padding discrepancies, `impulse_vm.h` exposes state hashing functions implementing the **`ICTX` v1** protocol: ```c /** * @brief Computes a deterministic SHA-256 state hash of the VM execution frame and context. * * Serializes the ICTX v1 binary stream: * - 8-byte header: Magic "ICTX" (0x494D5053), uint16 version (1), uint16 reserved (0) * - State metadata: int32 status, uint32 pc, uint64 flags * - Call stack: uint32 depth, 8 x uint32 frame PCs (inactive frames zeroed) * - Architectural registers: 64 x (uint8 type, uint64 value LE) * - Handle dereferencing: canonical bitset node lists, normalized float vectors (NaN normalized * to 0x7FC00000, -0.0f to +0.0f), double vectors, multi-lane bit-sliced arrays, string vectors, * and value maps in register index order 0..63. * * @param state Pointer to VM execution state frame. * @param status VM execution status code. * @param hash_out 32-byte buffer receiving the binary SHA-256 digest. * @return 0 on success, negative error code on failure. */ IMPULSE_API int impulse_vm_state_hash( const impulse_vm_state_t* state, int32_t status, uint8_t hash_out[32] ); /** * @brief Computes a deterministic 64-character lowercase hex SHA-256 state digest. * * @param state Pointer to VM execution state frame. * @param status VM execution status code. * @param hex_out Buffer of at least 65 bytes receiving null-terminated hex string. * @return 0 on success, negative error code on failure. */ IMPULSE_API int impulse_vm_state_hash_hex( const impulse_vm_state_t* state, int32_t status, char hex_out[65] ); ``` ### 7.2 188 Formal Opcode Contracts (`impulse_opcode_contracts.hpp`) `impulse-cpp/include/impulse_opcode_contracts.hpp` declares `constexpr` execution contracts for **188 opcode variants** across all 166 ISA instructions (`0x00`..`0xCB`). Each contract enforces register operand layouts (`RegFieldLayout`), dynamic type validity masks, instruction modifier flags, and flag modifications: ```cpp #include "impulse_opcode_contracts.hpp" // Branchless 2-cycle dynamic type validation macro: IMPULSE_CHECK_REG_TYPE(vm_state, reg, allowed_mask); // Access compile-time contract table covering all 188 opcode variants: namespace impulse::vm { // Retrieve all 188 formal opcode contracts across opcodes 0x00..0xCB: std::vector get_all_opcode_contracts(); } ``` The formal contracts are verified via the 5-pass verification suite in `test_opcode_contracts.cpp` (rejection of disallowed register types, acceptance of valid types and output type conformity, out-of-bounds register safety, in-place register aliasing safety, and null snapshot safety). ================================================================================ FILE: docs/reference/rust-api.md | URL: https://www.impulsegraph.org/reference/rust-api/ ================================================================================ # Rust Crate Reference (`impulse-graph`) The `impulse-graph` crate (`impulse-graph-core/impulse-rust`) provides `.imps` snapshot reading, SoA slice accessors, fluent traversals, Vamana ANN search, and single-pass snapshot writing. --- ## 1. Installation (`Cargo.toml`) ```toml [dependencies] impulse-graph = "0.10" # Or local workspace path: # impulse-graph = { path = "../impulse-graph-core/impulse-rust" } ``` | Module | Exported Types & Functions | | :--- | :--- | | **`reader`** | `SnapshotReader` (`open`, `domain_count`, `relation_count`, `is_reachable`, `get_row_offsets`, `get_col_indices`, `get_neighbors`, `get_attribute_data`, `index_entries`, `parse_vamana_header`, `vamana_ann_search`) | | **`traversal`** | `Traversal`, `TraversalStep`, `StepDirection` | | **`writer`** | `SnapshotWriter` (`new`, `add_domain`, `add_relation`, `add_attribute_to_relation`, `add_attribute_to_domain`, `add_index`, `add_vamana_index`, `add_built_vamana_index`, `finalize`) | | **`vamana`** | `VamanaBuildConfig`, `BuiltVamanaIndex` (`VamanaArtifact`), `build_vamana_index`, `permute_vamana_index`, `compute_vamana_bfs_order`, `vamana_ann_search`, `brute_force_ann_search`, `evaluate_ann_quality` (`v0.10.0`) | | **`spec`** | `SnapshotHeader`, `KeyType`, `BaseDataType`, `EncodingType`, `ImpulseError`, `IMPULSE_MAGIC`, `IMP_INDEX_VAMANA_ANN` (`0x08`), `VamanaHeader`, `VamanaMetric`, `VamanaQuantType`, `VAMANA_MAGIC` | | **`simd`** | SIMD dot product, elementwise sum/scale/mul, and sorted `u32` slice intersection | | **`ffi`** | Raw `extern "C"` bindings to `impulse_graph.h` and `impulse_vm.h` | --- ## 2. Snapshot Reader (`SnapshotReader`) `SnapshotReader::open` maps an `.imps` file via `mmap`, validating the Page 0 header, CRC-16-CCITT checksum, and SHA-256 payload digest: ```rust use impulse_graph::reader::SnapshotReader; fn main() -> Result<(), Box> { let reader = SnapshotReader::open("social_graph.imps")?; println!("Domains: {}, Relations: {}", reader.domain_count(), reader.relation_count()); // Direct O(log d) adjacency check on relation 0 (0 -> 1) let connected: bool = reader.is_reachable(0, 0, 1); // Outgoing neighbor dense IDs (Vec) let neighbors: Vec = reader.get_neighbors(0, 0)?; // CSR row_offsets and col_indices slices (&[u32]) let row_offsets: &[u32] = reader.get_row_offsets(0)?; let col_indices: &[u32] = reader.get_col_indices(0)?; // SoA attribute byte slice (&[u8]) let attr_bytes: &[u8] = reader.get_attribute_data(0, 0)?; Ok(()) } ``` --- ## 3. Fluent Multi-Hop Traversal (`Traversal`) ```rust use impulse_graph::reader::SnapshotReader; fn main() -> Result<(), Box> { let reader = SnapshotReader::open("social_graph.imps")?; // Multi-hop fluent topology traversal let reachable_nodes: Vec = reader .traverse(0) .out("MEMBER_OF") .in_step("MANAGES") .out("HAS_PERMISSION") .to_vec()?; println!("Reachable Nodes: {:?}", reachable_nodes); Ok(()) } ``` *(Note: Rust `Traversal::to_vec()` currently executes high-performance topology walks. In-kernel CEL evaluation for `out_filtered` is scheduled for upcoming compiler integration).* --- ## 4. Single-Pass Streaming Writer (`SnapshotWriter`) Constructs 4KB-page-aligned and 128-byte-section-aligned `.imps` snapshots with automatic CRC-16 header and SHA-256 payload checksum computation: ```rust use impulse_graph::writer::SnapshotWriter; use impulse_graph::spec::KeyType; fn main() -> Result<(), Box> { let mut writer = SnapshotWriter::new("graph.imps"); writer.add_domain(0, KeyType::Int64, "User"); writer.add_relation( 0, 0, 4, 4, vec![0u32, 2, 3, 4, 4], vec![1u32, 2, 3, 0], ); writer.finalize()?; Ok(()) } ``` ### 4.1 Vamana ANN Graph Index Construction, Permutation & Two-Stage Search (`vamana` Module, `v0.10.0`) The zero-dependency `impulse_graph::vamana` module implements Section 2.6 **`IMP_INDEX_VAMANA_ANN` (`0x08`)** single-layer DiskANN/Vamana proximity graph construction, medoid-seeded BFS node permutation, and two-stage quantized beam search (`BQ1` / `SQ8` / `FP16` routing codes followed by exact `Float32` reranking): | Type / Function | Description | | :--- | :--- | | **`IMP_INDEX_VAMANA_ANN` (`0x08`)** | Section 2.6 secondary index type constant for 128-byte-aligned Vamana proximity graphs (`VAMANA_MAGIC = 0x56414D41`). | | **`VamanaBuildConfig`** | Build parameters (`max_degree_r`, `ef_construction`, `alpha`, `metric: VamanaMetric`, `quant_type: VamanaQuantType`, `seed`) and `VamanaBuildConfig::parse_params("r=32,l=100,alpha=1.2,metric=cosine,quant=sq8")`. | | **`BuiltVamanaIndex` (`VamanaArtifact`)** | Serialized Vamana index artifact containing the 64-byte `VamanaHeader`, 128-byte-aligned fixed-stride `adj_slab` (`N * (R + 1) * 4` bytes), and quantized `quant_slab`. | | **`build_vamana_index(...)`** | Constructs a two-pass $\alpha$-RNG pruned Vamana index ($\alpha = 1.0$ then $\alpha = \text{cfg.alpha}$) over `[node_count, dimension]` `f32` vectors. | | **`compute_vamana_bfs_order(hdr, adj_slab)`** | Computes a medoid-rooted BFS node ordering `(old_to_new, new_to_old)` so neighbors visited consecutively during beam search are co-located in memory. | | **`permute_vamana_index(...)`** | Relabels an existing Vamana index in $O(N \cdot R + N \cdot D)$ time under a node ID bijection `(old_to_new, new_to_old)` without rebuilding the graph. | | **`vamana_ann_search(...)`** | Executes greedy beam search using quantized routing codes (`BQ1`, `SQ8`, `FP16`) and reranks the `ef_search` beam survivors using exact `Float32` vectors. | | **`brute_force_ann_search(...)` & `evaluate_ann_quality(...)`** | Exact nearest-neighbor oracle and `(recall_at_1, recall_at_k, ndcg_at_k, mrr)` quality evaluator. | ```rust use impulse_graph::reader::SnapshotReader; use impulse_graph::spec::{BaseDataType, KeyType, VamanaMetric, VamanaQuantType, IMP_INDEX_VAMANA_ANN}; use impulse_graph::vamana::{brute_force_ann_search, evaluate_ann_quality, VamanaBuildConfig}; use impulse_graph::writer::SnapshotWriter; fn build_and_search_vamana(vectors: &[f32], n: usize, dim: usize) -> Result<(), Box> { let mut vec_bytes = Vec::with_capacity(vectors.len() * 4); for &f in vectors { vec_bytes.extend_from_slice(&f.to_le_bytes()); } let mut writer = SnapshotWriter::new("entities_vamana.imps"); writer.add_domain(0, KeyType::Int64, "Entity"); writer.set_domain_node_count(0, n as u64); writer.add_attribute_to_domain(0, "embedding", BaseDataType::Float32 as u8, dim as u32, vec_bytes, None); let cfg = VamanaBuildConfig::parse_params("r=32,l=100,alpha=1.2,metric=cosine,quant=sq8")?; writer.add_vamana_index(0, "embedding", "Entity_embedding_vamana", &cfg)?; writer.finalize()?; let reader = SnapshotReader::open("entities_vamana.imps")?; let entry = &reader.index_entries()[0]; assert_eq!(entry.index_type, IMP_INDEX_VAMANA_ANN); let query = &vectors[0..dim]; let approx = reader.vamana_ann_search(entry, query, /*top_k=*/ 10, /*ef_search=*/ 64)?; let exact = brute_force_ann_search(VamanaMetric::Cosine, vectors, n, dim, query, 10); let (_r1, recall_at_10, ndcg_at_10, _mrr) = evaluate_ann_quality(&approx, &exact, 10); println!("Recall@10: {:.3}, nDCG@10: {:.3}", recall_at_10, ndcg_at_10); Ok(()) } ``` ================================================================================ FILE: docs/reference/polyglot-sdks.md | URL: https://www.impulsegraph.org/reference/polyglot-sdks/ ================================================================================ # Go, .NET (C#) & Node.js SDKs In addition to Java 25, Python, C/C++20, and Rust, Impulse Graph provides official native bindings for **Go (CGo)**, **.NET 8+ (C# / F# P/Invoke)**, and **Node.js / Bun / TypeScript (N-API)**, all backed by the static C-ABI kernel (`libimpulse_graph_static.a`). --- ## 1. Go SDK (`impulse-go` via CGo) Links directly against `libimpulse_graph_static.a` (`CGO_ENABLED=1`), exposing zero-copy `.imps` loading, CSR slice views (`GetRelationBuffers`), fluent `Traversal` pipelines, `ImpulseVM` bytecode execution (`QueryBuilder` + `ExecuteVM`), and single-pass `.imps` writing. ```go package main import ( "fmt" "log" impulse "github.com/impulse-graph/impulse-graph/go" ) func main() { snap, err := impulse.OpenSnapshot("rbac.imps") if err != nil { log.Fatalf("open failed: %v", err) } defer snap.Close() // 1. Direct O(log d) reachability check & zero-copy CSR buffer slices connected := snap.IsReachable(0, 10, 42) offsets, targets, nodeCount, edgeCount, err := snap.GetRelationBuffers(0) if err != nil { log.Fatalf("buffer access failed: %v", err) } fmt.Printf("Edge (10 -> 42): %v (nodes=%d, edges=%d, offsets=%d, targets=%d)\n", connected, nodeCount, edgeCount, len(offsets), len(targets)) // 2. Fluent VM QueryBuilder & ExecuteVM ctx, err := impulse.NewVMContext(snap) if err != nil { log.Fatalf("vm context failed: %v", err) } defer ctx.Close() state := impulse.NewVMState() state.SetQueryContext(ctx) bytecode := impulse.NewQueryBuilder(). InputNode(0). WalkEdge(0, 1). // Relation 0: MEMBER_OF -> R1 WalkEdge(1, 2). // Relation 1: PARENT_GROUP -> R2 CollectBitset(2). Compile() if err := impulse.ExecuteVM(bytecode, state, 10); err != nil { log.Fatalf("VM execution failed: %v", err) } fmt.Printf("Result bitset handle in R2: %d\n", state.GetRegister(2)) } ``` --- ## 2. .NET 8+ / C# SDK (`ImpulseGraph` via P/Invoke) Provides deterministic `IDisposable` off-heap management (`Snapshot`, `VmContext`, `QueryBuilder`, `Query`, `ExecutionResult`) across Linux (`x64`/`arm64`), macOS (`arm64`), and Windows (`x64`). ```bash # Reference local project or build from source (NuGet package publication planned for v1.0): dotnet add reference path/to/impulse-graph-core/impulse-dotnet/ImpulseGraph.csproj ``` ```csharp using System; using ImpulseGraph; using ImpulseGraph.Vm; using var snap = new Snapshot("rbac.imps"); Console.WriteLine($"Domains: {snap.DomainCount}, Relations: {snap.RelationCount}"); // 1. Direct O(log d) reachability check & relation directory inspection bool reachable = snap.IsReachable(0, 10UL, 42UL); var relEntry = snap.GetRelationEntry(0); // 2. Fluent VM QueryBuilder & Snapshot.ExecuteQuery using var ctx = new VmContext(snap); Query query = new QueryBuilder() .InputNode(0) .WalkEdge(relationId: 0, dstReg: 1) // Relation 0: MEMBER_OF -> R1 .WalkEdge(relationId: 1, dstReg: 2) // Relation 1: PARENT_GROUP -> R2 .CollectBitset(reg: 2) .Compile(); ExecutionResult result = snap.ExecuteQuery(query, ctx, inputParam: 42UL); Console.WriteLine($"VM Status: {result.Status}, R2 Handle: {result.GetRegister(2)}"); ``` --- ## 3. Node.js, Bun & TypeScript SDK (`impulse-graph` via N-API) Built on N-API (`node-addon-api`) with zero external npm dependencies and full TypeScript declarations (`index.d.ts`). Exposes `Snapshot` (with fluent `.traverse(startNode)`), `VmContext` (with `Float32Array` / `Float64Array` / `BigUint64Array` vector views), `VmState`, `QueryBuilder`, `CompiledQuery`, and `Writer`. ```bash # Build native add-on from source (npm registry publication planned for v1.0): cd impulse-graph-core/impulse-node && npm install && npm run build ``` ```typescript import { Snapshot, VmContext, VmState, QueryBuilder } from 'impulse-graph'; const snap = new Snapshot('rbac.imps'); const ctx = new VmContext(snap); try { // 1. Direct reachability check const reachable: boolean = snap.isReachable(0, 10, 0, 42); // 2. Fluent VM QueryBuilder with fixed-point transitive closure const state = new VmState(); const query = new QueryBuilder() .inputNode(0) .walkEdge(0) // Relation 0: MEMBER_OF .repeatUntilStable((b) => { b.walkEdge(1); // Relation 1: PARENT_GROUP }) .collectBitset() .compile(); const res = query.executeWithContext(ctx, state, 42); console.log('Execution OK:', res.isOk(), 'Group 7 reachable:', res.testBitset(ctx, 7)); } finally { ctx.destroy(); snap.close(); } ``` --- ## 4. Cross-SDK Method Equivalence | Operation | Go (`impulse-go`) | .NET 8+ (`ImpulseGraph`) | Node.js / TS (`impulse-graph`) | | :--- | :--- | :--- | :--- | | **Open `.imps`** | `impulse.OpenSnapshot(path)` | `new Snapshot(path)` | `new Snapshot(path)` | | **Domain / Relation Count** | `snap.DomainCount()` / `RelationCount()` | `snap.DomainCount` / `RelationCount` | — | | **Direct CSR Check** | `snap.IsReachable(rel, src, tgt)` | `snap.IsReachable(rel, src, tgt)` | `snap.isReachable(srcDom, src, tgtDom, tgt)` | | **Zero-Copy CSR Buffers** | `snap.GetRelationBuffers(rel)` | — *(Direct pointers via FFI)* | — *(Off-heap VM buffers)* | | **Fluent Traversal API** | — | — | `snap.traverse(node)` | | **VM Context** | `impulse.NewVMContext(snap)` | `new VmContext(snap)` | `new VmContext(snap)` | | **Seed Input Node** | `qb.InputNode(dstReg)` | `qb.InputNode(dstReg)` | `qb.inputNode(dstReg)` | | **Forward Walk (CSR)** | `qb.WalkEdge(relId, dstReg)` | `qb.WalkEdge(relId, dstReg)` | `qb.walkEdge(relId, flags)` | | **Reverse Walk (CSC)** | `qb.CscWalk(relId, dstReg)` | `qb.CscWalk(relId, dstReg)` | `qb.walkCsc(relId)` | | **Fixed-Point Loop** | — | — | `qb.repeatUntilStable(b => ...)` | | **Execute VM Query** | `impulse.ExecuteVM(code, state, seed)` | `snap.ExecuteQuery(query, ctx, seed)` | `query.executeWithContext(ctx, state, seed)` | | **Close / Unmap** | `snap.Close()` | `snap.Dispose()` (`using`) | `snap.close()` | ================================================================================ FILE: docs/benchmarks/java-hotspot-vs-graal.md | URL: https://www.impulsegraph.org/benchmarks/java-hotspot-vs-graal/ ================================================================================ # Java VM Benchmark: OpenJDK HotSpot C2 vs. Oracle GraalVM JIT & Project Leyden AOT This benchmark report presents empirical performance comparisons for the **Impulse Graph Java VM Engine** across **OpenJDK HotSpot C2** (with JDK 25 Project Leyden `-XX:AOTCache`) and **Oracle GraalVM JIT**, alongside architectural build notes for **GraalVM Native Image (`native-image`)**. --- ## 1. Empirical `twitter-2010` Benchmark Suite Matrix (41.65M Nodes, 1.47B Edges, 10 Threads) All evaluations below were conducted on **Apple Silicon M-Series (ARM64 NEON 128-bit SIMD, 10 Threads)** over the **`twitter-2010.imps` Graph Snapshot** (**41,652,230 Nodes**, **1,468,365,182 Edges**, **6.040 GB** zero-copy memory-mapped binary snapshot): | Benchmark Workload (`twitter-2010.imps`, 10 Threads) | C++ GAPBS Reference (10 Threads) | Impulse C++20 Kernel (`impulse_vm.cpp`) | Impulse Java VM HotSpot C2 (OpenJDK) | Impulse Java VM Graal JIT | Best Engine / Primary Architectural Driver | | :--- | :---: | :---: | :---: | :---: | :--- | | **0. Off-Heap `mmap` Dataset Load Time** | `0.047 ms` *(pre-mapped)* | **`0.038 ms`** | `7.869 ms` (`9.748 ms` cold w/ Leyden AOT) | `16.703 ms` | **Impulse C++20** (`0.038 ms` direct `mmap`) | | **1A. Full-Graph Direction-Optimizing BFS** *(Root 0, Optimized CSR+CSC Hybrid)* | `149.00 ms` | **`145.00 ms`** | **`240.29 ms`** (`1.65x` of C++20) | — | **Impulse C++20** (`145.00 ms`) / **Java 25** (`1.65x` parity) | | **1B. Full-Graph Parallel BFS** *(Root 613, Pre-Hoist Baseline)* | `2,476.26 ms` (`593.0 MTEPS`) | **`779.37 ms`** (`1,884.0 MTEPS`) | `3,191.67 ms` (`443.6 MTEPS`) | `3,668.51 ms` (`385.9 MTEPS`) | **Impulse C++20** (Pre-hoist baseline before `VmQueryContext` bitset reuse) | | **2. 2-Hop Targeted BFS Micro-Query** *(Steady-State Micro-Latency)* | N/A | — | **`2.8 µs – 4.13 µs`** | `3.7 µs` | **Java HotSpot C2** (`MethodHandle` Combinator Fusion) | | **3. CC (Connected Components)** *(39,681,514 Components via `OP_CC_AFFOREST`)* | **`138.69 ms`** (`10,587.3 MTEPS`) | `156.73 ms` (`9,368.6 MTEPS`) | `349.60 ms` (`4,200.1 MTEPS`) | **`311.23 ms`** (`4,717.9 MTEPS`) | **Graal JIT** (`1.12x` faster than HotSpot C2 via Union-Find loop unrolling) | | **4. PR (PageRank per iteration)** *(10 Iterations via `OP_MXV`)* | `2,286.45 ms` / iter | `1,940.12 ms` / iter | `1,890.30 ms` / iter | **`1,680.10 ms`** / iter | **Graal JIT** (`1.13x` faster than HotSpot C2 on float SpMV pull pass) | !!! note **Why Row 1A (`240.29 ms`) is `13.3x` faster than Row 1B (`3,191.67 ms`)**: Row 1B reflects an earlier baseline (`Twitter2010BfsVmBenchmarkTest` from Root 613) where per-level frontier arrays were allocated inside the BFS loop. Hoisting off-heap bitset buffers into a reusable `VmQueryContext` and applying direction-optimizing push/pull switching reduced 10-thread Java 25 BFS latency to **`240.29 ms`** (`1.65x` of the `145.00 ms` C++20 kernel; see [Benchmarks](../benchmarks.md)). --- ## 2. JDK 25 Project Leyden AOT Cache (`-XX:AOTCache`) vs. Cold JVM Startup Recording and pre-linking class metadata, `MethodHandle` combinators, and C2 JIT profiles into a Project Leyden AOT cache (`-XX:AOTMode=record` / `-XX:AOTMode=create` / `-XX:AOTCache=...`) eliminates cold-start warmup penalties: | Workload / Experiment Mode (`twitter-2010.imps`) | JVM Flags / AOT Mode | Warmup Iterations | Cold-Start Load Time | First Invocation Latency | Post-Warmup Latency (10k iters) | | :--- | :--- | :---: | :---: | :---: | :---: | | **BFS Baseline (Cold JVM)** | Standard JVM flags | `0` | `14.557 ms` | `332 µs` (`0.332 ms`) | — | | **BFS Leyden AOT Production** | `-XX:AOTCache=impulse.aotcache` | `0` | **`9.748 ms`** (`1.49x` faster) | `369 µs` (`0.369 ms`) | — | | **BFS Post-C2 JIT (Vector API)** | `--add-modules jdk.incubator.vector` | `10,000` | `5.784 ms` | `222 µs` (`0.222 ms`) | **`4.13 µs`** (`0.0041 ms`) | | **CC Baseline (Cold JVM)** | Standard JVM flags | `0` | `16.501 ms` | `776 µs` (`0.776 ms`) | — | | **CC Leyden AOT Production** | `-XX:AOTCache=impulse_cc.aotcache` | `0` | **`9.899 ms`** (`1.67x` faster) | **`321 µs`** (**`2.42x` faster cold**) | — | | **CC Post-C2 JIT (Vector API)** | `--add-modules jdk.incubator.vector` | `10,000` | `5.784 ms` | `329 µs` (`0.329 ms`) | **`9.88 µs`** (`0.0098 ms`) | --- ## 3. Deployment Recommendations: HotSpot C2 vs. GraalVM JIT * **OpenJDK HotSpot C2 + Project Leyden (`-XX:AOTCache`)**: Recommended default for standard enterprise microservices, Spring Boot applications, and container deployments on both **ARM64 (Apple Silicon / AWS Graviton)** and **AMD64 (x86_64)**. Achieves **`9.75 ms`** cold snapshot load times and **`2.8 µs – 4.13 µs`** targeted multi-hop query latencies via `ImpulseMethodHandleCompiler`. * **Oracle GraalVM JIT (JVM Mode)**: Recommended for compute-heavy analytical batch sweeps such as full-graph **Connected Components (`OP_CC_AFFOREST`)** and **PageRank (`OP_MXV`)**, where Graal's aggressive loop unrolling and bounds-check elimination provide a **`12%–13%` throughput advantage** over HotSpot C2. --- ## 4. Building GraalVM Native Image Distributables & Architectural Constraints !!! warning **Empirical Architecture Constraint (ARM64 vs. AMD64 for GraalVM `native-image`)**: - **GraalVM JIT (JVM mode)**: Full 100% support for Java 25 Foreign Function & Memory (FFM) API across both **ARM64** (Apple Silicon / AWS Graviton) and **AMD64** (`x86_64`). - **GraalVM Native Image AOT (`native-image`)**: FFM Foreign API support (`-H:+ForeignAPISupport`) is currently supported **exclusively on AMD64 (`x86_64`) architectures**. Attempting to build a `native-image` binary with FFM on ARM64 / Apple Silicon fails at build time with: `Error: Support for the Foreign Function and Memory API is currently available only on the AMD64 architecture.` - On ARM64 platforms, use **OpenJDK 25 with Project Leyden AOT Cache (`-XX:AOTCache`)** for fast startup (`9.75 ms`), or use the native C++20/Rust CLI (`impulse`). ### Build Command (AMD64 Linux / macOS `x86_64` Only) ```bash native-image \ --enable-preview \ --add-modules jdk.incubator.vector \ -H:+UnlockExperimentalVMOptions \ -H:+ForeignAPISupport \ -H:+EnableURLProtocols \ --enable-native-access=ALL-UNNAMED \ -O3 \ -jar target/impulse-server-executable.jar \ -o impulse-native-server ``` --- ## 5. Benchmark Execution Commands To re-run the `twitter-2010` Java VM benchmark suite locally: ```bash # 1. Full-Graph BFS Benchmark mvn test -pl impulse-vm -Dtest=Twitter2010BfsVmBenchmarkTest # 2. Connected Components (OP_CC_AFFOREST) Benchmark mvn test -pl impulse-vm -Dtest=Twitter2010CcVmBenchmarkTest # 3. PageRank SIMD SpMV (OP_MXV) Benchmark mvn test -pl impulse-vm -Dtest=Twitter2010PrVmBenchmarkTest ``` ================================================================================ FILE: docs/benchmarks/jvm-ecosystem-comparison.md | URL: https://www.impulsegraph.org/benchmarks/jvm-ecosystem-comparison/ ================================================================================ # Enterprise JVM Ecosystem Guide: HotSpot, GraalVM, Corretto, Azul Prime & OpenJ9 Because the **Pure Java 25 Impulse Graph Engine** (`impulse-graph-java`) has **zero third-party runtime dependencies** and relies strictly on standard JDK APIs—**Foreign Function & Memory (`java.lang.foreign`)**, **Vector API (`jdk.incubator.vector`)**, and **`java.lang.invoke.MethodHandle`**—it runs across all compliant Java 21 LTS+ and Java 25 LTS enterprise JVM distributions. This guide summarizes our verified empirical JVM measurements alongside architectural compatibility and tuning guidance for the major enterprise JVM runtimes. --- ## 1. Verified Empirical Baseline: OpenJDK HotSpot C2 vs. Oracle GraalVM JIT Evaluated on **Apple Silicon M-Series (ARM64 NEON, 10 Threads)** over the **6.04 GB `twitter-2010.imps`** snapshot (`41.65M` nodes, `1.47B` edges; see [HotSpot vs. GraalVM Report](java-hotspot-vs-graal.md) and [Main Benchmarks](../benchmarks.md) for full reproduction commands): | Empirical Metric (`twitter-2010.imps`) | OpenJDK HotSpot C2 (JDK 25 + `-XX:AOTCache`) | Oracle GraalVM JIT (JVM Mode) | Key Takeaway | | :--- | :---: | :---: | :--- | | **Cold-Start Snapshot Load (`mmap` + AOT)** | **`9.748 ms`** (`7.869 ms` warm) | `16.703 ms` | Leyden `-XX:AOTCache` delivers `< 10 ms` JVM cold start. | | **2-Hop Targeted BFS Micro-Latency** | **`2.8 µs – 4.13 µs`** | `3.7 µs` | HotSpot C2 inlines `MethodHandle` combinator chains with zero heap allocations. | | **Full-Graph Connected Components (10T)** | `349.60 ms` (`4,200.1 MTEPS`) | **`311.23 ms`** (`4,717.9 MTEPS`) | Graal JIT's loop unrolling accelerates `OP_CC_AFFOREST` by `1.12x`. | | **Full-Graph PageRank SpMV (10T)** | `1,890.30 ms` / iter | **`1,680.10 ms`** / iter | Graal JIT accelerates float vector pull accumulation (`OP_MXV`) by `1.13x`. | | **Hot-Path Heap GC Pauses** | **`0.00 ms`** (Zero Heap Allocations) | **`0.00 ms`** (Zero Heap Allocations) | Topology and VM registers live 100% off-heap in FFM `MemorySegment`s. | --- ## 2. Enterprise JVM Runtime Compatibility & Architecture Matrix | JVM Distribution | FFM (`MemorySegment`) Support | Vector API (`jdk.incubator.vector`) SIMD | Cold-Start Acceleration Mechanism | Primary Production Target | | :--- | :--- | :--- | :--- | :--- | | **OpenJDK 25 (HotSpot C2)** | Full (`AMD64` & `ARM64`) | Full (`AVX-512`, `AVX2`, `ARM NEON`) | **Project Leyden AOT Cache** (`-XX:AOTCache`) | Reference standard for Linux/macOS/Windows enterprise deployments | | **Amazon Corretto 25** | Full (`AMD64` & `ARM64`) | Full (`AVX-512`, `AVX2`, `ARM NEON` / SVE) | AppCDS / Project Leyden (Roadmap) | AWS EC2 Graviton3 / Graviton4 (`ARM64` Neoverse) & EKS | | **Oracle GraalVM JIT (JVM Mode)** | Full (`AMD64` & `ARM64`) | Full (Graal Vectorizer + Vector API) | AppCDS / JVM AOT Cache | Compute-intensive graph analytics (PageRank, Connected Components) | | **GraalVM Native Image (`native-image`)** | **AMD64 (`x86_64`) Only** (`-H:+ForeignAPISupport`; unsupported on `ARM64`) | Experimental on `native-image` | AOT Native Binary (No JVM warmup) | Serverless / CLI containers on `x86_64` Linux | | **Azul Platform Prime (Zing)** \* | Full (`x86_64` & `ARM64` Linux) | LLVM Falcon JIT auto-vectorization + Vector API | Falcon ReadyNow! profile log | Strict SLA financial trading & fraud services with large auxiliary heaps (C4 GC) | | **Eclipse OpenJ9 / IBM Semeru** \* | Supported (JDK 21+) | Partial / Scalar Fallback in OMR JIT | Shared Classes Cache (`-Xshareclasses`) | Memory-constrained Kubernetes pod packing where minimal base JVM RSS is required | *\* Note: Azul Platform Prime and Eclipse OpenJ9 characterizations reflect architectural compatibility and vendor feature matrices; empirical benchmark tables above were recorded strictly on OpenJDK 25 HotSpot and Oracle GraalVM.* --- ## 3. Runtime-Specific Deployment Notes ### 1. OpenJDK 25 & Amazon Corretto 25 (Recommended Default) * **Why**: Zero custom build steps, full support for `IntVector.SPECIES_PREFERRED` SIMD intrinsics on both x86_64 (`AVX-512`/`AVX2`) and ARM64 (`NEON`), and sub-10ms cold start via Project Leyden (`-XX:AOTCache`). * **Recommended Flags**: ```bash java --add-modules jdk.incubator.vector \ --enable-native-access=ALL-UNNAMED \ -XX:+UseZGC -XX:+ZGenerational \ -XX:AOTCache=impulse.aotcache \ -Xms2g -Xmx4g \ -jar application.jar ``` ### 2. Azul Platform Prime (Falcon LLVM JIT + C4 GC) * **Why**: While Impulse Graph itself performs **zero heap allocations** on the query hot path, enterprise applications often co-locate graph traversal alongside heavy heap-allocating frameworks (Spring Boot, Jackson JSON serialization, Kafka consumers, gRPC protobuf marshaling). Azul Prime's C4 collector eliminates GC tail-latency spikes from those surrounding application layers, while the LLVM-based Falcon JIT aggressively vectorizes off-heap loops. ### 3. Eclipse OpenJ9 / IBM Semeru * **Why**: OpenJ9's Shared Classes Cache (`-Xshareclasses`) and compact internal metadata reduce the baseline JVM RSS overhead of the host microservice container, leaving more physical node RAM available for the OS page cache (`mmap` `.imps` pages). ### 4. GraalVM Native Image (`x86_64` Only) * **Constraint**: As detailed in the [HotSpot vs. GraalVM Report](java-hotspot-vs-graal.md#4-building-graalvm-native-image-distributables-architectural-constraints), GraalVM `native-image`'s `-H:+ForeignAPISupport` flag is currently restricted to **AMD64 (`x86_64`)** and throws an `UnsupportedFeatureException` at build time on ARM64 / Apple Silicon. For ARM64 deployments requiring instant startup, use OpenJDK 25 with `-XX:AOTCache` or the native C-ABI / Rust engine. ================================================================================ FILE: docs/contributing/index.md | URL: https://www.impulsegraph.org/contributing/ ================================================================================ # Contributing to Impulse Graph Engine Welcome! We are excited to have you contribute to the Impulse Graph Engine. Because our repository spans multiple languages and architectural layers, please review this guide to get your local environment configured. ## Architecture Rule: Zero Dependencies The core engine (`impulse-storage` and `impulse-vm` in Java, `impulse-cpp`, `impulse-rust`) strictly maintains **zero third-party runtime dependencies**. Features like Kafka, Spring Boot, or RocksDB belong in the `impulse-platform` repository. Do not introduce network, parsing, or logging dependencies into the core engine. ## Building from Source All repositories reside in the `~/impulse/` multi-repository workspace. Engine and verification repositories include `impulse-graph-spec` at `spec/` via Git submodules, so clone them with `--recurse-submodules`: ```bash git clone --recurse-submodules https://github.com/impulse-graph/impulse-graph-core.git git clone --recurse-submodules https://github.com/impulse-graph/impulse-graph-java.git ``` ### Pure Java Engine (`impulse-graph-java/`) Requires JDK 22+ (JDK 25 recommended for Vector API SIMD enhancements). ```bash cd impulse-graph-java mvn clean test ``` ### Native C++20 & C-ABI Kernel (`impulse-graph-core/impulse-cpp/`) Requires a C++20 compliant compiler (GCC 11+, Clang 14+, MSVC 19.30+). ```bash cd impulse-graph-core/impulse-cpp cmake -B build cmake --build build ctest --test-dir build --output-on-failure ``` ### Rust Crate (`impulse-graph-core/impulse-rust/`) Requires stable Rust (`1.80+`). ```bash cd impulse-graph-core/impulse-rust cargo test ``` ### Developer CLI & Compiler Suite (`impulse-graph-core/impulse-cli/`) ```bash cd impulse-graph-core/impulse-cli cargo build --release cargo test ``` ### Language Bindings (`impulse-graph-core/`) ```bash # Python cd impulse-graph-core/impulse-python && pytest # Go cd impulse-graph-core/impulse-go && go test -v ./... # Node.js cd impulse-graph-core/impulse-node && npm test # C# / .NET cd impulse-graph-core/impulse-dotnet && dotnet test ``` ### Preparing Kernels for Four-Way Validation Build the optimized and unoptimized C++ kernels plus Java classes before running the suites in [Polyglot Validation & Testing](polyglot-validation.md): ```bash cd impulse-graph-core/impulse-cpp cmake -B build_on -DCMAKE_BUILD_TYPE=Release && cmake --build build_on cmake -B build_off -DCMAKE_BUILD_TYPE=Debug -DOPTIMIZATIONS=OFF && cmake --build build_off cd ../../impulse-graph-java && mvn compile -DskipTests ``` ### Documentation Portal (`impulse-website/`) Requires Python 3 and MkDocs Material. ```bash cd impulse-website pip install mkdocs-material mkdocs serve ``` ## Git & Data Hygiene - **No Data Blobs**: Never commit datasets (`.csv`, `.bin`, `.imps`) into Git. - **Datasets Folder**: Use the `datasets/` subdirectory for all local tests and benchmarks. It is excluded via `.gitignore`. - **Branch Naming**: Use `feature/`, `bugfix/`, or `docs/`. ================================================================================ FILE: docs/contributing/polyglot-validation.md | URL: https://www.impulsegraph.org/contributing/polyglot-validation/ ================================================================================ # Polyglot Validation & Testing This page covers how Impulse Graph verifies correctness across its specification, VM engines, compilers, and language bindings (`impulse-graph-spec`, `impulse-graph-core`, `impulse-graph-java`, `impulse-ocaml`, and `impulse-verification`). For workspace setup and building individual repositories, see the [Contributing Guide](index.md). For design rationale, see [Why Impulse Graph?](../concepts/why-impulse.md). --- ## 1. Verification Layers | Layer | Location | What It Tests | | :--- | :--- | :--- | | **Binary Snapshot Vectors** | `impulse-graph-spec/test-vectors/tc01`–`tc38` | Positive layout, alignment, CSR/CSC, key catalog, and attribute vectors; negative SHA-256 corruption, bad flag, out-of-bounds offset, and truncation traps. | | **VM Assembly Suite** | `impulse-graph-spec/test-vectors/vm-impas/` | 531 self-contained `.impas` scripts with `{EXPECT: ...}` headers. `run_vm_asm_suite.py` enforces 100% coverage of all 166 opcodes (`0x00`..`0xCB`) and requires every opcode to appear in at least 2 test files. | | **Four-Way VM Parity** | `impulse-verification/tools/four_way_validation.py` | Runs every `.impas` vector across C++ (`-O3`), C++ (`-O0`), Java 25, and OCaml (`impulse-ocaml`), requiring identical registers (`R0`..`R63`), PC, flags, status codes, and `ICTX` v1 SHA-256 state hashes. | | **Contract & Differential Fuzzing** | `impulse-verification/tools/fuzz_vm_contracts.py` & `test_opcode_contracts.cpp` | Validates all 188 opcode contract variants (`contracts.json`) for register type checks, bounds (`r >= 64`), in-place aliasing, and null-context safety. | | **Cross-Compiler Parity** | `impulse-verification/tools/cross_compiler_parity.py` | Verifies consistent lowering and execution across frontends (ImpK, ImpLog, openCypher). | | **Engine vs. FFI Boundaries** | `impulse-graph-core` / `impulse-graph-java` | Engine kernels run the full ISA suite; FFI bindings (Python, Go, Node.js, .NET) run focused boundary tests covering C-ABI signatures, struct layout, memory lifecycle, and error propagation. | ### Test-First ISA Rule New `impOps` opcodes or ISA behavior changes must add positive and negative `.impas` test vectors in `impulse-graph-spec/test-vectors/vm-impas/` alongside the spec change. Each `.impas` file embeds its assertions in comment headers: ```asm ; {EXPECT: STATUS = IMPULSE_VM_OK} ; {EXPECT: R0 = 42} ; {EXPECT: R1 = 100} ; {EXPECT: FLAG = !ZF} .text 0x00: OP_LOAD_CONST_INT R0, 42 0x01: OP_LOAD_CONST_INT R1, 100 0x04: OP_MOV R7, R0 0x09: OP_HALT ``` For the `ICTX` v1 hash wire format and opcode contract definitions, see [VM Specification §9–§10](../reference/spec/vm-specification.md) and [C-ABI Reference §7](../reference/c-abi.md). --- ## 2. Engine Logic vs. FFI Binding Scope | Concern | Targets | Scope | | :--- | :--- | :--- | | **Engine Logic** | `impulse-cpp`, `impulse-rust`, `impulse-graph-java`, `impulse-ocaml` | Opcode execution, bitsets, SIMD kernels, memory mapping, and compiler passes. | | **FFI Boundaries** | `impulse-python`, `impulse-go`, `impulse-node`, `impulse-dotnet` | C-ABI signatures, struct padding, string/array marshaling, pointer lifecycle, and exception mapping. | Running all 531 VM vectors through every FFI wrapper on every PR adds build time without finding engine bugs already caught by the native kernel and four-way suites. PRs run focused FFI contract suites, while release validation exercises the full matrix. --- ## 3. CI Gates * **`impulse-graph-core` PR CI**: C++20 build & `ctest` matrix (Linux, macOS, Windows), Rust crate (`rustfmt`, `clippy`, `cargo test`), CLI matrix, Multi-Language FFI bindings (Python, Go, Node.js), ASan/UBSan, TSan, and libFuzzer smoke tests. * **`impulse-graph-java` PR CI**: Dual-target JDK 21 LTS and JDK 22+/25 LTS builds, `spotless:check`, unit/integration suites, and Jazzer fuzzing. * **Release Pipelines**: Artifact builds, signing, and provenance attestations are documented in [Packages & Distribution](../reference/packages.md). --- ## 4. Running Verification Suites Locally First build the C++ kernels (`build_on` and `build_off`) and Java classes as described in the [Contributing Guide](index.md), then run: ```bash # 1. Spec VM assembly suite & 100% opcode coverage check cd impulse-graph-spec python3 tools/run_vm_asm_suite.py # 2. Four-way VM parity (C++ -O3, C++ -O0, Java 25, OCaml) cd ../impulse-verification python3 tools/four_way_validation.py # 3. Contract-guided differential fuzzer python3 tools/fuzz_vm_contracts.py --iterations 1000 # 4. Cross-compiler parity (ImpK / ImpLog / openCypher) python3 tools/cross_compiler_parity.py ```