icydb-core 0.158.12

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
496
497
498
499
500
501
502
503
504
505
506
//! Startup expression-index schema mutation adapter.
//!
//! This module mirrors the field-path DDL publication boundary while keeping
//! expression-index key construction on accepted mutation targets.

use crate::{
    db::{
        data::{DataKey, RawRow, StructuralRowContract},
        index::{IndexId, IndexKey, IndexState, IndexStore, RawIndexKey},
        predicate::{PredicateProgram, normalize, parse_sql_predicate},
        registry::StoreHandle,
        schema::{
            AcceptedSchemaSnapshot, PersistedSchemaSnapshot, SchemaExpressionIndexRebuildRow,
            SchemaExpressionIndexRebuildTarget, SchemaExpressionIndexStagedEntry,
            SchemaExpressionIndexStagedRebuild, SchemaMutationExecutionStep,
            SchemaMutationRunnerInput, SchemaTransitionPlanKind, transition::SchemaTransitionPlan,
        },
    },
    error::InternalError,
    types::EntityTag,
};
use sha2::{Digest, Sha256};

use super::startup_field_path::{
    StartupDecodedFieldPathRebuildRow, StartupFieldPathRebuildRow, decode_field_path_rebuild_rows,
    field_path_rebuild_raw_rows_for_entity,
};

pub(super) fn execute_supported_expression_index_addition(
    store: StoreHandle,
    entity_tag: EntityTag,
    entity_path: &'static str,
    accepted_before: &PersistedSchemaSnapshot,
    accepted_after: &PersistedSchemaSnapshot,
    plan: &SchemaTransitionPlan,
    target: &SchemaExpressionIndexRebuildTarget,
) -> Result<(usize, usize), InternalError> {
    if plan.kind() != SchemaTransitionPlanKind::AddExpressionIndex {
        return Err(InternalError::store_unsupported(format!(
            "schema mutation expression-index execution rejected for entity '{entity_path}': plan_kind={:?}",
            plan.kind(),
        )));
    }
    validate_expression_execution_plan(plan, target, entity_path)?;
    let input =
        SchemaMutationRunnerInput::new(accepted_before, accepted_after, plan.execution_plan())
            .map_err(|error| {
                InternalError::store_unsupported(format!(
                    "schema mutation expression-index runner input rejected for entity '{entity_path}': error={error:?}",
                ))
            })?;
    let accepted = AcceptedSchemaSnapshot::try_new(accepted_before.clone())?;
    let row_contract =
        StructuralRowContract::from_accepted_schema_snapshot(entity_path, &accepted)?;
    let predicate_program = expression_rebuild_predicate_program(target, &row_contract)?;
    let raw_rows = field_path_rebuild_raw_rows_for_entity(store, entity_tag, entity_path)?;
    let rebuild_gate = StartupExpressionRebuildGate::from_raw_rows(
        entity_tag,
        entity_path,
        accepted_before,
        raw_rows.as_slice(),
    )?;
    let rows =
        decode_field_path_rebuild_rows(raw_rows.as_slice(), entity_tag, entity_path, row_contract)?;
    rebuild_gate.validate_before_physical_work(store, rows.len())?;

    let (rows_scanned, index_keys_written) = store.with_index_mut(|index_store| {
        execute_expression_index_store_mutation(
            index_store,
            entity_tag,
            entity_path,
            target,
            predicate_program.as_ref(),
            rows.as_slice(),
            &input,
        )
    })?;
    rebuild_gate.validate_before_schema_publication(store, rows_scanned)?;
    validate_expression_physical_store_before_schema_publication(
        store,
        entity_tag,
        entity_path,
        target,
        index_keys_written,
    )?;
    store.with_schema_mut(|schema_store| {
        schema_store.insert_persisted_snapshot(entity_tag, accepted_after)
    })?;

    Ok((rows_scanned, index_keys_written))
}

fn validate_expression_execution_plan(
    plan: &SchemaTransitionPlan,
    target: &SchemaExpressionIndexRebuildTarget,
    entity_path: &'static str,
) -> Result<(), InternalError> {
    let execution_plan = plan.execution_plan();
    let [
        SchemaMutationExecutionStep::BuildExpressionIndex {
            target: planned_target,
        },
        SchemaMutationExecutionStep::ValidatePhysicalWork,
        SchemaMutationExecutionStep::InvalidateRuntimeState,
    ] = execution_plan.steps()
    else {
        return Err(InternalError::store_unsupported(format!(
            "schema mutation expression-index execution rejected unsupported plan shape for entity '{entity_path}'",
        )));
    };
    if planned_target != target {
        return Err(InternalError::store_unsupported(format!(
            "schema mutation expression-index execution target drifted for entity '{entity_path}': prepared='{}' actual='{}'",
            target.name(),
            planned_target.name(),
        )));
    }

    Ok(())
}

