sochdb 2.0.11

SochDB - LLM-optimized database with native vector search
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// SochDB - LLM-Optimized Embedded Database
// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Unified Output Format Semantics (Task 3)
//!
//! This module provides a single taxonomy for output formats with:
//! - Clear layer boundaries (WireFormat vs ContextFormat)
//! - No lossy coercions (round-trip property preserved)
//! - Explicit conversion with error handling
//!
//! ## Problem Solved
//!
//! Previously, there were two competing format universes:
//! - Client: Soch | Json | Columnar
//! - Context: Soch | Json | Markdown | Text (with Text -> Soch coercion)
//!
//! This created semantic drift and violated the round-trip property:
//! `decode(encode(x)) = x` should hold for all formats.
//!
//! ## Solution
//!
//! Separate format enums with explicit conversions:
//! - `WireFormat`: For query results sent to clients
//! - `ContextFormat`: For LLM context packaging
//!
//! Conversions between them use `TryFrom` and can fail, making
//! incompatibilities explicit rather than silent.

use std::fmt;

/// Error when format conversion fails
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatConversionError {
    pub from: String,
    pub to: String,
    pub reason: String,
}

impl fmt::Display for FormatConversionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Cannot convert {} to {}: {}",
            self.from, self.to, self.reason
        )
    }
}

impl std::error::Error for FormatConversionError {}

// ============================================================================
// Wire Format (Query Results)
// ============================================================================

/// Output format for query results sent to clients.
///
/// These formats are optimized for transmission efficiency and
/// client-side processing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WireFormat {
    /// TOON format (default, 40-66% fewer tokens than JSON)
    /// Optimized for LLM consumption.
    Soch,

    /// Standard JSON for compatibility
    Json,

    /// Raw columnar format for analytics
    /// More efficient for large result sets with projection pushdown.
    Columnar,
}

impl Default for WireFormat {
    fn default() -> Self {
        Self::Soch
    }
}

impl fmt::Display for WireFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Soch => write!(f, "toon"),
            Self::Json => write!(f, "json"),
            Self::Columnar => write!(f, "columnar"),
        }
    }
}

impl std::str::FromStr for WireFormat {
    type Err = FormatConversionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "toon" => Ok(Self::Soch),
            "json" => Ok(Self::Json),
            "columnar" | "column" => Ok(Self::Columnar),
            _ => Err(FormatConversionError {
                from: s.to_string(),
                to: "WireFormat".to_string(),
                reason: format!("Unknown format '{}'. Valid: toon, json, columnar", s),
            }),
        }
    }
}

// ============================================================================
// Context Format (LLM Context Packaging)
// ============================================================================

/// Output format for LLM context packaging.
///
/// These formats are optimized for readability and token efficiency
/// when constructing prompts for language models.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ContextFormat {
    /// TOON format (default, token-efficient)
    /// Structured data with minimal syntax overhead.
    Soch,

    /// JSON format
    /// Widely understood by LLMs, good for structured data.
    Json,

    /// Markdown format
    /// Best for human-readable context with formatting.
    Markdown,
}

impl Default for ContextFormat {
    fn default() -> Self {
        Self::Soch
    }
}

impl fmt::Display for ContextFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Soch => write!(f, "toon"),
            Self::Json => write!(f, "json"),
            Self::Markdown => write!(f, "markdown"),
        }
    }
}

impl std::str::FromStr for ContextFormat {
    type Err = FormatConversionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "toon" => Ok(Self::Soch),
            "json" => Ok(Self::Json),
            "markdown" | "md" => Ok(Self::Markdown),
            // NOTE: "text" is NOT supported - it was previously coerced to Soch
            // which violated the round-trip property. Use Markdown for plain text.
            "text" | "plain" => Err(FormatConversionError {
                from: s.to_string(),
                to: "ContextFormat".to_string(),
                reason: "Plain text format is not supported. Use 'markdown' for \
                        human-readable output or 'toon' for LLM-optimized output."
                    .to_string(),
            }),
            _ => Err(FormatConversionError {
                from: s.to_string(),
                to: "ContextFormat".to_string(),
                reason: format!("Unknown format '{}'. Valid: toon, json, markdown", s),
            }),
        }
    }
}

// ============================================================================
// Format Conversions
// ============================================================================

/// Convert WireFormat to ContextFormat (where possible)
impl TryFrom<WireFormat> for ContextFormat {
    type Error = FormatConversionError;

    fn try_from(wire: WireFormat) -> Result<Self, Self::Error> {
        match wire {
            WireFormat::Soch => Ok(ContextFormat::Soch),
            WireFormat::Json => Ok(ContextFormat::Json),
            WireFormat::Columnar => Err(FormatConversionError {
                from: "Columnar".to_string(),
                to: "ContextFormat".to_string(),
                reason: "Columnar format is for analytics, not LLM context. \
                        Convert to Soch or Json first."
                    .to_string(),
            }),
        }
    }
}

/// Convert ContextFormat to WireFormat (always succeeds)
impl From<ContextFormat> for WireFormat {
    fn from(ctx: ContextFormat) -> Self {
        match ctx {
            ContextFormat::Soch => WireFormat::Soch,
            ContextFormat::Json => WireFormat::Json,
            ContextFormat::Markdown => WireFormat::Soch, // Markdown renders to Soch structure
        }
    }
}

// ============================================================================
// Format Capabilities
// ============================================================================

