lietzsche;stokes

updated 2026-11-26·5 min read

Projection Consumption Isolation & Field Masking

Eliminating wildcard projection hazards, isolating internal shard table leakage, and enforcing compile-time field mask verification across storage boundaries.

Querying an analytical store without bounding what comes back (SELECT * FROM events, or WHERE table LIKE 'events%' against system.columns) is the fastest way to smuggle schema drift across a service boundary.

  1. ClickHouse Distributed Storage & Shards

    Distributed table events delegates across events_r0 and events_r1, each carrying 40 internal operational columns (_shard_num, _replica_sync_token, _part_offset, _compaction_epoch).

  2. Unqualified Catalog Reflection

    SELECT name FROM system.columns WHERE table LIKE 'events%' matches all three tables and emits 280 columns instead of 200.

  3. Downstream Buffer Collision

    The Rust proxy expects [Feature; 200]. Calling slice.try_into().unwrap() panics and drives crash loops.

Stokes stops that leak with explicit projection isolation and field mask verification.

Physical Schema Leakage from Internal Shard Tables

ClickHouse scales horizontally with Distributed tables backed by ReplicatedMergeTree shards. If a Python worker queries system.columns without pinning database and using strict table equality, internal shard maintenance columns spill straight onto the wire:

Vulnerable Schema & Unqualified Reflection Query
CREATE TABLE analytics.events (
    event_id UUID,
    client_ip String,
    bot_score Float32,
    ja4_fingerprint String,
    datacenter_asn UInt32
) ENGINE = Distributed('cluster_east', 'analytics', 'events_local', rand());

CREATE TABLE analytics.events_r0 (
    event_id UUID,
    _shard_num UInt8,
    _replica_sync_token UInt64,
    _part_offset UInt32,
    _compaction_epoch UInt32
) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/events_r0', '{replica}');
# VULNERABLE: Unqualified reflection query emits 280 strings
def discover_active_signals(ch_client) -> list[str]:
    query = """
    SELECT name
    FROM system.columns
    WHERE table LIKE 'events%'
    """
    rows = ch_client.execute(query)
    return [row[0] for row in rows]

sqlfluff says the SQL is valid, mypy sees list[str], ClickHouse returns 280 rows without complaint, and the downstream proxy crashes as soon as it reads them.

Allowlisted Field Masks

Every downstream intake boundary needs a closed Field Mask declared upfront (mask list size <= downstream buffer capacity). Any column emitted upstream must appear in that allowlist before reaching serialization:

Admitted by Allowlist (200 fields)

Canonical fields (bot_score, ja4_fingerprint, datacenter_asn, …) pass into [Feature; 200], keeping slice.try_into() safe.

Dropped Before Serialization (80 items)

Internal shard maintenance columns (_shard_num, _replica_sync_token, _part_offset, …) are discarded before packing or heap allocation.

Field Mask Verification Engine

Stokes enforces explicit field masking across three layers: stokes-sql runs Tree-sitter queries to catch SELECT * wildcards (LINT-006) and unscoped catalog reflections (LINT-001), stokes.toml pins mode = "strict_field_mask" with an explicit mask list and allow_unmapped_columns = false, and on the Rust side a static [u64; 4] 256-bit ProjectionMask checks incoming feature IDs in registers without touching the heap.

Tree-sitter Query, Field Mask Manifest & Rust Bitset Validator
;; contracts/ast_queries/sql_projection_wildcard.scm
(select_statement
  (select_clause
    (wildcard_expression) @wildcard_hazard)
  (#match? @wildcard_hazard "^\\*$")) @fatal_wildcard_projection
# stokes.toml: Declarative Field Mask Contract
[[channels]]
id = "analytics_to_edge_l7"
wire_format = "json"
transport = "kv_store"

[channels.producer]
cardinality_limit = 200

[channels.consumer]
capacity_limit = 200

[channels.projection]
mode = "strict_field_mask"
allow_unmapped_columns = false
mask = [
  "bot_score",
  "ja4_fingerprint",
  "entropy_score",
  "datacenter_asn",
  "http_method",
  "path_depth",
  "tls_ciphersuite",
]
// crates/cloudflame-proxy/src/engine/projection_mask.rs
pub const MAX_CANONICAL_FEATURES: usize = 200;

pub struct ProjectionMask {
    mask_bits: [u64; 4], // 256-bit bitset covers IDs 0..255
}

impl ProjectionMask {
    pub const fn new() -> Self {
        Self {
            mask_bits: [
                u64::MAX,              // 0..63
                u64::MAX,              // 64..127
                u64::MAX,              // 128..191
                0x0000_00FF_FFFF_FFFF, // 192..199
            ],
        }
    }

    #[inline(always)]
    pub fn is_allowed(&self, feature_id: u32) -> bool {
        if feature_id >= 200 {
            return false;
        }
        let word_idx = (feature_id / 64) as usize;
        let bit_idx = feature_id % 64;
        (self.mask_bits[word_idx] & (1u64 << bit_idx)) != 0
    }
}

Production Patch: Eliminating Shard Column Leakage

In the Cloudflame benchmark ETL worker (services/feature-pipeline/catalog_sync.py), Stokes resolves LINT-001 and LINT-006 by scoping database, enforcing strict table equality, excluding ALIAS columns, ordering rows deterministically, and keeping the SQL LIMIT 200 aligned with the [:200] Python guard (whereas downstream Rust still runs Dual-Zone 128 + 72 priority partitioning so any unmasked overflow never drops Zone 0 core signals blindly):

--- a/services/feature-pipeline/catalog_sync.py
+++ b/services/feature-pipeline/catalog_sync.py
@@ -14,14 +14,24 @@
 def query_catalog_features(client, db_name: str, table_name: str) -> list[dict]:
-    query = f"""
-        SELECT name, type 
-        FROM system.columns 
-        WHERE table LIKE '{table_name}%'
-    """
+    query = f"""
+        SELECT name, type 
+        FROM system.columns 
+        WHERE database = '{db_name}'
+          AND table = '{table_name}'
+          AND default_kind != 'ALIAS'
+        ORDER BY position ASC
+        LIMIT 200
+    """
     rows = client.execute(query)
-    return [{"name": r[0], "type": r[1]} for r in rows]
+    features = [{"name": r[0], "type": r[1]} for r in rows]
+    features.sort(key=lambda f: 0 if "shard" in f["name"] else 200, reverse=True)
+    return features[:200]

Diagnostic Rules & Security Model Comparison

Projection ModelImmunity to Shard LeakageAllocation OverheadZero-Copy FitStatic Verification
Wildcard (SELECT *)0% (Drifts on any DDL change)UnboundedLowFlagged (LINT-006)
Unqualified Reflection0% (Absorbs r0, r1 shards)UnboundedNoneFlagged (LINT-001)
GraphQL Field Selection100%Heavy (AST parse per request)Poor (Dynamic dicts)Complex runtime
Stokes Field Masks100% (Static bitmask)0 B (Static bitmask)Optimal (Stack buffers)Deterministic CI check

Continue to Deterministic CI Gate & Native MCP Server to integrate these rules into pull requests and IDE agents.

Search wiki and portfolio

type to search across all entries.