Provable but Unqueryable
Why a Merkle state store is hard to query, and how DataFusion could provide SQL over committed state.
I wrote previously about QMDB, a verifiable database that combines Merkle tree maintenance and key-value storage with O(1) I/O per update. After building a protocol on it, I’ve encountered a limitation that update benchmarks don’t measure: efficient proofs do not make arbitrary queries efficient.
Merkle state stores, including Ethereum’s Merkle Patricia Trie (MPT), Celestia’s Namespaced Merkle Tree (NMT), and QMDB, organize data for commitments and proofs. The resulting layout may not support the queries an application needs.
Queries supported by the key layout
Our protocol stores state in QMDB as key-value pairs. Each entity type has a byte prefix followed by identifiers:
[0x0A] [project_id:32] → project state
[0x0D] [project_id:32] [ref_name:variable] → ref state
[0x0E] [project_id:32] [commit_hash:32] → commit state
[0x10] [owner:20] [target:32] [type:1] → link (follow/star)
Lexicographic ordering makes prefix scans efficient. Listing all refs for a project requires one range scan over [0x0D | project_id]. Point lookups require O(1) I/O. Each block produces a state root against which light clients can verify proofs.
The queries that are fast are the ones the key layout was designed for:
| Query | Key pattern | Cost |
|---|---|---|
| Get project by ID | [0x0A | id] |
O(1) |
| List refs for project | scan [0x0D | project_id] |
O(refs in project) |
| List commits for project | scan [0x0E | project_id] |
O(commits in project) |
| Get link by owner+target | [0x10 | owner | target | type] |
O(1) |
These queries use the key layout as their index.
Queries that require scans
Most starred projects. This requires scanning every link entry (0x10), filtering for type Star, grouping by target, counting, and sorting. There is no secondary index on star count. The key layout groups links by owner rather than target.
Projects owned by address X, sorted by recent activity. The project prefix (0x0A) groups by project_id rather than owner. Activity timestamps are stored in commit and ref entries under other prefixes.
In practice, listing an owner’s projects looks like this:
loop {
let entries = store
.scan_prefix_paginated(&prefix, &cursor, batch_size)
.await?;
for (key, value) in &entries {
let project: ProjectState = serde_json::from_slice(value)?;
// Client-side filtering requires scanning all projects.
if !project_matches_owner_address(&project, &owner) {
continue;
}
projects.push(build_project_response(store, &project_id, &project).await?);
}
}
The code deserializes and checks every project it reads. The batch_size = limit * 4 heuristic assumes one in four projects matches. Finding all three projects belonging to an owner among 100,000 projects requires a full scan.
Search projects by name. The name index (0x0C) maps [owner_address | name] to project_id and supports exact matches. Substring and full-text searches require scanning the namespace.
Without additional indexes, queries that do not match the key layout require scans.
The two-system compromise
A common solution uses two systems:
graph TB
subgraph Fresh["Consensus-fresh, limited queries"]
direction LR
U1["User"] --> G1["Gateway"] --> Node["QMDB (node)"] --> Q1["get project X\nlist refs for project Y"]
end
subgraph Rich["Eventually consistent, rich queries"]
direction LR
U2["User"] --> G2["Gateway"] --> Idx["Indexer (edge)"] --> Q2["full-text search\nsorted lists\naggregates"]
end
Node -.->|"block stream"| Idx
style Node fill:#2A40FF,color:#fff
style Idx fill:#3BB273,color:#fff
The node produces blocks. An ingestion pipeline consumes them and updates an indexer that handles joins, aggregates, full-text search, and sorting. The application routes reads to the backend that supports the query:
| Node (QMDB) | Indexer | |
|---|---|---|
| Freshness | Consensus-current | Lags by ingest pipeline |
| Queries | Point lookups and prefix scans | Rich queries, depending on the indexer |
| Proofs | Merkle proofs for any key | None |
| Trust model | Verifiable | Trust the indexer |
The node provides current state and proofs for limited queries. The indexer supports richer queries but can lag by milliseconds or minutes, depending on load, and does not provide proofs in this setup. Maintaining both requires two schemas, two query APIs, and separate failure handling. The indexer must also process the state transitions relevant to its queries.
For someone browsing an explorer, a short delay may be acceptable. The application can display indexed data and refresh it as new blocks arrive.
The agent problem
Agents running in V8 isolates, WebAssembly sandboxes, or edge runtimes may read state and immediately attempt a write. Consider an MCP tool that asks: “What are this user’s most active projects, and do I have permission to update the default branch on each one?”
The answer requires projects filtered by owner, refs and commits for activity, and keys for permissions. With two backends, the agent queries the indexer for activity and the node for permissions. Those responses may describe different blocks.
A short-lived invocation may have no persistent connections, local cache, or record of earlier reads. An environment with a 128–256 MB memory budget cannot reasonably load a full QMDB replica or a large local indexer. HTTP gateways also add round trips when the runtime or service does not support a direct connection.
Inconsistent reads can lead the agent to act on outdated information. A ref may have moved, a permission may have been revoked, or a project may have been archived. A consistent snapshot would make the decision easier to reason about, but the protocol must still validate the write against its current state.
Auditability is a separate requirement. A user should be able to check which state an agent used to make a decision. An indexer response without a proof does not establish that its results match committed state.
graph LR
Agent["Agent\n(V8 isolate)"] --> GW["REST gateway"]
GW --> Node["QMDB node"]
GW --> Idx["Indexer"]
Node --> Fresh["fresh\npoint reads"]
Idx --> Rich["stale\nrich queries"]
style Agent fill:#E84855,color:#fff
style Node fill:#2A40FF,color:#fff
style Idx fill:#3BB273,color:#fff
We run an MCP server with 15 tools that query protocol state through a REST gateway. The gateway routes requests to the node or indexer, so the tools inherit both systems’ limitations. A single query interface over a consistent, provable snapshot would simplify these tools.
SQL over the state store
Apache DataFusion is an extensible query engine in Rust. It takes SQL, optimizes it into a physical execution plan, and runs it against any storage backend that implements TableProvider:
trait TableProvider: Debug + Sync + Send {
fn schema(&self) -> Arc<Schema>;
fn table_type(&self) -> TableType;
async fn scan(
&self,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>>;
}
The provider describes the column schema and how to scan the data. DataFusion handles joins, aggregation, sorting, GROUP BY, HAVING, and window functions. It supports streaming, vectorized, multithreaded execution using Apache Arrow’s columnar format.
The proposal is to implement TableProvider for each QMDB key prefix and register the providers as virtual tables. DataFusion could then execute SQL using QMDB range scans. This would provide one query interface over committed state, though it would not add indexes.
graph LR
SQL["SQL query\nJOIN + GROUP BY + ORDER BY"] --> DF["DataFusion\nplanner + executor"]
DF --> P["Projects provider\nscan 0x0A"]
DF --> L["Links provider\nscan 0x10"]
P --> QMDB["QMDB"]
L --> QMDB
style SQL fill:#E84855,color:#fff
style DF fill:#2A40FF,color:#fff
style QMDB fill:#3BB273,color:#fff
A ProjectsTableProvider translates a scan into a QMDB prefix scan over 0x0A, deserializes each ProjectState, and emits Arrow RecordBatches with columns like project_id, owner_address, name, created_at, commit_count. DataFusion handles the join against LinksTableProvider (prefix 0x10), computes the aggregate, and sorts.
Filter pushdown lets DataFusion pass predicates like owner_address = X to the provider, which can narrow the QMDB scan range when the filter aligns with the key layout, or fall back to post-filtering when it doesn’t.
What this enables
A query layer over committed state could answer questions such as “most starred projects” without waiting for an external indexer to catch up. It could also let an MCP tool query activity and permissions in one request.
These benefits depend on all providers reading the same snapshot. Without snapshot consistency, tables scanned at different times could still disagree. Even with a consistent snapshot, a later write must check current permissions and any preconditions, such as the expected ref value.
The response could include Merkle proofs for the state entries used at a specified block. Those proofs establish that the entries belong to that state root. They do not establish that an aggregate includes every relevant entry or that a ranking is correct. Proving those claims requires additional mechanisms.
This design would avoid a separate indexer replaying state transitions for the queries it supports. Providers would still need to map the stored state to table schemas and track changes to that representation.
The hard parts
The key layout still determines which scans are efficient. DataFusion can pass filters to a TableProvider, but a filter that does not match a key prefix still requires scanning the namespace. “Most starred projects” remains a scan over all link entries. Arrow supports efficient execution after decoding, but the provider still has to read and deserialize the source records. The overall performance needs measurement.
Efficient queries by star count, owner, or recent activity would require additional indexes. The protocol could maintain them under new prefixes during state transitions, at the cost of more writes and more indexing logic inside the state machine.
Concurrency also needs a design. Block execution currently holds a mutex on the database. Long analytical queries could delay block production if they compete for that lock. Historical queries using OldId chains may help implement snapshot reads, but the integration must establish both consistency and isolation from writes.
Full-text search may still need a separate system. SQL predicates such as LIKE and regular expressions do not by themselves provide inverted indexes or BM25-style relevance ranking.
Choosing a query architecture
For browsing applications, a node and external indexer are often sufficient. A short indexing delay may be acceptable, and a dedicated indexer can support search features that a SQL layer over the state store would not provide on its own.
For heavier analytics, exported snapshots in an open table format are another option. R2’s Data Catalog provides a managed Apache Iceberg catalog. R2 SQL uses DataFusion to query those tables without requiring a Spark or Trino cluster. Iceberg snapshots support analytical access patterns through partitioning and column statistics, but exported state still lags the node.
An embedded query layer is most useful when a tool needs several related reads from the same committed snapshot before attempting an action. It could reduce requests and avoid reconciling node and indexer responses. The write path would still enforce permissions and reject outdated preconditions.
QMDB provides storage and entry proofs; DataFusion provides query planning and execution. A TableProvider connects the two. The remaining work includes efficient scans, consistent snapshots, isolation from block production, and proofs for claims beyond individual entries. SQL would make committed state easier to query. It would not, on its own, make every query result verifiable.
Further reading
- QMDB paper: the underlying verifiable database
- Apache DataFusion: extensible query engine in Rust
- DataFusion
TableProvidertrait: the integration point - Arrow Columnar Format: the in-memory data representation
- R2 Data Catalog: managed Apache Iceberg catalog on R2
- R2 SQL deep dive: serverless DataFusion over Iceberg tables