/// Capabilities of a format
#[derive(Debug, Clone)]
pub struct FormatCapabilities {
    /// Supports structured data (tables, objects)
    pub structured: bool,
    /// Supports nested data
    pub nested: bool,
    /// Supports binary data (via encoding)
    pub binary: bool,
    /// Supports streaming
    pub streaming: bool,
    /// Typical token efficiency vs JSON (1.0 = same, 0.5 = half the tokens)
    pub token_efficiency: f32,
}

impl WireFormat {
    /// Get the capabilities of this format
    pub fn capabilities(&self) -> FormatCapabilities {
        match self {
            Self::Soch => FormatCapabilities {
                structured: true,
                nested: true,
                binary: true,
                streaming: true,
                token_efficiency: 0.4, // 40% of JSON tokens
            },
            Self::Json => FormatCapabilities {
                structured: true,
                nested: true,
                binary: false, // Requires base64
                streaming: true,
                token_efficiency: 1.0,
            },
            Self::Columnar => FormatCapabilities {
                structured: true,
                nested: false,
                binary: true,
                streaming: true,
                token_efficiency: 0.3, // Very efficient for tabular data
            },
        }
    }
}

impl ContextFormat {
    /// Get the capabilities of this format
    pub fn capabilities(&self) -> FormatCapabilities {
        match self {
            Self::Soch => FormatCapabilities {
                structured: true,
                nested: true,
                binary: true,
                streaming: true,
                token_efficiency: 0.4,
            },
            Self::Json => FormatCapabilities {
                structured: true,
                nested: true,
                binary: false,
                streaming: true,
                token_efficiency: 1.0,
            },
            Self::Markdown => FormatCapabilities {
                structured: true, // Tables, lists
                nested: true,     // Nested lists
                binary: false,
                streaming: true,
                token_efficiency: 0.7, // Less overhead than JSON
            },
        }
    }

    /// Get the recommended format for a given use case
    pub fn recommended_for_llm() -> Self {
        Self::Soch
    }

    pub fn recommended_for_human() -> Self {
        Self::Markdown
    }

    pub fn recommended_for_api() -> Self {
        Self::Json
    }
}

// ============================================================================
// Canonical AST Representation
// ============================================================================

/// Canonical format identifier for AST nodes.
///
/// This is the internal representation used in the query AST.
/// It preserves the user's intent exactly without lossy coercions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CanonicalFormat {
    /// Context format for LLM output
    Context(ContextFormat),
    /// Wire format for query results
    Wire(WireFormat),
}

impl CanonicalFormat {
    /// Get the format name for display
    pub fn name(&self) -> &'static str {
        match self {
            Self::Context(ContextFormat::Soch) => "context:toon",
            Self::Context(ContextFormat::Json) => "context:json",
            Self::Context(ContextFormat::Markdown) => "context:markdown",
            Self::Wire(WireFormat::Soch) => "wire:toon",
            Self::Wire(WireFormat::Json) => "wire:json",
            Self::Wire(WireFormat::Columnar) => "wire:columnar",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_wire_format_parsing() {
        assert_eq!("toon".parse::<WireFormat>().unwrap(), WireFormat::Soch);
        assert_eq!("json".parse::<WireFormat>().unwrap(), WireFormat::Json);
        assert_eq!(
            "columnar".parse::<WireFormat>().unwrap(),
            WireFormat::Columnar
        );
        assert!("invalid".parse::<WireFormat>().is_err());
    }

    #[test]
    fn test_context_format_parsing() {
        assert_eq!(
            "toon".parse::<ContextFormat>().unwrap(),
            ContextFormat::Soch
        );
        assert_eq!(
            "json".parse::<ContextFormat>().unwrap(),
            ContextFormat::Json
        );
        assert_eq!(
            "markdown".parse::<ContextFormat>().unwrap(),
            ContextFormat::Markdown
        );

        // "text" should fail - no more silent coercion to Soch
        assert!("text".parse::<ContextFormat>().is_err());
    }

    #[test]
    fn test_wire_to_context_conversion() {
        assert_eq!(
            ContextFormat::try_from(WireFormat::Soch).unwrap(),
            ContextFormat::Soch
        );
        assert_eq!(
            ContextFormat::try_from(WireFormat::Json).unwrap(),
            ContextFormat::Json
        );

        // Columnar cannot convert to ContextFormat
        assert!(ContextFormat::try_from(WireFormat::Columnar).is_err());
    }

    #[test]
    fn test_context_to_wire_conversion() {
        assert_eq!(WireFormat::from(ContextFormat::Soch), WireFormat::Soch);
        assert_eq!(WireFormat::from(ContextFormat::Json), WireFormat::Json);
        assert_eq!(WireFormat::from(ContextFormat::Markdown), WireFormat::Soch);
    }

    #[test]
    fn test_round_trip_property() {
        // This test verifies the core requirement:
        // Converting to string and back should preserve the format

        for format in [WireFormat::Soch, WireFormat::Json, WireFormat::Columnar] {
            let s = format.to_string();
            let parsed: WireFormat = s.parse().unwrap();
            assert_eq!(
                format, parsed,
                "Round-trip failed for WireFormat::{:?}",
                format
            );
        }

        for format in [
            ContextFormat::Soch,
            ContextFormat::Json,
            ContextFormat::Markdown,
        ] {
            let s = format.to_string();
            let parsed: ContextFormat = s.parse().unwrap();
            assert_eq!(
                format, parsed,
                "Round-trip failed for ContextFormat::{:?}",
                format
            );
        }
    }
}