relay-knowledge 1.1.9

Graph-database-based knowledge graph project.
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
use rusqlite::{Connection, OptionalExtension, params};

use crate::storage::StorageError;

const SCHEMA_MARKER_KEY: &str = "sqlite_graph_store";
const SCHEMA_MARKER_VERSION: i64 = 3;
const GRAPH_BM25_COLUMNS: &[&str] = &[
    "document_id",
    "document_kind",
    "evidence_id",
    "parent_evidence_id",
    "modality",
    "created_graph_version",
    "source_scope",
    "source_path",
    "entity_labels",
    "entity_aliases",
    "content",
];
const GRAPH_SEMANTIC_COLUMNS: &[&str] = &[
    "document_id",
    "document_kind",
    "evidence_id",
    "parent_evidence_id",
    "modality",
    "created_graph_version",
    "source_scope",
    "source_path",
    "entity_labels_json",
    "content",
    "token_signature_json",
    "model",
    "dimension",
    "source_hash",
    "tokenizer_version",
];
const GRAPH_VECTOR_COLUMNS: &[&str] = &[
    "document_id",
    "document_kind",
    "evidence_id",
    "parent_evidence_id",
    "modality",
    "created_graph_version",
    "source_scope",
    "source_path",
    "entity_labels_json",
    "content",
    "vector_json",
    "model",
    "dimension",
    "source_hash",
    "tokenizer_version",
];
const GRAPH_BM25_LABEL_GRAM_COLUMNS: &[&str] = &[
    "document_id",
    "document_kind",
    "source_scope",
    "created_graph_version",
    "label",
    "label_lower",
    "label_len",
    "gram_size",
    "gram",
];
const CODE_WORKSPACE_PACKAGE_MAPPING_COLUMNS: &[&str] = &[
    "set_id",
    "package_name",
    "ecosystem",
    "repository_id",
    "source_scope",
    "workspace_format",
    "created_at_ms",
];
const CODE_WORKSPACE_PACKAGE_MAPPING_UNIQUE: &[&str] = &["set_id", "package_name", "ecosystem"];
const CODE_REPOSITORY_FILES_COLUMNS: &[&str] = &[
    "repository_id",
    "source_scope",
    "file_id",
    "path",
    "language_id",
    "blob_hash",
    "byte_len",
    "line_count",
    "parse_status",
    "is_generated",
    "degraded_reason",
];

pub(super) fn schema_initialization_is_current(
    connection: &Connection,
) -> Result<bool, StorageError> {
    if !schema_marker_table_exists(connection)? {
        return Ok(false);
    }
    let version = connection
        .query_row(
            "
            SELECT version
            FROM relay_storage_schema_state
            WHERE key = ?1
            ",
            params![SCHEMA_MARKER_KEY],
            |row| row.get::<_, i64>(0),
        )
        .optional()?;

    if version != Some(SCHEMA_MARKER_VERSION) {
        return Ok(false);
    }
    if !table_has_columns(connection, "graph_bm25", GRAPH_BM25_COLUMNS)?
        || !table_has_columns(
            connection,
            "graph_semantic_documents",
            GRAPH_SEMANTIC_COLUMNS,
        )?
        || !table_has_columns(connection, "graph_vector_documents", GRAPH_VECTOR_COLUMNS)?
        || !table_has_columns(
            connection,
            "graph_bm25_label_grams",
            GRAPH_BM25_LABEL_GRAM_COLUMNS,
        )?
        || !workspace_package_mappings_current(connection)?
        || !table_has_columns(
            connection,
            "relay_sqlite_maintenance_diagnostics",
            &["id", "last_maintenance_at_ms", "last_maintenance_error"],
        )?
        || !table_has_columns(
            connection,
            "code_repository_files",
            CODE_REPOSITORY_FILES_COLUMNS,
        )?
    {
        return Ok(false);
    }
    if !super::retrieval::derived_documents_current(connection)? {
        return Ok(false);
    }
    if !fact_evidence_links_are_current(connection)? {
        return Ok(false);
    }

    Ok(true)
}

