brainwires-storage 0.9.0

Backend-agnostic storage, tiered memory, and document management for the Brainwires Agent Framework
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Pinecone managed cloud vector database backend.
//!
//! [`PineconeDatabase`] implements [`VectorDatabase`] for use with Pinecone's
//! cloud-hosted vector search service.
//!
//! # Feature flag
//!
//! Requires `pinecone-backend`.
//!
//! # Configuration
//!
//! Requires a Pinecone API key and an index host URL. The index must already
//! exist in the Pinecone console — this backend does **not** create indexes
//! automatically.
//!
//! ```ignore
//! let db = PineconeDatabase::new(
//!     "https://my-index-abc1234.svc.us-east-1-aws.pinecone.io",
//!     "pcsk_...",
//!     "my-namespace",
//! );
//! db.initialize(384).await?;
//! ```

use anyhow::{Context, Result, bail};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::RwLock;

use crate::databases::traits::{ChunkMetadata, DatabaseStats, SearchResult, VectorDatabase};

/// Pinecone REST API vector database client.
///
/// Implements [`VectorDatabase`] only (no [`StorageBackend`] — Pinecone is a
/// pure vector store with no relational query support).
pub struct PineconeDatabase {
    /// Base URL of the Pinecone index (e.g. `https://my-index-abc.svc.pinecone.io`).
    index_host: String,
    /// Pinecone API key.
    api_key: String,
    /// Namespace to use within the index (for multi-project isolation).
    namespace: String,
    /// HTTP client shared across requests.
    client: Client,
    /// Embedding dimension (set during `initialize`).
    dimension: RwLock<Option<usize>>,
}

impl PineconeDatabase {
    /// Create a new Pinecone database client.
    ///
    /// - `index_host` — the full URL of the Pinecone index
    /// - `api_key` — Pinecone API key
    /// - `namespace` — namespace within the index (use `""` for default)
    pub fn new(
        index_host: impl Into<String>,
        api_key: impl Into<String>,
        namespace: impl Into<String>,
    ) -> Self {
        let index_host = index_host.into().trim_end_matches('/').to_string();
        Self {
            index_host,
            api_key: api_key.into(),
            namespace: namespace.into(),
            client: Client::new(),
            dimension: RwLock::new(None),
        }
    }

    /// Build a full URL for a Pinecone REST API endpoint.
    fn url(&self, path: &str) -> String {
        format!("{}{}", self.index_host, path)
    }

    /// Build metadata filter JSON for Pinecone queries.
    fn build_metadata_filter(
        &self,
        project: Option<&str>,
        root_path: Option<&str>,
        file_extensions: &[String],
        languages: &[String],
        path_patterns: &[String],
    ) -> Option<serde_json::Value> {
        let mut conditions = Vec::new();

        if let Some(p) = project {
            conditions.push(serde_json::json!({ "project": { "$eq": p } }));
        }
        if let Some(rp) = root_path {
            conditions.push(serde_json::json!({ "root_path": { "$eq": rp } }));
        }
        if !file_extensions.is_empty() {
            conditions.push(serde_json::json!({ "extension": { "$in": file_extensions } }));
        }
        if !languages.is_empty() {
            conditions.push(serde_json::json!({ "language": { "$in": languages } }));
        }
        // Path patterns are matched client-side since Pinecone doesn't support
        // regex/glob in metadata filters. We request extra results and post-filter.
        let _ = path_patterns;

        if conditions.is_empty() {
            None
        } else if conditions.len() == 1 {
            Some(conditions.into_iter().next().unwrap())
        } else {
            Some(serde_json::json!({ "$and": conditions }))
        }
    }