fn expression_rebuild_predicate_program(
    target: &SchemaExpressionIndexRebuildTarget,
    row_contract: &StructuralRowContract,
) -> Result<Option<PredicateProgram>, InternalError> {
    let Some(predicate_sql) = target.predicate_sql() else {
        return Ok(None);
    };
    let predicate = parse_sql_predicate(predicate_sql).map_err(|error| {
        InternalError::store_unsupported(format!(
            "schema mutation expression rebuild predicate failed to parse for target '{}': {error}",
            target.name(),
        ))
    })?;

    Ok(Some(PredicateProgram::compile_with_row_contract(
        row_contract,
        &normalize(&predicate),
    )))
}

fn execute_expression_index_store_mutation(
    index_store: &mut IndexStore,
    entity_tag: EntityTag,
    entity_path: &'static str,
    target: &SchemaExpressionIndexRebuildTarget,
    predicate_program: Option<&PredicateProgram>,
    rows: &[StartupDecodedFieldPathRebuildRow<'_>],
    input: &SchemaMutationRunnerInput<'_>,
) -> Result<(usize, usize), InternalError> {
    if index_store.state() != IndexState::Ready {
        return Err(InternalError::store_unsupported(format!(
            "schema mutation expression-index rebuild requires a ready physical index store before rebuild for entity '{entity_path}': target_index={} index_state={}",
            target.name(),
            index_store.state().as_str(),
        )));
    }
    let target_index_id = IndexId::new(entity_tag, target.ordinal());
    let preflight =
        expression_startup_index_store_preflight(index_store, entity_tag, target, entity_path)?;
    if preflight.target != 0 {
        return Err(InternalError::store_unsupported(format!(
            "schema mutation expression-index rebuild requires an empty target physical index for entity '{entity_path}': target_index={} target_index_entries={} other_index_entries={} total_entries={}",
            target.name(),
            preflight.target,
            preflight.other,
            preflight.total,
        )));
    }

    let rebuild_rows = rows
        .iter()
        .map(|row| SchemaExpressionIndexRebuildRow::new(row.storage_key, &row.slots));
    let staged = SchemaExpressionIndexStagedRebuild::from_rows(
        input.accepted_after().entity_path(),
        entity_tag,
        target.clone(),
        predicate_program,
        rebuild_rows,
    )?;
    let validation = staged.validate().map_err(|error| {
        InternalError::store_unsupported(format!(
            "schema mutation expression-index staged validation failed for entity '{entity_path}': target_index={} error={error:?}",
            target.name(),
        ))
    })?;

    index_store.mark_building();
    for entry in staged.entries() {
        index_store.insert(entry.key().clone(), entry.entry().clone());
    }
    validate_expression_index_store_batch(
        index_store,
        entity_path,
        target,
        &target_index_id,
        staged.entries(),
    )?;
    index_store.mark_ready();

    Ok((validation.source_rows(), validation.entry_count()))
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct StartupExpressionIndexStorePreflight {
    target: u64,
    other: u64,
    total: u64,
}

fn expression_startup_index_store_preflight(
    index_store: &IndexStore,
    entity_tag: EntityTag,
    target: &SchemaExpressionIndexRebuildTarget,
    entity_path: &'static str,
) -> Result<StartupExpressionIndexStorePreflight, InternalError> {
    let target_index_id = IndexId::new(entity_tag, target.ordinal());
    let mut preflight = StartupExpressionIndexStorePreflight {
        target: 0,
        other: 0,
        total: 0,
    };

    for (raw_key, _) in index_store.entries() {
        let index_key = IndexKey::try_from_raw(&raw_key).map_err(|error| {
            InternalError::store_corruption(format!(
                "schema mutation expression-index key decode failed for entity '{entity_path}' while preflighting target index '{}': {error}",
                target.name(),
            ))
        })?;
        if *index_key.index_id() == target_index_id {
            preflight.target += 1;
        } else {
            preflight.other += 1;
        }
        preflight.total += 1;
    }

    Ok(preflight)
}

fn validate_expression_index_store_batch(
    index_store: &IndexStore,
    entity_path: &'static str,
    target: &SchemaExpressionIndexRebuildTarget,
    target_index_id: &IndexId,
    entries: &[SchemaExpressionIndexStagedEntry],
) -> Result<(), InternalError> {
    if index_store.state() != IndexState::Building {
        return Err(InternalError::store_unsupported(format!(
            "schema mutation expression-index validation requires a building index store for entity '{entity_path}': target_index={} index_state={}",
            target.name(),
            index_store.state().as_str(),
        )));
    }
    let expected_entry_count = u64::try_from(entries.len()).map_err(|_| {
        InternalError::store_unsupported(format!(
            "schema mutation expression-index produced too many entries for entity '{entity_path}': target_index={}",
            target.name(),
        ))
    })?;
    let actual_entry_count =
        expression_target_index_entry_count(index_store, target_index_id, entity_path, target)?;
    if actual_entry_count != expected_entry_count {
        return Err(InternalError::store_unsupported(format!(
            "schema mutation expression-index entry count mismatch for entity '{entity_path}': target_index={} expected={} actual={actual_entry_count}",
            target.name(),
            expected_entry_count,
        )));
    }
    for entry in entries {
        let index_key = IndexKey::try_from_raw(entry.key()).map_err(|error| {
            InternalError::store_corruption(format!(
                "schema mutation expression-index key decode failed for entity '{entity_path}' while validating target index '{}': {error}",
                target.name(),
            ))
        })?;
        if index_key.index_id() != target_index_id {
            return Err(InternalError::store_unsupported(format!(
                "schema mutation expression-index target mismatch for entity '{entity_path}': target_index={}",
                target.name(),
            )));
        }
        let Some(index_entry) = index_store.get(entry.key()) else {
            return Err(InternalError::store_unsupported(format!(
                "schema mutation expression-index missing written entry for entity '{entity_path}': target_index={}",
                target.name(),
            )));
        };
        if index_entry != *entry.entry() {
            return Err(InternalError::store_unsupported(format!(
                "schema mutation expression-index written entry mismatch for entity '{entity_path}': target_index={}",
                target.name(),
            )));
        }
    }

    Ok(())
}

fn validate_expression_physical_store_before_schema_publication(
    store: StoreHandle,
    entity_tag: EntityTag,
    entity_path: &'static str,
    target: &SchemaExpressionIndexRebuildTarget,
    expected_entries: usize,
) -> Result<(), InternalError> {
    store.with_index(|index_store| {
        if index_store.state() != IndexState::Ready {
            return Err(InternalError::store_unsupported(format!(
                "schema mutation expression-index publication requires a ready physical index store for entity '{entity_path}': target_index={} index_state={}",
                target.name(),
                index_store.state().as_str(),
            )));
        }
        let target_index_id = IndexId::new(entity_tag, target.ordinal());
        let actual = expression_target_index_entry_count(
            index_store,
            &target_index_id,
            entity_path,
            target,
        )?;
        let expected = u64::try_from(expected_entries).map_err(|_| {
            InternalError::store_unsupported(format!(
                "schema mutation expression-index expected-entry count is unpublishable for entity '{entity_path}': target_index={}",
                target.name(),
            ))
        })?;
        if actual == expected {
            return Ok(());
        }

        Err(InternalError::store_unsupported(format!(
            "schema mutation expression-index physical store changed before schema publication for entity '{entity_path}': target_index={} expected_entries={expected} actual_entries={actual}",
            target.name(),
        )))
    })
}

fn expression_target_index_entry_count(
    index_store: &IndexStore,
    target_index_id: &IndexId,
    entity_path: &'static str,
    target: &SchemaExpressionIndexRebuildTarget,
) -> Result<u64, InternalError> {
    let mut count = 0u64;
    for (raw_key, _) in index_store.entries() {
        if expression_key_targets_index(&raw_key, target_index_id, entity_path, target)? {
            count += 1;
        }
    }

    Ok(count)
}

fn expression_key_targets_index(
    raw_key: &RawIndexKey,
    target_index_id: &IndexId,
    entity_path: &'static str,
    target: &SchemaExpressionIndexRebuildTarget,
) -> Result<bool, InternalError> {
    let index_key = IndexKey::try_from_raw(raw_key).map_err(|error| {
        InternalError::store_corruption(format!(
            "schema mutation expression-index key decode failed for entity '{entity_path}' while counting target index '{}': {error}",
            target.name(),
        ))
    })?;

    Ok(index_key.index_id() == target_index_id)
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct StartupExpressionRebuildRowFingerprint {
    rows: usize,
    digest: [u8; 32],
}

impl StartupExpressionRebuildRowFingerprint {
    const fn new(rows: usize, digest: [u8; 32]) -> Self {
        Self { rows, digest }
    }

    const fn rows(&self) -> usize {
        self.rows
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct StartupExpressionRebuildGate {
    entity_tag: EntityTag,
    entity_path: &'static str,
    accepted_before: PersistedSchemaSnapshot,
    row_fingerprint: StartupExpressionRebuildRowFingerprint,
}

impl StartupExpressionRebuildGate {
    fn from_raw_rows(
        entity_tag: EntityTag,
        entity_path: &'static str,
        accepted_before: &PersistedSchemaSnapshot,
        rows: &[StartupFieldPathRebuildRow],
    ) -> Result<Self, InternalError> {
        Ok(Self {
            entity_tag,
            entity_path,
            accepted_before: accepted_before.clone(),
            row_fingerprint: expression_rebuild_row_fingerprint_from_rows(entity_tag, rows)?,
        })
    }

    fn validate_before_physical_work(
        &self,
        store: StoreHandle,
        rows_scanned: usize,
    ) -> Result<(), InternalError> {
        self.validate_current_state(store, rows_scanned, "before physical work")
    }

    fn validate_before_schema_publication(
        &self,
        store: StoreHandle,
        rows_scanned: usize,
    ) -> Result<(), InternalError> {
        self.validate_current_state(store, rows_scanned, "before schema publication")
    }

    fn validate_current_state(
        &self,
        store: StoreHandle,
        rows_scanned: usize,
        boundary: &'static str,
    ) -> Result<(), InternalError> {
        let current =
            expression_rebuild_row_fingerprint_for_store(store, self.entity_tag, self.entity_path)?;
        if current != self.row_fingerprint {
            return Err(InternalError::store_unsupported(format!(
                "schema mutation expression-index rebuild lost exclusive row gate {boundary} for entity '{}': expected_rows={} actual_rows={} rows_scanned={rows_scanned}",
                self.entity_path,
                self.row_fingerprint.rows(),
                current.rows(),
            )));
        }

        let latest = store.with_schema_mut(|schema_store| {
            schema_store.latest_persisted_snapshot(self.entity_tag)
        })?;
        if latest.as_ref() != Some(&self.accepted_before) {
            return Err(InternalError::store_unsupported(format!(
                "schema mutation expression-index rebuild lost exclusive schema gate {boundary} for entity '{}'",
                self.entity_path,
            )));
        }

        Ok(())
    }
}

fn expression_rebuild_row_fingerprint_from_rows(
    entity_tag: EntityTag,
    rows: &[StartupFieldPathRebuildRow],
) -> Result<StartupExpressionRebuildRowFingerprint, InternalError> {
    let mut hasher = Sha256::new();
    for row in rows {
        let raw_key = DataKey::new(entity_tag, row.storage_key).to_raw()?;
        hash_expression_rebuild_row(&mut hasher, raw_key.as_bytes(), &row.row);
    }

    Ok(StartupExpressionRebuildRowFingerprint::new(
        rows.len(),
        hasher.finalize().into(),
    ))
}

fn expression_rebuild_row_fingerprint_for_store(
    store: StoreHandle,
    entity_tag: EntityTag,
    entity_path: &'static str,
) -> Result<StartupExpressionRebuildRowFingerprint, InternalError> {
    store.with_data(|data_store| {
        let mut rows = 0usize;
        let mut hasher = Sha256::new();
        for entry in data_store.entries() {
            let data_key = DataKey::try_from_raw(entry.key()).map_err(|error| {
                InternalError::store_corruption(format!(
                    "schema mutation expression-index data key decode failed for entity '{entity_path}' while validating startup rebuild gate: {error}",
                ))
            })?;
            if data_key.entity_tag() != entity_tag {
                continue;
            }
            rows += 1;
            hash_expression_rebuild_row(&mut hasher, entry.key().as_bytes(), &entry.value());
        }

        Ok(StartupExpressionRebuildRowFingerprint::new(
            rows,
            hasher.finalize().into(),
        ))
    })
}

fn hash_expression_rebuild_row(hasher: &mut Sha256, raw_key: &[u8], row: &RawRow) {
    hasher.update(raw_key);
    hasher.update((row.len() as u64).to_be_bytes());
    hasher.update(row.as_bytes());
}