pub(super) fn initialize_schema_marker(connection: &Connection) -> Result<(), StorageError> {
    connection.execute_batch(
        "
        CREATE TABLE IF NOT EXISTS relay_storage_schema_state (
            key TEXT PRIMARY KEY,
            version INTEGER NOT NULL,
            updated_at_ms INTEGER NOT NULL
        );
        ",
    )?;

    Ok(())
}

pub(super) fn mark_schema_initialization_current(
    connection: &Connection,
) -> Result<(), StorageError> {
    initialize_schema_marker(connection)?;
    connection.execute(
        "
        INSERT INTO relay_storage_schema_state (key, version, updated_at_ms)
        VALUES (?1, ?2, CAST(strftime('%s', 'now') AS INTEGER) * 1000)
        ON CONFLICT(key) DO UPDATE SET
            version = excluded.version,
            updated_at_ms = excluded.updated_at_ms
        ",
        params![SCHEMA_MARKER_KEY, SCHEMA_MARKER_VERSION],
    )?;

    Ok(())
}

fn schema_marker_table_exists(connection: &Connection) -> Result<bool, StorageError> {
    table_exists(connection, "relay_storage_schema_state")
}

fn table_has_columns(
    connection: &Connection,
    table: &str,
    required_columns: &[&str],
) -> Result<bool, StorageError> {
    if !table_exists(connection, table)? {
        return Ok(false);
    }
    let mut statement = connection.prepare(&format!("PRAGMA table_info({table})"))?;
    let rows = statement.query_map([], |row| row.get::<_, String>(1))?;
    let columns = rows
        .collect::<Result<Vec<_>, _>>()
        .map_err(StorageError::from)?;

    Ok(required_columns
        .iter()
        .all(|required| columns.iter().any(|column| column == required)))
}

fn workspace_package_mappings_current(connection: &Connection) -> Result<bool, StorageError> {
    if !table_has_columns(
        connection,
        "code_workspace_package_mappings",
        CODE_WORKSPACE_PACKAGE_MAPPING_COLUMNS,
    )? {
        return Ok(false);
    }
    table_has_unique_columns(
        connection,
        "code_workspace_package_mappings",
        CODE_WORKSPACE_PACKAGE_MAPPING_UNIQUE,
    )
}

fn table_has_unique_columns(
    connection: &Connection,
    table: &str,
    expected_columns: &[&str],
) -> Result<bool, StorageError> {
    let mut statement = connection.prepare(&format!("PRAGMA index_list({table})"))?;
    let rows = statement.query_map([], |row| {
        Ok((row.get::<_, String>(1)?, row.get::<_, i64>(2)? != 0))
    })?;
    let indexes = rows
        .collect::<Result<Vec<_>, _>>()
        .map_err(StorageError::from)?;

    for (index_name, unique) in indexes {
        if !unique {
            continue;
        }
        let mut statement = connection.prepare(&format!("PRAGMA index_info({index_name})"))?;
        let rows = statement.query_map([], |row| row.get::<_, String>(2))?;
        let columns = rows
            .collect::<Result<Vec<_>, _>>()
            .map_err(StorageError::from)?;
        if columns
            .iter()
            .map(String::as_str)
            .eq(expected_columns.iter().copied())
        {
            return Ok(true);
        }
    }

    Ok(false)
}

fn fact_evidence_links_are_current(connection: &Connection) -> Result<bool, StorageError> {
    if !table_exists(connection, "graph_fact_evidence")? {
        return Ok(false);
    }
    for (fact_kind, table) in [
        ("relation", "graph_relations"),
        ("claim", "graph_claims"),
        ("event", "graph_events"),
    ] {
        if !fact_evidence_links_are_current_for_kind(connection, fact_kind, table)? {
            return Ok(false);
        }
    }

    Ok(true)
}

fn fact_evidence_links_are_current_for_kind(
    connection: &Connection,
    fact_kind: &'static str,
    table: &'static str,
) -> Result<bool, StorageError> {
    if !table_exists(connection, table)? {
        return Ok(true);
    }
    let mut statement =
        connection.prepare(&format!("SELECT id, evidence_ids_json FROM {table}"))?;
    let rows = statement.query_map([], |row| {
        Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
    })?;
    let facts = rows
        .collect::<Result<Vec<_>, _>>()
        .map_err(StorageError::from)?;
    drop(statement);

    for (fact_id, evidence_json) in facts {
        let evidence_ids: Vec<String> = serde_json::from_str(&evidence_json)
            .map_err(|error| StorageError::InvalidInput(error.to_string()))?;
        for evidence_id in evidence_ids {
            if !fact_evidence_link_exists(connection, fact_kind, &fact_id, &evidence_id)? {
                return Ok(false);
            }
        }
    }

    Ok(true)
}

