惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Last Watchdog
The Last Watchdog
博客园_首页
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
美团技术团队
小众软件
小众软件
V
V2EX
博客园 - Franky
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
Attack and Defense Labs
Attack and Defense Labs
S
Security Affairs
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
T
The Exploit Database - CXSecurity.com
有赞技术团队
有赞技术团队
S
Schneier on Security
人人都是产品经理
人人都是产品经理
Security Archives - TechRepublic
Security Archives - TechRepublic
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
K
Kaspersky official blog
PCI Perspectives
PCI Perspectives
AI
AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
罗磊的独立博客
O
OpenAI News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Register - Security
The Register - Security
V
Vulnerabilities – Threatpost
GbyAI
GbyAI
博客园 - 【当耐特】
C
Cisco Blogs
大猫的无限游戏
大猫的无限游戏
Help Net Security
Help Net Security
Google DeepMind News
Google DeepMind News
S
Securelist
Application and Cybersecurity Blog
Application and Cybersecurity Blog
P
Proofpoint News Feed
博客园 - 三生石上(FineUI控件)
雷峰网
雷峰网
L
LangChain Blog
SecWiki News
SecWiki News
博客园 - 叶小钗
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V2EX - 技术
V2EX - 技术
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
L
LINUX DO - 热门话题
Cisco Talos Blog
Cisco Talos Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
V.E.L.O.C.I.T.Y.-OS: The JIT Compiler Core – From AST to Native Closures (Part 4)
UnitBuilds · 2026-06-28 · via DEV Community

With the standalone IDE running, I had a sandboxed environment to write and execute Neural Document Architecture (NDA) programs. However, executing the binary AST via a standard recursive tree-walk interpreter was adding unacceptable dispatch overhead.

Every opcode instruction required match branching, dynamic type checking, and variable lookup cycles. I needed a Just-In-Time (JIT) compiler to turn the AST into native machine code.


The V.E.L.O.C.I.T.Y.-OS 12-Part Roadmap

We are building a bare-metal, self-healing operating system running entirely inside the CPU's L3 cache. Here is the roadmap for this 12-part series:

  1. Part 1: The Spark — Exposing the "Safe-Room" security leak and building the compiler gate.
  2. Part 2: The NDA Language — Designing a content-addressed triplet representation to cure context bloat.
  3. Part 3: Ditching the Web Stack — Building a native 30MB IDE with 1,500,000x IPC latency drops.
  4. Part 4: The Closure JIT — Compiling AST blocks to nested closures and bypassing borrow checker limits. (You are here)
  5. Part 5: JIT Math Optimizations — Replacing division operations with precomputed 16-bit lookup tables.
  6. Part 6: x86-64 Assembler & SCEV-Lite — Compiling scalar loops directly to native code in constant time.
  7. Part 7: Classic Compiler Passes — Implementing inter-procedural Dead Code Elimination and loop unrolling.
  8. Part 8: Reclaiming Ring 0 — Exiting UEFI boot services and transitioning the kernel to Ring 0.
  9. Part 9: Bare-Metal Drivers — Writing a PCI scanner, NVMe block storage controller, and FAT32 parser.
  10. Part 10: Synaptic Canvas — Rendering a spatial, force-directed GUI based on model token activation vectors.
  11. Part 11: Swarms & Hot-Patching — Building multi-agent scheduling and zero-downtime RCU driver updates.
  12. Part 12: Self-Evolution — Handing system control over to a local LLM Terminal that self-optimizes via telemetry.

Tier-1: The Closure JIT

I started by designing a Tier-1 Closure-Based JIT Compiler.

Instead of compiling directly to machine instructions, the compiler walks the AST at load-time and generates a chain of nested Rust closures (Box<dyn Fn>).

This approach resolves all opcode matches, scope checks, and control-flow branches at compile-time. At runtime, the JIT engine simply walks down a flat, pre-compiled chain of function pointers. This completely eliminates branch misprediction penalties and instruction cache misses.

Here is how the compiler defines the JIT function type and registers the compilation sequence in src/compiler/nda_jit.rs:

// compiler/nda_jit.rs — Closure JIT definitions
pub enum JitControlFlow {
    Continue,
    Break,
    Return,
}

// A compiled JIT closure: accepts a mutable state reference of *any* lifetime 'a
pub type JitFn = Arc<dyn for<'a> Fn(&mut JitState<'a>) -> Result<JitControlFlow, String> + Send + Sync>;

// Compile a sequence of NDA AST nodes into a flat chain of closures
fn compile_sequence(nodes: &[NdaNode], counter: &mut usize, registry: &VarRegistry) -> Vec<JitFn> {
    nodes.iter().map(|n| compile_node(n, counter, registry)).collect()
}

Dynamic Dispatch: How AST Nodes Compile to Closures

To understand why this compiler is so fast, we have to look at how the AST nodes compile into closures.

