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

推荐订阅源

SecWiki News
SecWiki News
量子位
The Cloudflare Blog
美团技术团队
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
Spread Privacy
Spread Privacy
P
Proofpoint News Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 三生石上(FineUI控件)
T
Tor Project blog
博客园 - 司徒正美
宝玉的分享
宝玉的分享
T
Threatpost
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Secure Thoughts
T
Threat Research - Cisco Blogs
Hacker News: Ask HN
Hacker News: Ask HN
Jina AI
Jina AI
博客园 - 聂微东
A
Arctic Wolf
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Know Your Adversary
Know Your Adversary
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
爱范儿
爱范儿
Hugging Face - Blog
Hugging Face - Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
小众软件
小众软件
T
Tailwind CSS Blog
The Hacker News
The Hacker News
L
LINUX DO - 最新话题
Hacker News - Newest:
Hacker News - Newest: "LLM"
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
TaoSecurity Blog
TaoSecurity Blog
Project Zero
Project Zero
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cloudbric
Cloudbric
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
大猫的无限游戏
大猫的无限游戏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Troy Hunt's Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
V2EX - 技术
V2EX - 技术
The GitHub Blog
The GitHub Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law 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
Three Stabs at a Typed Schema DSL in Kotlin
Rasmus Ros · 2026-05-13 · via DEV Community

