cqlite-core 0.11.0

Core engine for CQLite — read Apache Cassandra 5.0 SSTables locally without a cluster
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Large-data stress tests for the CQLite write engine (#466)
//!
//! These tests validate that the write engine handles large-scale data correctly:
//! - VInt encoding at large offsets (10K clustering rows)
//! - Collection serialization at scale (10K element lists, sets, maps)
//! - Large blob values (10MB)
//! - Wide-row schemas (500 columns)
//! - Bloom filter sizing at scale (1,000 partitions)
//!
//! ## Running
//!
//! All tests are marked `#[ignore]` to avoid slowing down normal CI.
//! Run them explicitly with:
//!
//! ```bash
//! cargo test --package cqlite-core --features write-support \
//!     --test write_large_data -- --ignored
//! ```

#![cfg(feature = "write-support")]

use cqlite_core::schema::{ClusteringColumn, ClusteringOrder, Column, KeyColumn, TableSchema};
use cqlite_core::storage::write_engine::{
    CellOperation, ClusteringKey, Mutation, PartitionKey, TableId, WriteEngine, WriteEngineConfig,
};
use cqlite_core::types::Value;
use std::collections::HashMap;
use tempfile::TempDir;

// ============================================================================
// Helper Functions
// ============================================================================

/// Build a simple schema with partition key `pk` and arbitrary regular columns.
///
/// `columns` is a slice of `(name, data_type)` pairs (must include `pk`).
fn simple_schema(keyspace: &str, table: &str, columns: Vec<(&str, &str)>, pk: &str) -> TableSchema {
    let col_structs: Vec<Column> = columns
        .iter()
        .map(|(name, dt)| Column {
            name: name.to_string(),
            data_type: dt.to_string(),
            nullable: name != &pk,
            default: None,
            is_static: false,
        })
        .collect();

    TableSchema {
        keyspace: keyspace.to_string(),
        table: table.to_string(),
        partition_keys: vec![KeyColumn {
            name: pk.to_string(),
            data_type: col_structs
                .iter()
                .find(|c| c.name == pk)
                .map(|c| c.data_type.clone())
                .unwrap_or_else(|| "int".to_string()),
            position: 0,
        }],
        clustering_keys: vec![],
        columns: col_structs,
        comments: HashMap::new(),
    }
}

/// Build a schema with a single partition key and a single clustering key.
fn simple_schema_with_clustering(
    keyspace: &str,
    table: &str,
    columns: Vec<(&str, &str)>,
    pk: &str,
    ck: &str,
) -> TableSchema {
    let col_structs: Vec<Column> = columns
        .iter()
        .map(|(name, dt)| Column {
            name: name.to_string(),
            data_type: dt.to_string(),
            nullable: name != &pk && name != &ck,
            default: None,
            is_static: false,
        })
        .collect();

    let ck_type = col_structs
        .iter()
        .find(|c| c.name == ck)
        .map(|c| c.data_type.clone())
        .unwrap_or_else(|| "int".to_string());

    TableSchema {
        keyspace: keyspace.to_string(),
        table: table.to_string(),
        partition_keys: vec![KeyColumn {
            name: pk.to_string(),
            data_type: col_structs
                .iter()
                .find(|c| c.name == pk)
                .map(|c| c.data_type.clone())
                .unwrap_or_else(|| "int".to_string()),
            position: 0,
        }],
        clustering_keys: vec![ClusteringColumn {
            name: ck.to_string(),
            data_type: ck_type,
            position: 0,
            order: ClusteringOrder::Asc,
        }],
        columns: col_structs,
        comments: HashMap::new(),
    }
}

/// Create a `WriteEngine` in the provided `TempDir`.
fn create_engine(temp_dir: &TempDir, schema: TableSchema) -> WriteEngine {
    let config = WriteEngineConfig::new(
        temp_dir.path().join("data"),
        temp_dir.path().join("wal"),
        schema,
    );
    WriteEngine::new(config).expect("failed to create WriteEngine")
}

// ============================================================================
// Tests
// ============================================================================

/// Write 10,000 clustering rows into a single partition, then flush.
///
/// Validates VInt offset encoding at scale — the partition body will be large
/// enough that multi-byte VInts are required for internal offsets.
#[tokio::test]
#[ignore] // Large-data test — run with: cargo test -- --ignored
async fn test_10k_clustering_rows_single_partition() -> cqlite_core::error::Result<()> {
    let temp_dir = TempDir::new().expect("failed to create temp dir");

    // Schema: pk int, ck int, data text — columns sorted alphabetically
    let schema = simple_schema_with_clustering(
        "test_large",
        "clustering_10k",
        vec![("ck", "int"), ("data", "text"), ("pk", "int")],
        "pk",
        "ck",
    );

    let mut engine = create_engine(&temp_dir, schema);
    let table_id = TableId::new("test_large", "clustering_10k");
    let timestamp = 1_700_000_000_000_000_i64;

    for ck_val in 0..10_000_i32 {
        let pk = PartitionKey::single("pk", Value::Integer(1));
        let ck = ClusteringKey::single("ck", Value::Integer(ck_val));
        let ops = vec![CellOperation::Write {
            column: "data".to_string(),
            value: Value::Text(format!("row_{}", ck_val)),
        }];
        let mutation = Mutation::new(
            table_id.clone(),
            pk,
            Some(ck),
            ops,
            timestamp + ck_val as i64,
            None,
        );
        engine.write_async(mutation).await?;
    }

    let info = engine
        .flush()
        .await?
        .expect("flush should produce an SSTable");

    assert_eq!(
        info.partition_count, 1,
        "all 10k clustering rows belong to one partition"
    );
    assert!(
        info.data_size > 0,
        "Data.db must be non-empty after flushing 10k rows"
    );

    engine.close().await?;
    Ok(())
}

/// Write a single row containing a list with 10,000 integer elements, then flush.
///
/// Validates collection serialization path under high element count.
#[tokio::test]
#[ignore] // Large-data test — run with: cargo test -- --ignored
async fn test_10k_element_list_roundtrip() -> cqlite_core::error::Result<()> {
    let temp_dir = TempDir::new().expect("failed to create temp dir");

    // Schema: my_list list<int>, pk int — columns sorted alphabetically
    let schema = simple_schema(
        "test_large",
        "list_10k",
        vec![("my_list", "list<int>"), ("pk", "int")],
        "pk",
    );

    let mut engine = create_engine(&temp_dir, schema);
    let table_id = TableId::new("test_large", "list_10k");

    let large_list = Value::List((0..10_000_i32).map(Value::Integer).collect());

    let pk = PartitionKey::single("pk", Value::Integer(1));
    let ops = vec![CellOperation::Write {
        column: "my_list".to_string(),
        value: large_list,
    }];
    let mutation = Mutation::new(table_id, pk, None, ops, 1_700_000_000_000_000, None);
    engine.write_async(mutation).await?;

    let info = engine
        .flush()
        .await?
        .expect("flush should produce an SSTable");

    assert_eq!(
        info.partition_count, 1,
        "single partition with 10k-element list"
    );

    engine.close().await?;
    Ok(())
}

/// Write a single row containing a set with 10,000 text elements, then flush.
///
/// Validates set serialization path under high element count.
#[tokio::test]
#[ignore] // Large-data test — run with: cargo test -- --ignored
async fn test_10k_element_set_roundtrip() -> cqlite_core::error::Result<()> {
    let temp_dir = TempDir::new().expect("failed to create temp dir");

    // Schema: my_set set<text>, pk int — columns sorted alphabetically
    let schema = simple_schema(
        "test_large",
        "set_10k",
        vec![("my_set", "set<text>"), ("pk", "int")],
        "pk",
    );

    let mut engine = create_engine(&temp_dir, schema);
    let table_id = TableId::new("test_large", "set_10k");

    let large_set = Value::Set(
        (0..10_000_i32)
            .map(|i| Value::Text(format!("item_{}", i)))
            .collect(),
    );

    let pk = PartitionKey::single("pk", Value::Integer(1));
    let ops = vec![CellOperation::Write {
        column: "my_set".to_string(),
        value: large_set,
    }];
    let mutation = Mutation::new(table_id, pk, None, ops, 1_700_000_000_000_000, None);
    engine.write_async(mutation).await?;

    let info = engine
        .flush()
        .await?
        .expect("flush should produce an SSTable");

    assert_eq!(
        info.partition_count, 1,
        "single partition with 10k-element set"
    );

    engine.close().await?;
    Ok(())
}

/// Write a single row containing a map with 10,000 entries, then flush.
///
/// Validates map serialization path under high element count.
#[tokio::test]
#[ignore] // Large-data test — run with: cargo test -- --ignored
async fn test_10k_element_map_roundtrip() -> cqlite_core::error::Result<()> {
    let temp_dir = TempDir::new().expect("failed to create temp dir");

    // Schema: my_map map<int, text>, pk int — columns sorted alphabetically
    let schema = simple_schema(
        "test_large",
        "map_10k",
        vec![("my_map", "map<int,text>"), ("pk", "int")],
        "pk",
    );

    let mut engine = create_engine(&temp_dir, schema);
    let table_id = TableId::new("test_large", "map_10k");

    let large_map = Value::Map(
        (0..10_000_i32)
            .map(|i| (Value::Integer(i), Value::Text(format!("val_{}", i))))
            .collect(),
    );

    let pk = PartitionKey::single("pk", Value::Integer(1));
    let ops = vec![CellOperation::Write {
        column: "my_map".to_string(),
        value: large_map,
    }];
    let mutation = Mutation::new(table_id, pk, None, ops, 1_700_000_000_000_000, None);
    engine.write_async(mutation).await?;

    let info = engine
        .flush()
        .await?
        .expect("flush should produce an SSTable");

    assert_eq!(
        info.partition_count, 1,
        "single partition with 10k-element map"
    );

    engine.close().await?;
    Ok(())
}

/// Write a single row containing a 10 MB blob value, then flush.
///
/// Validates large cell value encoding — the cell length VInt will require
/// multiple bytes (> 2^21), exercising the full VInt width.
#[tokio::test]
#[ignore] // Large-data test — run with: cargo test -- --ignored
async fn test_10mb_blob_roundtrip() -> cqlite_core::error::Result<()> {
    let temp_dir = TempDir::new().expect("failed to create temp dir");

    // Use a larger threshold so the 10MB blob doesn't trigger auto-flush
    let schema = simple_schema(
        "test_large",
        "blob_10mb",
        vec![("data", "blob"), ("pk", "int")],
        "pk",
    );

    let config = WriteEngineConfig::new(
        temp_dir.path().join("data"),
        temp_dir.path().join("wal"),
        schema,
    )
    .with_flush_threshold(256 * 1024 * 1024) // 256 MB
    .with_hard_limit(512 * 1024 * 1024); // 512 MB

    let mut engine = WriteEngine::new(config).expect("failed to create WriteEngine");
    let table_id = TableId::new("test_large", "blob_10mb");

    const BLOB_SIZE: usize = 10 * 1024 * 1024; // 10 MB
    let blob = Value::Blob(vec![0xAB_u8; BLOB_SIZE]);

    let pk = PartitionKey::single("pk", Value::Integer(1));
    let ops = vec![CellOperation::Write {
        column: "data".to_string(),
        value: blob,
    }];
    let mutation = Mutation::new(table_id, pk, None, ops, 1_700_000_000_000_000, None);
    engine.write_async(mutation).await?;

    let info = engine
        .flush()
        .await?
        .expect("flush should produce an SSTable");

    assert_eq!(info.partition_count, 1, "single partition with 10MB blob");
    assert!(
        info.data_size >= BLOB_SIZE as u64,
        "Data.db ({} bytes) must be at least as large as the raw blob ({} bytes)",
        info.data_size,
        BLOB_SIZE,
    );

    engine.close().await?;
    Ok(())
}

/// Write a single row across a 500-column wide schema, then flush.
///
/// Validates column bitmap encoding correctness when there are many regular
/// columns — the bitmap spans multiple bytes and must correctly mark present
/// vs. absent columns.
#[tokio::test]
#[ignore] // Large-data test — run with: cargo test -- --ignored
async fn test_500_columns_roundtrip() -> cqlite_core::error::Result<()> {
    let temp_dir = TempDir::new().expect("failed to create temp dir");

    // Build schema: pk int + col_000..col_499 text, sorted alphabetically.
    // "col_NNN" sorts before "pk" so pk comes last in the columns vec.
    // Build Column structs directly using owned strings to avoid lifetime issues.
    let mut col_structs: Vec<Column> = (0..500)
        .map(|i| Column {
            name: format!("col_{:03}", i),
            data_type: "text".to_string(),
            nullable: true,
            default: None,
            is_static: false,
        })
        .collect();
    // Add pk column
    col_structs.push(Column {
        name: "pk".to_string(),
        data_type: "int".to_string(),
        nullable: false,
        default: None,
        is_static: false,
    });
    // Sort alphabetically — "col_NNN" comes before "pk"
    col_structs.sort_by(|a, b| a.name.cmp(&b.name));

    let schema = TableSchema {
        keyspace: "test_large".to_string(),
        table: "wide_500".to_string(),
        partition_keys: vec![KeyColumn {
            name: "pk".to_string(),
            data_type: "int".to_string(),
            position: 0,
        }],
        clustering_keys: vec![],
        columns: col_structs,
        comments: HashMap::new(),
    };

    let mut engine = create_engine(&temp_dir, schema);
    let table_id = TableId::new("test_large", "wide_500");

    // Build 500 write operations — one per column.
    let ops: Vec<CellOperation> = (0..500)
        .map(|i| CellOperation::Write {
            column: format!("col_{:03}", i),
            value: Value::Text(format!("value_{}", i)),
        })
        .collect();

    let pk = PartitionKey::single("pk", Value::Integer(1));
    let mutation = Mutation::new(table_id, pk, None, ops, 1_700_000_000_000_000, None);
    engine.write_async(mutation).await?;

    let info = engine
        .flush()
        .await?
        .expect("flush should produce an SSTable");

    assert_eq!(info.partition_count, 1, "single partition with 500 columns");

    engine.close().await?;
    Ok(())
}

/// Write 1,000 partitions (distinct partition keys), then flush.
///
/// Validates that the Bloom filter is correctly sized for large partition
/// counts and that the Index.db / Summary.db are produced correctly.
#[tokio::test]
#[ignore] // Large-data test — run with: cargo test -- --ignored
async fn test_1000_partitions_roundtrip() -> cqlite_core::error::Result<()> {
    let temp_dir = TempDir::new().expect("failed to create temp dir");

    // Schema: pk int, value text — columns sorted alphabetically
    let schema = simple_schema(
        "test_large",
        "partitions_1k",
        vec![("pk", "int"), ("value", "text")],
        "pk",
    );

    let mut engine = create_engine(&temp_dir, schema);
    let table_id = TableId::new("test_large", "partitions_1k");
    let timestamp = 1_700_000_000_000_000_i64;

    for i in 0..1_000_i32 {
        let pk = PartitionKey::single("pk", Value::Integer(i));
        let ops = vec![CellOperation::Write {
            column: "value".to_string(),
            value: Value::Text(format!("partition_{}", i)),
        }];
        let mutation = Mutation::new(table_id.clone(), pk, None, ops, timestamp + i as i64, None);
        engine.write_async(mutation).await?;
    }

    let info = engine
        .flush()
        .await?
        .expect("flush should produce an SSTable");

    assert_eq!(
        info.partition_count, 1_000,
        "should have exactly 1,000 distinct partitions"
    );

    engine.close().await?;
    Ok(())
}