    /// Convert Pinecone query results into `SearchResult` values.
    fn matches_to_results(
        &self,
        matches: Vec<PineconeMatch>,
        min_score: f32,
        path_patterns: &[String],
    ) -> Vec<SearchResult> {
        matches
            .into_iter()
            .filter(|m| m.score >= min_score)
            .filter_map(|m| {
                let meta = m.metadata.as_ref()?;
                let file_path = meta.get("file_path")?.as_str()?.to_string();

                // Client-side path pattern filtering
                if !path_patterns.is_empty() {
                    let matches_pattern = path_patterns.iter().any(|p| file_path.contains(p));
                    if !matches_pattern {
                        return None;
                    }
                }

                let content = meta
                    .get("content")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let root_path = meta
                    .get("root_path")
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let start_line =
                    meta.get("start_line").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
                let end_line = meta.get("end_line").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
                let language = meta
                    .get("language")
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown")
                    .to_string();
                let project = meta
                    .get("project")
                    .and_then(|v| v.as_str())
                    .map(String::from);
                let indexed_at = meta.get("indexed_at").and_then(|v| v.as_i64()).unwrap_or(0);

                Some(SearchResult {
                    file_path,
                    root_path,
                    content,
                    score: m.score,
                    vector_score: m.score,
                    keyword_score: None,
                    start_line,
                    end_line,
                    language,
                    project,
                    indexed_at,
                })
            })
            .collect()
    }
}

// ── Pinecone REST API types ──────────────────────────────────────────────

#[derive(Serialize)]
struct UpsertRequest {
    vectors: Vec<PineconeVector>,
    namespace: String,
}

#[derive(Serialize)]
struct PineconeVector {
    id: String,
    values: Vec<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<serde_json::Value>,
}

#[derive(Serialize)]
struct QueryRequest {
    vector: Vec<f32>,
    top_k: usize,
    namespace: String,
    include_metadata: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    filter: Option<serde_json::Value>,
}

#[derive(Deserialize)]
struct QueryResponse {
    matches: Vec<PineconeMatch>,
}

#[derive(Deserialize)]
struct PineconeMatch {
    #[allow(dead_code)]
    id: String,
    score: f32,
    metadata: Option<serde_json::Value>,
}

#[derive(Serialize)]
struct DeleteRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    ids: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    filter: Option<serde_json::Value>,
    namespace: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    delete_all: Option<bool>,
}

#[derive(Deserialize)]
struct DescribeIndexStatsResponse {
    namespaces: Option<HashMap<String, NamespaceStats>>,
    #[allow(dead_code)]
    dimension: Option<usize>,
    #[allow(dead_code)]
    total_vector_count: Option<usize>,
}

#[derive(Deserialize)]
struct NamespaceStats {
    vector_count: usize,
}

#[derive(Deserialize)]
struct ListResponse {
    vectors: Option<Vec<ListVector>>,
    #[allow(dead_code)]
    pagination: Option<serde_json::Value>,
}

#[derive(Deserialize)]
struct ListVector {
    id: String,
}

#[allow(dead_code)]
#[derive(Deserialize)]
struct FetchResponse {
    vectors: Option<HashMap<String, FetchedVector>>,
}

#[allow(dead_code)]
#[derive(Deserialize)]
struct FetchedVector {
    metadata: Option<serde_json::Value>,
}

// ── VectorDatabase implementation ────────────────────────────────────────