In a standard interpreter, executing an assignment like let a = 5 and a load like a + 1 requires querying a hash map by string name inside loop ticks. The JIT closure compiler bypasses this by pre-allocating variable slots at load-time and wrapping the runtime actions in nested closures that hold direct index offsets.

Here is the exact implementation in src/compiler/nda_jit.rs for compiling Let and Load nodes:

// compiler/nda_jit.rs — Compiling Let and Load AST nodes to closures
fn compile_node(node: &NdaNode, counter: &mut usize, registry: &VarRegistry) -> JitFn {
    *counter += 1;
    match node {
        // Compile a variable declaration
        NdaNode::Let { name_hash, init } => {
            let slot = registry.get_or_create_slot(*name_hash);
            let init_fn = compile_node(init, counter, registry);

            Arc::new(move |state: &mut JitState<'_>| {
                state.executed_nodes += 1;
                // Evaluate the initialization expression
                init_fn(state)?;
                let val = state.stack.pop().ok_or("Stack underflow in Let init")?;

                // Write directly to the pre-allocated flat array index
                if slot >= state.variables.len() {
                    state.variables.resize(slot + 1, None);
                }
                state.variables[slot] = Some(val);
                Ok(JitControlFlow::Continue)
            })
        }

        // Compile a variable reference load
        NdaNode::Load { name_hash } => {
            let slot = registry.get_or_create_slot(*name_hash);

            Arc::new(move |state: &mut JitState<'_>| {
                state.executed_nodes += 1;
                // Sub-nanosecond flat array read, no hash map overhead
                let val = state.variables.get(slot)
                    .and_then(|v| v.as_ref())
                    .ok_or_else(|| format!("Load of uninitialized variable slot {}", slot))?;

                state.stack.push(val.clone());
                Ok(JitControlFlow::Continue)
            })
        }
        // ... other nodes (Matrix, Norm, Loop, Add) compile similarly
    }
}

By resolving variable lookups to slot indices during compilation and mapping them directly to pre-allocated indices in JitState::variables, we reduce variable load/store operations from hash table lookups to flat memory offsets.

The Lifetime Trap: Higher-Ranked Trait Bounds (HRTBs)

However, I immediately hit a massive Rust lifetime wall.

The JIT execution closures needed to query my persistent Merkle database (SiteMap) to resolve content-addressed function calls. Because the JIT closures were stored and executed dynamically, Satisfying Rust’s borrow checker required wrapping the SiteMap in an Arc<SiteMap>.

This meant that every variable assignment, function call, and closure jump required cloning the atomic reference count. The CPU was wasting cycles updating memory barriers in the hot path.

To fix this, I refactored the JIT engine to accept direct reference inputs &SiteMap instead. I solved the lifetime constraint by using Higher-Ranked Trait Bounds (HRTBs):

type JitFn = Arc<dyn for<'a> Fn(&mut JitState<'a>) -> Result<JitControlFlow, String> + Send + Sync>;

By specifying for<'a>, I explicitly instructed the compiler that the JIT closure could accept a JitState of any lifetime 'a. This allowed the JIT engine to reference the live, stack-allocated database directly, eliminating Arc clones and reference-counting heap writes entirely.

The JIT Sandbox

I wrapped this JIT engine in a custom JIT Sandbox (NdaJitSandbox). Before any program was committed to the codebase, the sandbox:

  1. Compiled the AST on the fly (taking just 93 microseconds).
  2. Ran the execution inside a panic-safe boundary (AssertUnwindSafe).
  3. Captured print buffers and returned execution metadata.

Here is the architectural comparison mapping the JIT compilation pipeline and sandbox verification execution path:

Flowchart showing the JIT Sandbox compilation pipeline: deciding between Tier-1 Closures and Tier-2 Machine code assembly
Fig 1: The two-tier JIT sandbox compilation pipeline and execution pathways.

Pascal's Analysis: Bypassing the Serialization Wall

When I shared the performance gains (the JIT sandbox executing a 4-layer network block in 206µs including compile-and-run time),

analyzed the structural benefits:

"The format itself enforces consistency at write time, so the model can commit incrementally — each triple is either valid against the current graph or it isn't. The correction happens at write speed, not at review time."

By compiling directly to closures, I was allowing the model's output to bypass the serialization wall completely.

But my JIT closures still relied on heap allocations and standard integer loops. I needed to push compiler performance to match—and exceed—native Rust scalar math.

In the next post, I'll document how I optimized the JIT math by introducing slot-based registries and division-free byte loops.

Discussion

How do you handle runtime extensibility in compiled languages? Have you worked with closure chains or dynamic function dispatch in Rust? How do you tackle borrow checker constraints when dealing with dynamic state sharing? Let's discuss in the comments below!


Special thanks to

for showing me that a structured compilation pipeline is the ultimate guard against model hallucinations.


Disclaimer: AI was used throughout this project, it is just fitting that it would co-author with me, so special thanks to the Foundry for its tireless hours toiling away and Gemini for producing the cover image.