forked from Michael-A-Kuykendall/contextlite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage-report.html
More file actions
952 lines (823 loc) · 42 KB
/
coverage-report.html
File metadata and controls
952 lines (823 loc) · 42 KB
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>storage: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">contextlite/internal/storage/sqlite.go (87.8%)</option>
<option value="file1">contextlite/internal/timing/timer.go (100.0%)</option>
<option value="file2">contextlite/pkg/tokens/token_estimator.go (100.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package storage
import (
"context"
"database/sql"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"time"
"contextlite/pkg/tokens"
"contextlite/pkg/types"
"crypto/sha256"
_ "modernc.org/sqlite"
)
//go:embed schema.sql
var schemaFS embed.FS
// Storage provides SQLite storage operations
type Storage struct {
db *sql.DB
// Cache statistics
cacheHits int64
cacheMisses int64
}
// CacheStats represents cache performance metrics
// Remove the local CacheStats type since we'll use the one from types
// type CacheStats struct {
// Hits int64 `json:"hits"`
// Misses int64 `json:"misses"`
// HitRate float64 `json:"hit_rate"`
// L1Size int `json:"l1_size"`
// L2Size int `json:"l2_size"`
// }
// New creates a new Storage instance
func New(dbPath string) (*Storage, error) <span class="cov8" title="1">{
if dbPath == "" </span><span class="cov8" title="1">{
return nil, fmt.Errorf("database path cannot be empty")
}</span>
<span class="cov8" title="1">db, err := sql.Open("sqlite", dbPath)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to open database: %w", err)
}</span>
// Apply performance pragmas
<span class="cov8" title="1">pragmas := []string{
"PRAGMA journal_mode = WAL",
"PRAGMA synchronous = NORMAL",
"PRAGMA cache_size = -64000",
"PRAGMA temp_store = MEMORY",
"PRAGMA mmap_size = 268435456",
}
for _, pragma := range pragmas </span><span class="cov8" title="1">{
if _, err := db.Exec(pragma); err != nil </span><span class="cov8" title="1">{
return nil, fmt.Errorf("failed to apply pragma %s: %w", pragma, err)
}</span>
}
<span class="cov8" title="1">storage := &Storage{db: db}
// Initialize schema
if err := storage.initSchema(); err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to initialize schema: %w", err)
}</span>
// Apply migrations
<span class="cov8" title="1">if err := storage.applyMigrations(); err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to apply migrations: %w", err)
}</span>
<span class="cov8" title="1">return storage, nil</span>
}
// Close closes the database connection
func (s *Storage) Close() error <span class="cov8" title="1">{
return s.db.Close()
}</span>
// GetStorageStats returns real database statistics
func (s *Storage) GetStorageStats(ctx context.Context) (map[string]interface{}, error) <span class="cov8" title="1">{
stats := make(map[string]interface{})
// Get document count
var docCount int
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM documents").Scan(&docCount)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to get document count: %w", err)
}</span>
<span class="cov8" title="1">stats["total_documents"] = docCount
// Get database size (in pages * page_size)
var pageCount, pageSize int64
err = s.db.QueryRowContext(ctx, "PRAGMA page_count").Scan(&pageCount)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to get page count: %w", err)
}</span>
<span class="cov8" title="1">err = s.db.QueryRowContext(ctx, "PRAGMA page_size").Scan(&pageSize)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to get page size: %w", err)
}</span>
<span class="cov8" title="1">dbSizeBytes := pageCount * pageSize
stats["database_size"] = fmt.Sprintf("%.2f MB", float64(dbSizeBytes)/(1024*1024))
// Get FTS index size (estimate)
ftsPages := pageCount / 4 // Estimate FTS as 25% of total
ftsSizeBytes := ftsPages * pageSize
stats["index_size"] = fmt.Sprintf("%.2f MB", float64(ftsSizeBytes)/(1024*1024))
// Get last update time
var lastUpdate time.Time
err = s.db.QueryRowContext(ctx, `
SELECT MAX(created_at) FROM documents
`).Scan(&lastUpdate)
if err != nil </span><span class="cov8" title="1">{
lastUpdate = time.Now()
}</span>
<span class="cov8" title="1">stats["last_update"] = lastUpdate.Unix()
// Additional useful stats
var avgDocSize sql.NullFloat64
err = s.db.QueryRowContext(ctx, `
SELECT AVG(LENGTH(content)) FROM documents
`).Scan(&avgDocSize)
if err == nil && avgDocSize.Valid </span><span class="cov8" title="1">{
stats["avg_document_size"] = fmt.Sprintf("%.0f chars", avgDocSize.Float64)
}</span>
<span class="cov8" title="1">return stats, nil</span>
}
// GetWorkspaceStats returns workspace-specific statistics
func (s *Storage) GetWorkspaceStats(workspacePath string) (*types.WorkspaceStats, error) <span class="cov8" title="1">{
ctx := context.Background()
// Count documents in this workspace
var docCount int
err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM documents WHERE path LIKE ?
`, workspacePath+"%").Scan(&docCount)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to count workspace documents: %w", err)
}</span>
// Get total tokens in workspace
<span class="cov8" title="1">var totalTokens sql.NullInt64
err = s.db.QueryRowContext(ctx, `
SELECT SUM(token_count) FROM documents WHERE path LIKE ?
`, workspacePath+"%").Scan(&totalTokens)
if err != nil </span><span class="cov0" title="0">{
totalTokens.Int64 = 0 // Default if query fails
}</span>
// Get average file size
<span class="cov8" title="1">var avgFileSize sql.NullFloat64
err = s.db.QueryRowContext(ctx, `
SELECT AVG(LENGTH(content)) FROM documents WHERE path LIKE ?
`, workspacePath+"%").Scan(&avgFileSize)
if err != nil </span><span class="cov0" title="0">{
avgFileSize.Float64 = 0 // Default if query fails
}</span>
// Get languages (simplified - just take first few)
<span class="cov8" title="1">rows, err := s.db.QueryContext(ctx, `
SELECT DISTINCT lang FROM documents WHERE path LIKE ? AND lang != '' LIMIT 10
`, workspacePath+"%")
languages := []string{}
if err == nil </span><span class="cov8" title="1">{
defer rows.Close()
for rows.Next() </span><span class="cov8" title="1">{
var lang string
if err := rows.Scan(&lang); err == nil </span><span class="cov8" title="1">{
languages = append(languages, lang)
}</span>
}
}
// Get last indexed time (most recent document)
<span class="cov8" title="1">var lastIndexed time.Time
err = s.db.QueryRowContext(ctx, `
SELECT MAX(updated_at) FROM documents WHERE path LIKE ?
`, workspacePath+"%").Scan(&lastIndexed)
if err != nil </span><span class="cov8" title="1">{
lastIndexed = time.Now() // Default if query fails
}</span>
<span class="cov8" title="1">return &types.WorkspaceStats{
Path: workspacePath,
DocumentCount: docCount,
TotalTokens: totalTokens.Int64,
LastIndexed: lastIndexed,
Languages: languages,
AverageFileSize: int64(avgFileSize.Float64),
}, nil</span>
}
// GetCacheStats returns cache performance statistics
func (s *Storage) GetCacheStats(ctx context.Context) (*types.CacheStats, error) <span class="cov8" title="1">{
// Get L2 cache size (number of cached results)
var l2Size int
err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM query_cache").Scan(&l2Size)
if err != nil </span><span class="cov8" title="1">{
return nil, fmt.Errorf("failed to get cache size: %w", err)
}</span>
<span class="cov8" title="1">total := s.cacheHits + s.cacheMisses
hitRate := 0.0
if total > 0 </span><span class="cov0" title="0">{
hitRate = float64(s.cacheHits) / float64(total)
}</span>
<span class="cov8" title="1">return &types.CacheStats{
Hits: s.cacheHits,
Misses: s.cacheMisses,
HitRate: hitRate,
L1Size: 0, // L1 cache not implemented in this version
L2Size: l2Size,
}, nil</span>
}
// initSchema initializes the database schema
func (s *Storage) initSchema() error <span class="cov8" title="1">{
schema, err := schemaFS.ReadFile("schema.sql")
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to read schema: %w", err)
}</span>
// Split and execute each statement
<span class="cov8" title="1">statements := strings.Split(string(schema), ";")
for _, stmt := range statements </span><span class="cov8" title="1">{
stmt = strings.TrimSpace(stmt)
if stmt == "" </span><span class="cov8" title="1">{
continue</span>
}
// Special handling for FTS tables since IF NOT EXISTS doesn't work with them
<span class="cov8" title="1">if strings.Contains(stmt, "CREATE VIRTUAL TABLE") && strings.Contains(stmt, "documents_fts") </span><span class="cov8" title="1">{
// Check if FTS table exists
var count int
err := s.db.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='documents_fts'").Scan(&count)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to check FTS table existence: %w", err)
}</span>
<span class="cov8" title="1">if count > 0 </span><span class="cov8" title="1">{
continue</span> // Skip creating FTS table if it already exists
}
// Remove IF NOT EXISTS from FTS statement
<span class="cov8" title="1">stmt = strings.Replace(stmt, "IF NOT EXISTS ", "", 1)</span>
}
<span class="cov8" title="1">if _, err := s.db.Exec(stmt); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to execute schema statement: %w", err)
}</span>
}
<span class="cov8" title="1">return nil</span>
}
// AddDocument adds a document to the database
func (s *Storage) AddDocument(ctx context.Context, doc *types.Document) error <span class="cov8" title="1">{
// Generate ID if not provided
if doc.ID == "" </span><span class="cov8" title="1">{
hash := sha256.Sum256([]byte(doc.Content))
doc.ID = hex.EncodeToString(hash[:8])
}</span>
// Generate content hash
<span class="cov8" title="1">hash := sha256.Sum256([]byte(doc.Content))
doc.ContentHash = hex.EncodeToString(hash[:])
// Estimate token count if not provided
if doc.TokenCount == 0 </span><span class="cov8" title="1">{
tokenEstimator := tokens.NewTokenEstimator("gpt-4") // Default model
doc.TokenCount = tokenEstimator.EstimateTokens(doc.Content)
}</span>
// Set timestamps
<span class="cov8" title="1">now := time.Now()
doc.CreatedAt = now
doc.UpdatedAt = now
tx, err := s.db.BeginTx(ctx, nil)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to begin transaction: %w", err)
}</span>
<span class="cov8" title="1">defer tx.Rollback()
// Insert document
_, err = tx.ExecContext(ctx, `
INSERT OR REPLACE INTO documents
(id, content, content_hash, path, lang, mtime, token_count, model_id,
quantum_score, entanglement_map, coherence_history, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
doc.ID, doc.Content, doc.ContentHash, doc.Path, doc.Language,
doc.ModifiedTime, doc.TokenCount, doc.ModelID, doc.QuantumScore,
doc.Entanglement, doc.Coherence, doc.CreatedAt, doc.UpdatedAt)
if err != nil </span><span class="cov8" title="1">{
return fmt.Errorf("failed to insert document: %w", err)
}</span>
// Insert into FTS
<span class="cov8" title="1">_, err = tx.ExecContext(ctx, `
INSERT OR REPLACE INTO documents_fts(rowid, content)
SELECT rowid, content FROM documents WHERE id = ?`, doc.ID)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to insert into FTS: %w", err)
}</span>
<span class="cov8" title="1">return tx.Commit()</span>
}
// InsertDocument inserts a new document (wrapper around AddDocument for interface compliance)
func (s *Storage) InsertDocument(doc types.Document) error <span class="cov8" title="1">{
return s.AddDocument(context.Background(), &doc)
}</span>
// UpdateDocument updates an existing document (wrapper around AddDocument for interface compliance)
func (s *Storage) UpdateDocument(doc types.Document) error <span class="cov8" title="1">{
return s.AddDocument(context.Background(), &doc)
}</span>
// SearchDocuments performs FTS search
func (s *Storage) SearchDocuments(ctx context.Context, query string, limit int) ([]types.Document, error) <span class="cov8" title="1">{
// First try FTS search
docs, err := s.searchFTS(ctx, query, limit)
if err != nil </span><span class="cov8" title="1">{
// Fallback to LIKE search
return s.searchLike(ctx, query, limit)
}</span>
<span class="cov8" title="1">return docs, nil</span>
}
// searchFTS performs FTS5 search
func (s *Storage) searchFTS(ctx context.Context, query string, limit int) ([]types.Document, error) <span class="cov8" title="1">{
rows, err := s.db.QueryContext(ctx, `
SELECT d.id, d.content, d.content_hash, d.path, d.lang, d.mtime,
d.token_count, d.model_id, d.quantum_score, d.entanglement_map,
d.coherence_history, d.created_at, d.updated_at
FROM documents_fts fts
JOIN documents d ON d.rowid = fts.rowid
WHERE documents_fts MATCH ?
ORDER BY rank
LIMIT ?`, query, limit)
if err != nil </span><span class="cov8" title="1">{
return nil, err
}</span>
<span class="cov8" title="1">defer rows.Close()
return s.scanDocuments(rows)</span>
}
// searchLike performs LIKE search as fallback
func (s *Storage) searchLike(ctx context.Context, query string, limit int) ([]types.Document, error) <span class="cov8" title="1">{
likeQuery := "%" + strings.ReplaceAll(strings.ToLower(query), " ", "%") + "%"
rows, err := s.db.QueryContext(ctx, `
SELECT id, content, content_hash, path, lang, mtime,
token_count, model_id, quantum_score, entanglement_map,
coherence_history, created_at, updated_at
FROM documents
WHERE LOWER(content) LIKE ?
ORDER BY LENGTH(content)
LIMIT ?`, likeQuery, limit)
if err != nil </span><span class="cov8" title="1">{
return nil, err
}</span>
<span class="cov8" title="1">defer rows.Close()
return s.scanDocuments(rows)</span>
}
// scanDocuments scans rows into Document structs
func (s *Storage) scanDocuments(rows *sql.Rows) ([]types.Document, error) <span class="cov8" title="1">{
var docs []types.Document
for rows.Next() </span><span class="cov8" title="1">{
var doc types.Document
err := rows.Scan(
&doc.ID, &doc.Content, &doc.ContentHash, &doc.Path, &doc.Language,
&doc.ModifiedTime, &doc.TokenCount, &doc.ModelID, &doc.QuantumScore,
&doc.Entanglement, &doc.Coherence, &doc.CreatedAt, &doc.UpdatedAt)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">docs = append(docs, doc)</span>
}
<span class="cov8" title="1">return docs, rows.Err()</span>
}
// GetDocument retrieves a document by ID
func (s *Storage) GetDocument(ctx context.Context, id string) (*types.Document, error) <span class="cov8" title="1">{
var doc types.Document
err := s.db.QueryRowContext(ctx, `
SELECT id, content, content_hash, path, lang, mtime,
token_count, model_id, quantum_score, entanglement_map,
coherence_history, created_at, updated_at
FROM documents WHERE id = ?`, id).Scan(
&doc.ID, &doc.Content, &doc.ContentHash, &doc.Path, &doc.Language,
&doc.ModifiedTime, &doc.TokenCount, &doc.ModelID, &doc.QuantumScore,
&doc.Entanglement, &doc.Coherence, &doc.CreatedAt, &doc.UpdatedAt)
if err != nil </span><span class="cov8" title="1">{
return nil, err
}</span>
<span class="cov8" title="1">return &doc, nil</span>
}
// GetDocumentByPath retrieves a document by its file path
func (s *Storage) GetDocumentByPath(ctx context.Context, path string) (*types.Document, error) <span class="cov8" title="1">{
var doc types.Document
err := s.db.QueryRowContext(ctx, `
SELECT id, content, content_hash, path, lang, mtime,
token_count, model_id, quantum_score, entanglement_map,
coherence_history, created_at, updated_at
FROM documents WHERE path = ? LIMIT 1`, path).Scan(
&doc.ID, &doc.Content, &doc.ContentHash, &doc.Path, &doc.Language,
&doc.ModifiedTime, &doc.TokenCount, &doc.ModelID, &doc.QuantumScore,
&doc.Entanglement, &doc.Coherence, &doc.CreatedAt, &doc.UpdatedAt)
if err != nil </span><span class="cov8" title="1">{
return nil, err
}</span>
<span class="cov8" title="1">return &doc, nil</span>
}
// DeleteDocument removes a document
func (s *Storage) DeleteDocument(ctx context.Context, id string) error <span class="cov8" title="1">{
if id == "" </span><span class="cov8" title="1">{
return fmt.Errorf("document ID cannot be empty")
}</span>
<span class="cov8" title="1">tx, err := s.db.BeginTx(ctx, nil)
if err != nil </span><span class="cov8" title="1">{
return err
}</span>
<span class="cov8" title="1">defer tx.Rollback()
// Delete from documents_fts first (due to foreign key)
_, err = tx.ExecContext(ctx, "DELETE FROM documents_fts WHERE rowid = (SELECT rowid FROM documents WHERE id = ?)", id)
if err != nil </span><span class="cov8" title="1">{
return err
}</span>
// Delete from documents
<span class="cov8" title="1">_, err = tx.ExecContext(ctx, "DELETE FROM documents WHERE id = ?", id)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">return tx.Commit()</span>
}
// GetWorkspaceWeights retrieves workspace weights
func (s *Storage) GetWorkspaceWeights(ctx context.Context, workspacePath string) (*types.WorkspaceWeights, error) <span class="cov8" title="1">{
var weights types.WorkspaceWeights
err := s.db.QueryRowContext(ctx, `
SELECT workspace_path, relevance_weight, recency_weight, diversity_weight,
entanglement_weight, redundancy_penalty, normalization_stats,
update_count, last_updated
FROM workspace_weights WHERE workspace_path = ?`, workspacePath).Scan(
&weights.WorkspacePath, &weights.RelevanceWeight, &weights.RecencyWeight,
&weights.DiversityWeight, &weights.EntanglementWeight, &weights.RedundancyPenalty,
&weights.NormalizationStats, &weights.UpdateCount, &weights.LastUpdated)
if err != nil </span><span class="cov8" title="1">{
return nil, err
}</span>
<span class="cov8" title="1">return &weights, nil</span>
}
// SaveWorkspaceWeights saves workspace weights (interface-compatible version)
func (s *Storage) SaveWorkspaceWeights(workspacePath string, weights types.FeatureWeights) error <span class="cov8" title="1">{
ctx := context.Background()
// Convert FeatureWeights to WorkspaceWeights format for storage
workspaceWeights := &types.WorkspaceWeights{
WorkspacePath: workspacePath,
RelevanceWeight: weights.Relevance,
RecencyWeight: weights.Recency,
EntanglementWeight: weights.Entanglement,
DiversityWeight: weights.Specificity, // Map Specificity to DiversityWeight
RedundancyPenalty: weights.Uncertainty, // Map Uncertainty to RedundancyPenalty
UpdateCount: 1,
LastUpdated: time.Now().Format(time.RFC3339),
NormalizationStats: "", // Default empty
}
return s.saveWorkspaceWeightsInternal(ctx, workspaceWeights)
}</span>
// saveWorkspaceWeightsInternal saves workspace weights (internal implementation)
func (s *Storage) saveWorkspaceWeightsInternal(ctx context.Context, weights *types.WorkspaceWeights) error <span class="cov8" title="1">{
_, err := s.db.ExecContext(ctx, `
INSERT OR REPLACE INTO workspace_weights
(workspace_path, relevance_weight, recency_weight, diversity_weight,
entanglement_weight, redundancy_penalty, normalization_stats,
update_count, last_updated)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
weights.WorkspacePath, weights.RelevanceWeight, weights.RecencyWeight,
weights.DiversityWeight, weights.EntanglementWeight, weights.RedundancyPenalty,
weights.NormalizationStats, weights.UpdateCount, weights.LastUpdated)
return err
}</span>
// SaveQueryCache saves a query result to cache
func (s *Storage) SaveQueryCache(ctx context.Context, queryHash, corpusHash, modelID, tokenizerVersion string,
result *types.QueryResult, expiresAt time.Time) error <span class="cov8" title="1">{
resultJSON, err := json.Marshal(result.Documents)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">metricsJSON, err := json.Marshal(result.SMTMetrics)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">_, err = s.db.ExecContext(ctx, `
INSERT OR REPLACE INTO query_cache
(query_hash, corpus_hash, model_id, tokenizer_version, result_context,
quantum_metrics, document_scores, coherence_score, optimization_gap,
solve_time_ms, fallback_used, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
queryHash, corpusHash, modelID, tokenizerVersion, string(resultJSON),
string(metricsJSON), "", result.CoherenceScore, 0.0, // OptimalityGap removed
result.SMTMetrics.SolveTimeMs, result.SMTMetrics.FallbackReason != "", expiresAt)
return err</span>
}
// GetQueryCache retrieves a cached query result
func (s *Storage) GetQueryCache(ctx context.Context, queryHash, corpusHash, modelID, tokenizerVersion string) (*types.QueryResult, error) <span class="cov8" title="1">{
var resultJSON, metricsJSON string
var result types.QueryResult
var tempGap float64 // Unused - OptimalityGap field removed
err := s.db.QueryRowContext(ctx, `
SELECT result_context, quantum_metrics, coherence_score,
optimization_gap, solve_time_ms, fallback_used
FROM query_cache
WHERE query_hash = ? AND corpus_hash = ? AND model_id = ?
AND tokenizer_version = ? AND expires_at > CURRENT_TIMESTAMP`,
queryHash, corpusHash, modelID, tokenizerVersion).Scan(
&resultJSON, &metricsJSON, &result.CoherenceScore,
&tempGap, &result.SMTMetrics.SolveTimeMs, // OptimalityGap removed
&result.SMTMetrics.FallbackReason)
if err != nil </span><span class="cov8" title="1">{
return nil, err
}</span>
<span class="cov8" title="1">if err := json.Unmarshal([]byte(resultJSON), &result.Documents); err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">if err := json.Unmarshal([]byte(metricsJSON), &result.SMTMetrics); err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">result.CacheHit = true
// Track cache hit
s.cacheHits++
return &result, nil</span>
}
// GetCorpusHash computes a hash of the current document corpus
func (s *Storage) GetCorpusHash(ctx context.Context) (string, error) <span class="cov8" title="1">{
var hash string
err := s.db.QueryRowContext(ctx, `
SELECT hex(sha256_agg(content_hash ORDER BY id))
FROM (SELECT id, content_hash FROM documents ORDER BY id)`).Scan(&hash)
if err != nil </span><span class="cov8" title="1">{
// Fallback calculation if sha256_agg is not available
rows, err := s.db.QueryContext(ctx, "SELECT content_hash FROM documents ORDER BY id")
if err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov8" title="1">defer rows.Close()
h := sha256.New()
for rows.Next() </span><span class="cov8" title="1">{
var contentHash string
if err := rows.Scan(&contentHash); err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov8" title="1">h.Write([]byte(contentHash))</span>
}
<span class="cov8" title="1">hash = hex.EncodeToString(h.Sum(nil))</span>
}
<span class="cov8" title="1">return hash, nil</span>
}
// applyMigrations applies database migrations for schema changes
func (s *Storage) applyMigrations() error <span class="cov8" title="1">{
// Check if cache_key column exists in query_cache table
rows, err := s.db.Query("PRAGMA table_info(query_cache)")
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to check table info: %w", err)
}</span>
<span class="cov8" title="1">defer rows.Close()
hasCacheKey := false
for rows.Next() </span><span class="cov8" title="1">{
var cid int
var name, dataType string
var notNull, pk int
var defaultValue sql.NullString
if err := rows.Scan(&cid, &name, &dataType, &notNull, &defaultValue, &pk); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to scan table info: %w", err)
}</span>
<span class="cov8" title="1">if name == "cache_key" </span><span class="cov8" title="1">{
hasCacheKey = true
break</span>
}
}
// Add cache_key column if it doesn't exist
<span class="cov8" title="1">if !hasCacheKey </span><span class="cov8" title="1">{
_, err := s.db.Exec("ALTER TABLE query_cache ADD COLUMN cache_key TEXT")
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to add cache_key column: %w", err)
}</span>
// Add index for cache_key
<span class="cov8" title="1">_, err = s.db.Exec("CREATE INDEX IF NOT EXISTS idx_query_cache_key ON query_cache(cache_key)")
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create cache_key index: %w", err)
}</span>
}
<span class="cov8" title="1">return nil</span>
}
// GetCachedResultByKey retrieves cached result by cache key
func (s *Storage) GetCachedResultByKey(ctx context.Context, cacheKey string) (*types.QueryResult, error) <span class="cov8" title="1">{
query := `
SELECT result_context, quantum_metrics, document_scores, coherence_score,
solve_time_ms, fallback_used, created_at
FROM query_cache
WHERE cache_key = ? AND expires_at > ?
`
row := s.db.QueryRowContext(ctx, query, cacheKey, time.Now())
var resultContext, quantumMetrics, documentScores string
var coherenceScore float64
var solveTimeMs sql.NullFloat64 // Changed from NullInt64 to NullFloat64 to handle type mismatch
var fallbackUsed bool
var createdAt time.Time
err := row.Scan(&resultContext, &quantumMetrics, &documentScores,
&coherenceScore, &solveTimeMs, &fallbackUsed, &createdAt)
if err != nil </span><span class="cov8" title="1">{
if err == sql.ErrNoRows </span><span class="cov8" title="1">{
// Track cache miss
s.cacheMisses++
return nil, nil // Cache miss
}</span>
<span class="cov0" title="0">return nil, fmt.Errorf("failed to scan cached result: %w", err)</span>
}
// Deserialize the cached result
<span class="cov8" title="1">var result types.QueryResult
if err := json.Unmarshal([]byte(resultContext), &result); err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to unmarshal cached result: %w", err)
}</span>
// Set solve time from scanned value if available
<span class="cov8" title="1">if solveTimeMs.Valid </span><span class="cov8" title="1">{
result.SMTMetrics.SolveTimeMs = solveTimeMs.Float64
}</span>
<span class="cov8" title="1">return &result, nil</span>
}
// SaveQueryCacheWithKey saves a query result to cache with cache key
func (s *Storage) SaveQueryCacheWithKey(ctx context.Context, queryHash, corpusHash, modelID, tokenizerVersion, cacheKey string,
result *types.QueryResult, expiresAt time.Time) error <span class="cov8" title="1">{
resultJSON, err := json.Marshal(result)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">metricsJSON, err := json.Marshal(result.SMTMetrics)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
// Check if cache_key column exists
<span class="cov8" title="1">rows, err := s.db.Query("PRAGMA table_info(query_cache)")
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to check table info: %w", err)
}</span>
<span class="cov8" title="1">defer rows.Close()
hasCacheKey := false
for rows.Next() </span><span class="cov8" title="1">{
var cid int
var name, dataType string
var notNull, pk int
var defaultValue sql.NullString
if err := rows.Scan(&cid, &name, &dataType, &notNull, &defaultValue, &pk); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to scan table info: %w", err)
}</span>
<span class="cov8" title="1">if name == "cache_key" </span><span class="cov8" title="1">{
hasCacheKey = true
break</span>
}
}
<span class="cov8" title="1">if hasCacheKey </span><span class="cov8" title="1">{
_, err = s.db.ExecContext(ctx, `
INSERT OR REPLACE INTO query_cache
(query_hash, corpus_hash, model_id, tokenizer_version, result_context,
quantum_metrics, document_scores, coherence_score, optimization_gap,
solve_time_ms, fallback_used, expires_at, cache_key)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
queryHash, corpusHash, modelID, tokenizerVersion, string(resultJSON),
string(metricsJSON), "", result.CoherenceScore, 0.0, // OptimalityGap removed
result.SMTMetrics.SolveTimeMs, result.SMTMetrics.FallbackReason != "", expiresAt, cacheKey)
}</span> else<span class="cov0" title="0"> {
// Fallback to old method without cache_key
_, err = s.db.ExecContext(ctx, `
INSERT OR REPLACE INTO query_cache
(query_hash, corpus_hash, model_id, tokenizer_version, result_context,
quantum_metrics, document_scores, coherence_score, optimization_gap,
solve_time_ms, fallback_used, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
queryHash, corpusHash, modelID, tokenizerVersion, string(resultJSON),
string(metricsJSON), "", result.CoherenceScore, 0.0, // OptimalityGap removed
result.SMTMetrics.SolveTimeMs, result.SMTMetrics.FallbackReason != "", expiresAt)
}</span>
<span class="cov8" title="1">return err</span>
}
// InvalidateCache removes all cached query results
func (s *Storage) InvalidateCache(ctx context.Context) error <span class="cov8" title="1">{
_, err := s.db.ExecContext(ctx, "DELETE FROM query_cache")
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to invalidate cache: %w", err)
}</span>
// Reset cache statistics
<span class="cov8" title="1">s.cacheHits = 0
s.cacheMisses = 0
return nil</span>
}
</pre>
<pre class="file" id="file1" style="display: none">// Package timing provides high-precision timing utilities for performance measurement
package timing
import "time"
// Timer represents a timing measurement starting point
type Timer struct {
t0 time.Time
}
// Start creates a new timing measurement starting at the current time
func Start() Timer <span class="cov8" title="1">{
return Timer{t0: time.Now()} // monotonic clock included
}</span>
// Us returns the elapsed time in microseconds since Start()
func (t Timer) Us() int64 <span class="cov8" title="1">{
return time.Since(t.t0).Nanoseconds() / 1_000
}</span>
// Ms returns the elapsed time in milliseconds as a float64 since Start()
func (t Timer) Ms() float64 <span class="cov8" title="1">{
return float64(t.Us()) / 1_000.0
}</span>
// Ns returns the elapsed time in nanoseconds since Start()
func (t Timer) Ns() int64 <span class="cov8" title="1">{
return time.Since(t.t0).Nanoseconds()
}</span>
</pre>
<pre class="file" id="file2" style="display: none">package tokens
import (
"strings"
"unicode"
)
// TokenEstimator provides token counting functionality
type TokenEstimator struct {
model string
}
// NewTokenEstimator creates a new token estimator
func NewTokenEstimator(model string) *TokenEstimator <span class="cov8" title="1">{
return &TokenEstimator{
model: model,
}
}</span>
// EstimateTokens estimates the number of tokens in the given text
// This is a simple approximation - in production this would use
// the actual tokenizer for the specified model
func (te *TokenEstimator) EstimateTokens(text string) int <span class="cov8" title="1">{
if text == "" </span><span class="cov8" title="1">{
return 0
}</span>
// Simple heuristic: ~4 characters per token for English text
// This approximates GPT-style tokenization
<span class="cov8" title="1">charCount := len(text)
// Account for whitespace and punctuation
wordCount := len(strings.Fields(text))
punctCount := countPunctuation(text)
// Rough estimation: 0.75 tokens per word + punctuation tokens
estimatedTokens := int(float64(wordCount)*0.75) + punctCount
// Character-based fallback for edge cases
charBasedEstimate := charCount / 4
// Use the higher of the two estimates to be conservative
if charBasedEstimate > estimatedTokens </span><span class="cov8" title="1">{
return charBasedEstimate
}</span>
<span class="cov8" title="1">return estimatedTokens</span>
}
// countPunctuation counts punctuation characters that might be separate tokens
func countPunctuation(text string) int <span class="cov8" title="1">{
count := 0
for _, r := range text </span><span class="cov8" title="1">{
if unicode.IsPunct(r) </span><span class="cov8" title="1">{
count++
}</span>
}
<span class="cov8" title="1">return count</span>
}
</pre>
</div>
</body>
<script>
(function() {
var files = document.getElementById('files');
var visible;
files.addEventListener('change', onChange, false);
function select(part) {
if (visible)
visible.style.display = 'none';
visible = document.getElementById(part);
if (!visible)
return;
files.value = part;
visible.style.display = 'block';
location.hash = part;
}
function onChange() {
select(files.value);
window.scrollTo(0, 0);
}
if (location.hash != "") {
select(location.hash.substr(1));
}
if (!visible) {
select("file0");
}
})();
</script>
</html>