#[async_trait::async_trait]
impl VectorDatabase for PineconeDatabase {
    async fn initialize(&self, dimension: usize) -> Result<()> {
        // Store the dimension. We don't create the index — Pinecone indexes
        // are managed via the Pinecone console / API separately.
        {
            let mut dim = self.dimension.write().map_err(|e| anyhow::anyhow!("{e}"))?;
            *dim = Some(dimension);
        }

        // Verify connectivity by fetching index stats.
        let resp = self
            .client
            .post(self.url("/describe_index_stats"))
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({}))
            .send()
            .await
            .context("Failed to connect to Pinecone index")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            bail!("Pinecone health check failed (HTTP {status}): {body}");
        }

        tracing::info!(dimension, host = %self.index_host, "Pinecone database initialized");
        Ok(())
    }

    async fn store_embeddings(
        &self,
        embeddings: Vec<Vec<f32>>,
        metadata: Vec<ChunkMetadata>,
        contents: Vec<String>,
        root_path: &str,
    ) -> Result<usize> {
        if embeddings.is_empty() {
            return Ok(0);
        }
        if embeddings.len() != metadata.len() || embeddings.len() != contents.len() {
            bail!(
                "Mismatched lengths: {} embeddings, {} metadata, {} contents",
                embeddings.len(),
                metadata.len(),
                contents.len()
            );
        }

        let total = embeddings.len();
        // Pinecone recommends batches of up to 100 vectors.
        const BATCH_SIZE: usize = 100;
        let mut stored = 0;

        for batch_start in (0..total).step_by(BATCH_SIZE) {
            let batch_end = (batch_start + BATCH_SIZE).min(total);
            let mut vectors = Vec::with_capacity(batch_end - batch_start);

            for i in batch_start..batch_end {
                let meta = &metadata[i];
                let id = format!("{}:{}:{}", root_path, meta.file_path, meta.start_line);

                let metadata_json = serde_json::json!({
                    "file_path": meta.file_path,
                    "root_path": root_path,
                    "project": meta.project,
                    "start_line": meta.start_line,
                    "end_line": meta.end_line,
                    "language": meta.language,
                    "extension": meta.extension,
                    "file_hash": meta.file_hash,
                    "indexed_at": meta.indexed_at,
                    "content": contents[i],
                });

                vectors.push(PineconeVector {
                    id,
                    values: embeddings[i].clone(),
                    metadata: Some(metadata_json),
                });
            }

            let request = UpsertRequest {
                vectors,
                namespace: self.namespace.clone(),
            };

            let resp = self
                .client
                .post(self.url("/vectors/upsert"))
                .header("Api-Key", &self.api_key)
                .header("Content-Type", "application/json")
                .json(&request)
                .send()
                .await
                .context("Pinecone upsert request failed")?;

            if !resp.status().is_success() {
                let status = resp.status();
                let body = resp.text().await.unwrap_or_default();
                bail!("Pinecone upsert failed (HTTP {status}): {body}");
            }

            stored += batch_end - batch_start;
            tracing::debug!(stored, total, "Pinecone upsert progress");
        }

        tracing::info!(stored, "Stored embeddings in Pinecone");
        Ok(stored)
    }

    async fn search(
        &self,
        query_vector: Vec<f32>,
        _query_text: &str,
        limit: usize,
        min_score: f32,
        project: Option<String>,
        root_path: Option<String>,
        _hybrid: bool,
    ) -> Result<Vec<SearchResult>> {
        let filter =
            self.build_metadata_filter(project.as_deref(), root_path.as_deref(), &[], &[], &[]);

        let request = QueryRequest {
            vector: query_vector,
            top_k: limit,
            namespace: self.namespace.clone(),
            include_metadata: true,
            filter,
        };

        let resp = self
            .client
            .post(self.url("/query"))
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .context("Pinecone query request failed")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            bail!("Pinecone query failed (HTTP {status}): {body}");
        }

        let query_resp: QueryResponse = resp
            .json()
            .await
            .context("Failed to parse Pinecone query response")?;
        Ok(self.matches_to_results(query_resp.matches, min_score, &[]))
    }

    async fn search_filtered(
        &self,
        query_vector: Vec<f32>,
        _query_text: &str,
        limit: usize,
        min_score: f32,
        project: Option<String>,
        root_path: Option<String>,
        _hybrid: bool,
        file_extensions: Vec<String>,
        languages: Vec<String>,
        path_patterns: Vec<String>,
    ) -> Result<Vec<SearchResult>> {
        // Request extra results when post-filtering by path pattern.
        let extra = if path_patterns.is_empty() { 1 } else { 3 };

        let filter = self.build_metadata_filter(
            project.as_deref(),
            root_path.as_deref(),
            &file_extensions,
            &languages,
            &path_patterns,
        );

        let request = QueryRequest {
            vector: query_vector,
            top_k: limit * extra,
            namespace: self.namespace.clone(),
            include_metadata: true,
            filter,
        };

        let resp = self
            .client
            .post(self.url("/query"))
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .context("Pinecone filtered query request failed")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            bail!("Pinecone filtered query failed (HTTP {status}): {body}");
        }

        let query_resp: QueryResponse = resp
            .json()
            .await
            .context("Failed to parse Pinecone query response")?;
        let mut results = self.matches_to_results(query_resp.matches, min_score, &path_patterns);
        results.truncate(limit);
        Ok(results)
    }

    async fn delete_by_file(&self, file_path: &str) -> Result<usize> {
        // Pinecone supports deletion by metadata filter.
        let request = DeleteRequest {
            ids: None,
            filter: Some(serde_json::json!({ "file_path": { "$eq": file_path } })),
            namespace: self.namespace.clone(),
            delete_all: None,
        };

        let resp = self
            .client
            .post(self.url("/vectors/delete"))
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .context("Pinecone delete request failed")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            bail!("Pinecone delete failed (HTTP {status}): {body}");
        }

        // Pinecone delete doesn't return a count — return 0 as a placeholder.
        tracing::debug!(file_path, "Deleted vectors for file from Pinecone");
        Ok(0)
    }

    async fn clear(&self) -> Result<()> {
        let request = DeleteRequest {
            ids: None,
            filter: None,
            namespace: self.namespace.clone(),
            delete_all: Some(true),
        };

        let resp = self
            .client
            .post(self.url("/vectors/delete"))
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .context("Pinecone clear request failed")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            bail!("Pinecone clear failed (HTTP {status}): {body}");
        }

        tracing::info!("Cleared all vectors from Pinecone namespace");
        Ok(())
    }

    async fn get_statistics(&self) -> Result<DatabaseStats> {
        let resp = self
            .client
            .post(self.url("/describe_index_stats"))
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({}))
            .send()
            .await
            .context("Pinecone describe_index_stats failed")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            bail!("Pinecone describe_index_stats failed (HTTP {status}): {body}");
        }

        let stats: DescribeIndexStatsResponse = resp
            .json()
            .await
            .context("Failed to parse Pinecone stats")?;

        let total_vectors = stats
            .namespaces
            .as_ref()
            .and_then(|ns| ns.get(&self.namespace))
            .map(|n| n.vector_count)
            .unwrap_or(0);

        Ok(DatabaseStats {
            total_points: total_vectors,
            total_vectors,
            // Pinecone doesn't expose per-language breakdowns natively.
            language_breakdown: Vec::new(),
        })
    }

    async fn flush(&self) -> Result<()> {
        // Pinecone is a managed service — writes are durable immediately.
        Ok(())
    }

    async fn count_by_root_path(&self, root_path: &str) -> Result<usize> {
        // Use describe_index_stats with a filter to approximate the count.
        // Pinecone's describe_index_stats supports a filter parameter.
        let resp = self
            .client
            .post(self.url("/describe_index_stats"))
            .header("Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&serde_json::json!({
                "filter": { "root_path": { "$eq": root_path } }
            }))
            .send()
            .await
            .context("Pinecone count_by_root_path failed")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            bail!("Pinecone count_by_root_path failed (HTTP {status}): {body}");
        }

        let stats: DescribeIndexStatsResponse = resp
            .json()
            .await
            .context("Failed to parse Pinecone stats")?;

        let count = stats
            .namespaces
            .as_ref()
            .and_then(|ns| ns.get(&self.namespace))
            .map(|n| n.vector_count)
            .unwrap_or(0);

        Ok(count)
    }

    async fn get_indexed_files(&self, root_path: &str) -> Result<Vec<String>> {
        // Pinecone doesn't have a native "list unique metadata values" API.
        // We list vector IDs (which encode root_path:file_path:line) and extract
        // unique file paths from the IDs.
        let prefix = format!("{}:", root_path);

        let resp = self
            .client
            .get(self.url("/vectors/list"))
            .header("Api-Key", &self.api_key)
            .query(&[
                ("namespace", self.namespace.as_str()),
                ("prefix", prefix.as_str()),
                ("limit", "10000"),
            ])
            .send()
            .await
            .context("Pinecone list vectors failed")?;

        if !resp.status().is_success() {
            // If the list endpoint is unavailable (older Pinecone plans), fall back
            // to returning an empty list rather than failing hard.
            tracing::warn!(
                "Pinecone list endpoint returned non-success; returning empty file list"
            );
            return Ok(Vec::new());
        }

        let list: ListResponse = resp
            .json()
            .await
            .context("Failed to parse Pinecone list response")?;

        let mut files: Vec<String> = list
            .vectors
            .unwrap_or_default()
            .into_iter()
            .filter_map(|v| {
                // ID format: "root_path:file_path:start_line"
                let rest = v.id.strip_prefix(&prefix)?;
                let file_path = rest.rsplit_once(':')?.0;
                Some(file_path.to_string())
            })
            .collect();

        files.sort();
        files.dedup();
        Ok(files)
    }
}