Imagine a D&D character sheet. It has typed fields (Strength 1 to 18, Class is Fighter or Wizard or Rogue) and rules between them (Halflings can't be Paladins, Hit Points depend on Class and Constitution). The blank sheet is the schema; a filled-in character is one instance of it.

A blank and filled-in D&D character sheet
Schema vs. instance: the blank sheet on the back, one filled-in Human Fighter on top.

If you only have one schema, you can just write a CharacterSheet data class with the right fields plus some validation, and call it a day. This post is about the harder version: writing the library behind the sheet, where every user brings their own. Pathfinder, 5e, Call of Cthulhu, all different fields, all different rules, all driven by your code. The type system has to help, even though you don't know any of the user schemas in advance.

A few years ago I built combo (Constraint Oriented Multi-variate Bandit Optimization), an A/B-testing tool that picks variants subject to constraints between variables. I've been splitting the rewrite into two libraries: kumulant, a streaming aggregator with just the variables; and klause, an SMT solver with the variables and the rules between them. Both face the same design question: how does a user declare a typed schema, and how do call sites read variables back without dissolving into casts and string lookups?

I'll start with kumulant since it's the smaller half. The reason to lean hard on the types: the more the compiler catches (a misnamed read, a wrong-typed access, an illegal combination), the less the user has to remember.

1. Imperative registries

Every classical solver library starts the same way: a constructor for each kind of variable, references kept as locals, constraints as objects imposed onto the Problem. Choco in Java, Z3 via its Python and Java bindings, and combo's first version all look like this.

val problem = Problem()
val budget = IntVar(problem, "budget", 1000, 4000)
val color  = IntVar(problem, "color", 0, 2)  // 0=RED, 1=GREEN, 2=BLUE

// "if color=RED, then budget ≤ 2000"
problem.impose(IfThen(XeqC(color, 0), XlteqC(budget, 2000)))

Enter fullscreen mode Exit fullscreen mode

The natural upgrade in Kotlin is to hide the problem receiver inside a problem { ... } block and put each kind of variable in a sealed Variable<V, T> hierarchy so it knows its own type. This is the type-safe builder pattern that powers most Kotlin DSLs (e.g. kotlinx.html): lambdas with receivers, infix functions, and operator overloading, enough to make the body look like the original mathematical notation. That's what combo does:

val p = problem {
    val budget = int("budget", min = 1000, max = 4000)
    val color  = nominal("color", RED, GREEN, BLUE)

    impose {
        color[RED] implies budget.atMost(2000)
    }
}

Enter fullscreen mode Exit fullscreen mode

User-supplied relations reference typed value literals like color[RED] against variables in scope, not strings. Underneath, it's the same problem as the bare solver, though. To read a variable at a call site you either keep the typed reference around, threading it through every function that touches it, or fall back to by-name lookup that returns a Variable<*, *> you have to cast. With nested scopes the references fan out faster than you can keep clean, and the common fallback is a Map<String, Var> keyed by name, with reads as unchecked casts.

Is this a pigeon meme: pointing at a cast
Compiles fine, crashes at runtime.

Building the Problem is also imperative, not declarative: the body runs in order, and there's no static structure to inspect or serialize without first executing the lambda.

2. Arity-indexed products

Pivoting to kumulant here: the same schema problem shows up for streaming statistics, where each "variable" is an accumulator like Mean or Sum and call sites need typed reads of its snapshot. Next attempt: give every variable a value that carries its type with it. A call site should be able to write snap.mean and get a typed value end-to-end, no cast.

Encode the schema as a product: a tuple where each position holds a variable, and the type carries the arity.

data class Stat2<A : Stat, B : Stat>(val first: A, val second: B)         // accumulator product
data class Result2<A : Result, B : Result>(val first: A, val second: B)   // snapshot from .read()
// Stat3 / Result3 / … same shape, one per arity

operator fun <A : Stat, B : Stat> A.plus(other: B): Stat2<A, B> = Stat2(this, other)

// Per-trait accessors: one extension per (position, trait) combo
val <B : HasMean> Result2<*, B>.mean get() = second.mean
val <A : HasMean> Result2<A, *>.mean get() = first.mean

Enter fullscreen mode Exit fullscreen mode

The + is defined on Stat itself. A schema is built by adding stats together; the type carries the arity, and a StatGroup wraps the schema as the runtime accumulator:

val schema = Mean("avg_ms") + Sum("total_ms")  // Stat2<Mean, Sum>
val group  = StatGroup(schema)
group.update(105.0)
group.update(80.0)

val snap = group.read()  // Result2<MeanResult, SumResult>
snap.first.mean          // Double, typed
snap.second.sum          // Double, but "second" is positional
snap.mean                // works because only one position has HasMean

// Two stats sharing a trait kills the trait extension:
val decaySchema = DecayingSum(15.minutes) + DecayingSum(1.minutes)
val decayGroup  = StatGroup(decaySchema)
decayGroup.read().sum    // ambiguous; back to .first.sum / .second.sum

Enter fullscreen mode Exit fullscreen mode

The types are fully preserved: add a stat and the type changes; combine two schemas and the types fuse via +. But at the call site you write snap.first.mean, and first is the problem. Position isn't name. Reorder the stats and call sites change. And as soon as two stats share a trait (the DecayingSum + DecayingSum above), the trait extensions become ambiguous and you fall back to .first.sum / .second.sum anyway.

I built the N×M expansion with a KSP processor that generated a trait accessor per position-trait combo, and it compiled. But the abstraction leaked: every call site had to import the right extensions for the traits it read, the parameterized-instances pattern still had no clean read, and the whole thing felt like a hack. Languages with higher-kinded or dependent types make this natural (shapeless is the closest analogue on the JVM), but that's not exactly mainstream territory. Without those features you're encoding a record with positional bookkeeping. I cut it.

3. Typed-key schemas

The fix is to bundle the name and the type into one value: a heterogeneous map keyed by a typed key. Kumulant does it in two layers: a typed key as the plumbing, and a class on top of it for declaring lots of them at once. The plumbing first, a StatKey<R> paired with a GroupResult:

interface Result
interface Stat<R : Result> {
    fun update(value: Double)
    fun read(): R
}

open class StatKey<R : Result>(val name: String, val stat: Stat<R>)

@Serializable
data class GroupResult(val results: Map<String, Result>) : Result {
    operator fun <R : Result> get(key: StatKey<R>): R =
        results[key.name] as R
}

class StatGroup(val keys: List<StatKey<*>>) : Stat<GroupResult> {
    override fun update(value: Double) { keys.forEach { it.stat.update(value) } }
    override fun read(): GroupResult =
        GroupResult(keys.associate { it.name to it.stat.read() })
}

Enter fullscreen mode Exit fullscreen mode

Now keys can be declared directly, and the typed get returns the right result type at the call site:

val mean  = StatKey("mean",  Mean())
val count = StatKey("count", Sum())

val group = StatGroup(listOf(mean, count))
group.update(105.0)

val snap = group.read()
snap[mean]   // MeanResult, no cast at the call site
snap[count]  // SumResult

Enter fullscreen mode Exit fullscreen mode

Each StatKey<R> pairs a name with the type it indexes. The container is a Map<String, Result> underneath, but the typed get returns the declared type, so the call site never sees the cast. Compared to the imperative registry, the strings still exist, but they're bound to the key value, not typed by the user at every read. The key is the variable's identity.

Declaring keys by hand is clunky: you'd be tracking them yourself for the StatGroup, and writing each name twice (once on the property, once as a string). Kumulant uses property delegates on a singleton object instead. Same pattern as JetBrains' Exposed, minus the duplicate name.

abstract class StatSchema {
    private val _keys = mutableListOf<StatKey<*>>()
    val keys: List<StatKey<*>> get() = _keys

    fun <R : Result> stat(s: Stat<R>): PropertyDelegateProvider<StatSchema, StatKey<R>>
    // returns a delegate that registers _keys += StatKey(propertyName, s) and yields the key

    // group(schema): same idea, registers a nested StatGroup as one key
}

fun StatGroup(schema: StatSchema): StatGroup = StatGroup(schema.keys)

Enter fullscreen mode Exit fullscreen mode

User schemas are objects, and every property is a by-delegate:

object HttpMetrics : StatSchema() {
    val requests  by stat(Sum().withValue(1.0))
    // tracks p50, p99, and p999 latency quantiles
    val latencyMs by stat(DDSketch(probabilities = doubleArrayOf(0.5, 0.99, 0.999)))
}

object ServiceMetrics : StatSchema() {
    val requests        by stat(Sum().withValue(1.0))
    val billableMsTotal by stat(Sum())
    val http            by group(HttpMetrics)
    val db              by group(DbMetrics)
}

val service = StatGroup(ServiceMetrics)
service.update(120.0); service.update(80.0)

val snap = service.read()
snap[ServiceMetrics.requests].sum                  // Double, typed
snap[ServiceMetrics.billableMsTotal].sum           // Double, typed
snap[ServiceMetrics.http, { requests }].sum        // dotted lookup into a nested group

Enter fullscreen mode Exit fullscreen mode

Now the schema is a class. Each property is a typed StatKey<R> whose result type matches the stat that constructed it. No magic strings to sync, no references to thread between definition and use, no imperative builder to run before the schema exists; the schema declaration is the structure.

For streaming statistics, this is the design I'm currently happy with. The remaining tradeoffs sit inside individual variables (e.g. derived variables with non-invertible projections need the programmer to handle merge correctness), not in the schema design. This design doesn't address constraints between variables, though. Aggregation is fine; "variable A must always be less than variable B" or "variable C can only be set when variable D fires" has nowhere to live. Fine for kumulant, but klause's case still needs them. That's its own design problem (DSL, AST, wire format) and not one I'd want to cram into this post.

I've pulled the pattern out as Eignex/skema, now at 0.1.0 (Swedish skema means template). It's a Kotlin Multiplatform library where one definition does double duty: typed compile-time access on the producer side, and a kotlinx-serializable wire format so a consumer that doesn't share your Kotlin code can still decode the schema and walk it by name. kumulant, klause, and combo will all settle onto it eventually, just haven't gotten there yet.

If you've worked something like this out, especially in a language without dependent types, I'd love to hear about it. Combo, kumulant, and klause are at github.com/Eignex/combo, github.com/Eignex/kumulant, and github.com/Eignex/klause if you want to poke at them.