fn fact_evidence_link_exists(
    connection: &Connection,
    fact_kind: &str,
    fact_id: &str,
    evidence_id: &str,
) -> Result<bool, StorageError> {
    connection
        .query_row(
            "
            SELECT EXISTS (
                SELECT 1
                FROM graph_fact_evidence
                WHERE fact_kind = ?1
                  AND fact_id = ?2
                  AND evidence_id = ?3
            )
            ",
            params![fact_kind, fact_id, evidence_id],
            |row| row.get::<_, bool>(0),
        )
        .map_err(StorageError::from)
}

fn table_exists(connection: &Connection, table: &str) -> Result<bool, StorageError> {
    connection
        .query_row(
            "
            SELECT EXISTS (
                SELECT 1
                FROM sqlite_master
                WHERE type = 'table'
                  AND name = ?1
            )
            ",
            params![table],
            |row| row.get::<_, bool>(0),
        )
        .map_err(StorageError::from)
}

#[cfg(test)]
mod tests {
    use super::{mark_schema_initialization_current, schema_initialization_is_current};

    #[test]
    fn schema_marker_reports_current_only_after_successful_mark() {
        let store = super::super::SqliteGraphStore::open_in_memory().expect("store should open");
        let connection = store.connection.lock().expect("connection should lock");

        assert!(
            !schema_initialization_is_current(&connection)
                .expect("missing marker should be readable")
        );

        mark_schema_initialization_current(&connection).expect("marker should write");

        assert!(
            schema_initialization_is_current(&connection)
                .expect("current marker should be readable")
        );
    }

    #[test]
    fn schema_marker_requires_label_gram_table() {
        let store = super::super::SqliteGraphStore::open_in_memory().expect("store should open");
        let connection = store.connection.lock().expect("connection should lock");
        mark_schema_initialization_current(&connection).expect("marker should write");

        connection
            .execute("DROP TABLE graph_bm25_label_grams", [])
            .expect("label gram table should drop");

        assert!(
            !schema_initialization_is_current(&connection)
                .expect("missing label gram table should be detected")
        );
    }

    #[test]
    fn schema_marker_requires_workspace_mapping_ecosystem_unique_key() {
        let store = super::super::SqliteGraphStore::open_in_memory().expect("store should open");
        let connection = store.connection.lock().expect("connection should lock");
        mark_schema_initialization_current(&connection).expect("marker should write");
        connection
            .execute("DROP TABLE code_workspace_package_mappings", [])
            .expect("workspace mappings should drop");
        connection
            .execute_batch(
                "
                CREATE TABLE code_workspace_package_mappings (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    set_id TEXT NOT NULL,
                    package_name TEXT NOT NULL,
                    ecosystem TEXT NOT NULL,
                    repository_id TEXT NOT NULL,
                    source_scope TEXT NOT NULL,
                    workspace_format TEXT NOT NULL,
                    created_at_ms INTEGER NOT NULL,
                    UNIQUE (set_id, package_name)
                );
                ",
            )
            .expect("legacy workspace mappings should create");

        assert!(
            !schema_initialization_is_current(&connection)
                .expect("legacy workspace mapping uniqueness should be detected")
        );
    }

    #[test]
    fn schema_marker_rejects_previous_label_gram_migration_version() {
        let store = super::super::SqliteGraphStore::open_in_memory().expect("store should open");
        let connection = store.connection.lock().expect("connection should lock");
        super::initialize_schema_marker(&connection).expect("marker table should initialize");
        connection
            .execute(
                "
                INSERT INTO relay_storage_schema_state (key, version, updated_at_ms)
                VALUES ('sqlite_graph_store', 1, 0)
                ",
                [],
            )
            .expect("previous marker should insert");

        assert!(
            !schema_initialization_is_current(&connection)
                .expect("previous label gram migration marker should be stale")
        );
    }
}