Skip to main content

ragfs_store/
schema.rs

1//! Arrow schema definitions for `LanceDB` tables.
2
3use arrow_schema::{DataType, Field, Schema, TimeUnit};
4use serde::{Deserialize, Serialize};
5use std::sync::Arc;
6
7/// Current chunks table schema version.
8///
9/// Version 1: pre-scope columns (no `dir_path` / `dir_depth` / `path_components`).
10/// Version 2: directory-scope columns for `ragfs query --scope`.
11/// Version 3: source modality and nullable millisecond ranges.
12pub const CHUNKS_SCHEMA_VERSION: u32 = 3;
13
14/// Sidecar written beside the Lance database (`…/indices/<hash>/ragfs-schema.json`).
15pub const SCHEMA_SIDECAR_FILENAME: &str = "ragfs-schema.json";
16
17/// First assigned revision for a new or lazily migrated index.
18pub const INITIAL_INDEX_REVISION: u64 = 1;
19
20/// Persisted schema version for an existing Lance index.
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
22pub struct SchemaSidecar {
23    pub chunks_schema_version: u32,
24    /// Embedding width of the `vector` `FixedSizeList`, when known.
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub embedding_dim: Option<usize>,
27    /// Embedder model id that wrote this index, when known.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub embedding_model: Option<String>,
30    /// Alphanumeric floor used during indexing (absent on legacy indexes).
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub min_alnum_chars: Option<usize>,
33    /// A failed table rebuild must be retried explicitly before serving queries.
34    #[serde(default)]
35    pub rebuild_in_progress: bool,
36    /// Monotonic retrieval revision. Missing on pre-receipt indexes (`0`).
37    ///
38    /// This is sidecar metadata, not a Lance table schema change:
39    /// `CHUNKS_SCHEMA_VERSION` stays at 2. Old sidecars deserialize to `0`
40    /// and `init` persists [`INITIAL_INDEX_REVISION`] without rewriting tables.
41    #[serde(default)]
42    pub index_revision: u64,
43}
44
45impl Default for SchemaSidecar {
46    fn default() -> Self {
47        Self {
48            chunks_schema_version: CHUNKS_SCHEMA_VERSION,
49            embedding_dim: None,
50            embedding_model: None,
51            min_alnum_chars: None,
52            rebuild_in_progress: false,
53            index_revision: 0,
54        }
55    }
56}
57
58/// Treat `0` (missing / uninitialized) as the first persisted revision.
59#[must_use]
60pub fn effective_index_revision(stored: u64) -> u64 {
61    if stored == 0 {
62        INITIAL_INDEX_REVISION
63    } else {
64        stored
65    }
66}
67
68/// Scope columns missing from a pre-v2 chunks table (nullable so `add_columns` can fill nulls).
69#[must_use]
70pub fn missing_scope_columns(schema: &Schema) -> Vec<Field> {
71    let mut missing = Vec::new();
72    if schema.field_with_name("dir_path").is_err() {
73        missing.push(Field::new("dir_path", DataType::Utf8, true));
74    }
75    if schema.field_with_name("dir_depth").is_err() {
76        missing.push(Field::new("dir_depth", DataType::UInt16, true));
77    }
78    if schema.field_with_name("path_components").is_err() {
79        missing.push(Field::new("path_components", DataType::Utf8, true));
80    }
81    missing
82}
83
84/// Missing additive media columns. Legacy rows are backfilled to text/null/null.
85#[must_use]
86pub fn missing_media_columns(schema: &Schema) -> Vec<Field> {
87    [
88        ("modality", DataType::Utf8),
89        ("start_ms", DataType::UInt64),
90        ("end_ms", DataType::UInt64),
91    ]
92    .into_iter()
93    .filter(|(name, _)| schema.field_with_name(name).is_err())
94    .map(|(name, kind)| Field::new(name, kind, true))
95    .collect()
96}
97
98/// Schema for the chunks table.
99#[must_use]
100pub fn chunks_schema(embedding_dim: usize) -> Schema {
101    Schema::new(vec![
102        // Identity
103        Field::new("chunk_id", DataType::Utf8, false),
104        Field::new("file_id", DataType::Utf8, false),
105        Field::new("file_path", DataType::Utf8, false),
106        // Content
107        Field::new("content", DataType::Utf8, false),
108        Field::new("content_type", DataType::Utf8, false),
109        // Position
110        Field::new("chunk_index", DataType::UInt32, false),
111        Field::new("start_byte", DataType::UInt64, false),
112        Field::new("end_byte", DataType::UInt64, false),
113        Field::new("start_line", DataType::UInt32, true),
114        Field::new("end_line", DataType::UInt32, true),
115        // Hierarchy
116        Field::new("parent_chunk_id", DataType::Utf8, true),
117        Field::new("depth", DataType::UInt8, false),
118        // Embedding
119        Field::new(
120            "embedding",
121            DataType::FixedSizeList(
122                Arc::new(Field::new("item", DataType::Float32, true)),
123                embedding_dim as i32,
124            ),
125            false,
126        ),
127        // Metadata
128        Field::new("embedding_model", DataType::Utf8, true),
129        Field::new(
130            "indexed_at",
131            DataType::Timestamp(TimeUnit::Millisecond, None),
132            false,
133        ),
134        // File metadata (denormalized)
135        Field::new("file_mime_type", DataType::Utf8, true),
136        Field::new("file_size_bytes", DataType::UInt64, true),
137        // Code-specific
138        Field::new("language", DataType::Utf8, true),
139        Field::new("symbol_type", DataType::Utf8, true),
140        Field::new("symbol_name", DataType::Utf8, true),
141        Field::new("dir_path", DataType::Utf8, false),
142        Field::new("dir_depth", DataType::UInt16, false),
143        Field::new("path_components", DataType::Utf8, false),
144        Field::new("modality", DataType::Utf8, true),
145        Field::new("start_ms", DataType::UInt64, true),
146        Field::new("end_ms", DataType::UInt64, true),
147    ])
148}
149
150/// Schema for the files metadata table.
151#[must_use]
152pub fn files_schema() -> Schema {
153    Schema::new(vec![
154        Field::new("file_id", DataType::Utf8, false),
155        Field::new("path", DataType::Utf8, false),
156        Field::new("size_bytes", DataType::UInt64, false),
157        Field::new("mime_type", DataType::Utf8, false),
158        Field::new("content_hash", DataType::Utf8, false),
159        Field::new(
160            "modified_at",
161            DataType::Timestamp(TimeUnit::Millisecond, None),
162            false,
163        ),
164        Field::new(
165            "indexed_at",
166            DataType::Timestamp(TimeUnit::Millisecond, None),
167            true,
168        ),
169        Field::new("chunk_count", DataType::UInt32, false),
170        Field::new("status", DataType::Utf8, false),
171        Field::new("error_message", DataType::Utf8, true),
172    ])
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn test_missing_scope_columns_on_v1_schema() {
181        let v1 = Schema::new(vec![Field::new("file_path", DataType::Utf8, false)]);
182        let missing = missing_scope_columns(&v1);
183        assert_eq!(missing.len(), 3);
184        assert_eq!(missing[0].name(), "dir_path");
185        assert_eq!(missing[1].name(), "dir_depth");
186        assert_eq!(missing[2].name(), "path_components");
187        assert!(missing.iter().all(Field::is_nullable));
188    }
189
190    #[test]
191    fn test_missing_scope_columns_on_v2_schema() {
192        let v2 = chunks_schema(384);
193        assert!(missing_scope_columns(&v2).is_empty());
194    }
195
196    #[test]
197    fn old_sidecar_deserializes_without_embedding_fields() {
198        let s: SchemaSidecar = serde_json::from_str(r#"{"chunks_schema_version":2}"#).unwrap();
199        assert_eq!(s.chunks_schema_version, 2);
200        assert_eq!(s.embedding_dim, None);
201        assert_eq!(s.embedding_model, None);
202        assert_eq!(s.index_revision, 0);
203        assert_eq!(
204            effective_index_revision(s.index_revision),
205            INITIAL_INDEX_REVISION
206        );
207    }
208
209    #[test]
210    fn old_sidecar_deserialization_preserves_recorded_version() {
211        let s: SchemaSidecar = serde_json::from_str(r#"{"chunks_schema_version":2}"#).unwrap();
212        assert_eq!(s.chunks_schema_version, 2);
213    }
214
215    #[test]
216    fn sidecar_round_trips_index_revision() {
217        let original = SchemaSidecar {
218            chunks_schema_version: CHUNKS_SCHEMA_VERSION,
219            embedding_dim: Some(384),
220            embedding_model: Some("thenlper/gte-small".into()),
221            index_revision: 7,
222            min_alnum_chars: Some(3),
223            rebuild_in_progress: false,
224        };
225        let json = serde_json::to_string(&original).unwrap();
226        let parsed: SchemaSidecar = serde_json::from_str(&json).unwrap();
227        assert_eq!(parsed, original);
228        assert!(json.contains("\"index_revision\":7"));
229    }
230}