-
Notifications
You must be signed in to change notification settings - Fork 272
Expand file tree
/
Copy pathnode.go
More file actions
1827 lines (1649 loc) · 58.7 KB
/
Copy pathnode.go
File metadata and controls
1827 lines (1649 loc) · 58.7 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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2025 Homer Server Contributors
//
// 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.
// Package node provides the FlightSQL node module for Homer Server.
// It serves data from DuckLake storage via FlightSQL protocol.
package node
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
airport "github.com/hugr-lab/airport-go"
"github.com/sipcapture/homer-core/src/config"
"github.com/sipcapture/homer-core/src/coordinator/sqlvalidator"
"github.com/sipcapture/homer-core/src/storage/ducklake"
"github.com/sipcapture/homer-core/src/stream/hepstream"
logger "github.com/sipcapture/homer-core/src/utils/logging"
"google.golang.org/grpc"
_ "github.com/duckdb/duckdb-go/v2"
)
// VolumeInfo represents an attached storage volume
type VolumeInfo struct {
Name string // Volume name (e.g., "hot", "cold")
LakeName string // DuckLake name (e.g., "homer_lake_hot")
Path string // Data path
}
// Node is the FlightSQL node module
type Node struct {
config *config.NodeConfig
grpcServer *grpc.Server
httpServer *http.Server
catalog *DuckLakeCatalog
listener net.Listener
db *sql.DB
sharedDB *sql.DB // shared with writer module for real-time visibility
tieredQueryDB *sql.DB // writer TieredStorageManager DuckDB (homer_lake_hot / _cold)
mu sync.RWMutex
running bool
volumes []VolumeInfo // Attached storage volumes for tiered storage
// fsql is the optional Apache Arrow FlightSQL server (Grafana / InfluxDB FlightSQL).
fsql *fsqlServer
// broker is optional: wired from main.go when the ingest module is
// running in the same process and ingest.hep_stream.enable is true.
// When nil the /stream endpoint responds with 503 so the coordinator
// can cleanly skip this node during fan-out.
broker *hepstream.Broker
}
// SetBroker wires the live-stream broker into the node so handleStream
// can subscribe to it. Called once by main.go before Start(); passing
// nil disables the feature on this node.
func (n *Node) SetBroker(b *hepstream.Broker) {
n.mu.Lock()
defer n.mu.Unlock()
n.broker = b
}
// New creates a new Node module
func New(cfg *config.NodeConfig) (*Node, error) {
// Connect to DuckLake database
db, err := sql.Open("duckdb", "")
if err != nil {
return nil, fmt.Errorf("failed to open DuckDB: %w", err)
}
// Use single connection to ensure ATTACH catalogs are always visible
db.SetMaxOpenConns(1)
// Configure DuckDB for DuckLake and get attached volumes
volumes, err := configureDuckLake(db, cfg)
if err != nil {
db.Close()
return nil, fmt.Errorf("failed to configure DuckLake: %w", err)
}
// Create DuckLake catalog with volume support
catalog := NewDuckLakeCatalog(db, cfg.DuckLake.LakeName, volumes)
// Build airport config
airportConfig := airport.ServerConfig{
Catalog: catalog,
MaxMessageSize: cfg.FlightServer.MaxMessageSize,
}
// Add authentication if configured
if cfg.FlightServer.AuthToken != "" {
airportConfig.Auth = airport.BearerAuth(func(token string) (string, error) {
if token == cfg.FlightServer.AuthToken {
return "homer-user", nil
}
return "", airport.ErrUnauthorized
})
}
// Create gRPC server with airport options
opts := airport.ServerOptions(airportConfig)
grpcServer := grpc.NewServer(opts...)
// Register airport Flight service
airport.NewServer(grpcServer, airportConfig)
n := &Node{
config: cfg,
grpcServer: grpcServer,
catalog: catalog,
db: db,
volumes: volumes,
}
if cfg.FlightSQLServer.Enable {
n.fsql = newFsqlServer(n, cfg.FlightSQLServer, cfg.DuckLake.LakeName)
}
return n, nil
}
// Start starts the node module
func (n *Node) Start() error {
n.mu.Lock()
defer n.mu.Unlock()
if n.running {
return fmt.Errorf("node already running")
}
// Refresh catalog: DETACH + re-ATTACH so we see tables created by the
// storage module that started before us but used a separate DuckDB instance.
n.refreshCatalog()
// Start gRPC server for FlightSQL (Airport protocol)
grpcAddr := fmt.Sprintf("%s:%d", n.config.FlightServer.Host, n.config.FlightServer.Port)
listener, err := net.Listen("tcp", grpcAddr)
if err != nil {
return fmt.Errorf("failed to listen: %w", err)
}
n.listener = listener
n.running = true
go func() {
logger.Info("Node: FlightSQL server started", "addr", grpcAddr)
if err := n.grpcServer.Serve(listener); err != nil {
logger.Error(fmt.Sprintf("Node: FlightSQL server error: %v", err))
}
}()
// Start HTTP server for SQL queries (used by coordinator)
httpPort := n.config.FlightServer.Port + 1 // HTTP on next port
httpAddr := fmt.Sprintf("%s:%d", n.config.FlightServer.Host, httpPort)
mux := http.NewServeMux()
mux.HandleFunc("/query", n.handleQuery)
mux.HandleFunc("/health", n.handleHealth)
mux.HandleFunc("/vacuum", n.handleVacuum)
mux.HandleFunc("/stream", n.handleStream)
n.httpServer = &http.Server{
Addr: httpAddr,
Handler: mux,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
}
go func() {
logger.Info("Node: HTTP API started", "addr", httpAddr)
if err := n.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error(fmt.Sprintf("Node: HTTP server error: %v", err))
}
}()
if n.fsql != nil {
if n.sharedDB == nil {
n.fsql.withCatalogRefresher(func() { n.refreshCatalog() })
}
if err := n.fsql.Start(); err != nil {
return fmt.Errorf("FlightSQL: %w", err)
}
}
return nil
}
// refreshCatalog detaches and re-attaches all DuckLake volumes so that
// the node sees any tables created by the storage module (which runs
// its own DuckDB instance sharing the same catalog file).
func (n *Node) refreshCatalog() {
for _, vol := range n.volumes {
detachSQL := fmt.Sprintf("DETACH %s;", vol.LakeName)
if _, err := n.db.Exec(detachSQL); err != nil {
logger.Warn(fmt.Sprintf("Node: refreshCatalog: DETACH %s failed: %v", vol.LakeName, err))
}
}
// Re-attach volumes using the original config
newVolumes, err := configureDuckLake(n.db, n.config)
if err != nil {
logger.Error(fmt.Sprintf("Node: refreshCatalog: re-attach failed: %v", err))
return
}
n.volumes = newVolumes
n.catalog = NewDuckLakeCatalog(n.db, n.config.DuckLake.LakeName, newVolumes)
logger.Info("Node: catalog refreshed", "volumes", len(newVolumes))
}
// Stop stops the node module
func (n *Node) Stop() error {
n.mu.Lock()
defer n.mu.Unlock()
if !n.running {
return nil
}
// Stop HTTP server
if n.httpServer != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
n.httpServer.Shutdown(ctx)
}
if n.fsql != nil {
n.fsql.Stop()
}
// GracefulStop waits for all in-flight RPCs to finish. Guard with a timeout
// so that stale client connections do not block the entire shutdown sequence.
grpcStopped := make(chan struct{})
go func() {
n.grpcServer.GracefulStop()
close(grpcStopped)
}()
select {
case <-grpcStopped:
case <-time.After(5 * time.Second):
logger.Warn("Node: gRPC server did not stop gracefully in 5s, forcing stop")
n.grpcServer.Stop()
}
n.running = false
if n.db != nil {
n.db.Close()
}
logger.Info("Node: FlightSQL server stopped")
return nil
}
// QueryRequest represents a SQL query request
type QueryRequest struct {
SQL string `json:"sql"`
}
// QueryResponse represents a SQL query response
type QueryResponse struct {
Success bool `json:"success"`
Data []map[string]interface{} `json:"data,omitempty"`
Count int `json:"count,omitempty"`
Error string `json:"error,omitempty"`
}
// shouldUseSQLQuery returns true for statements that return row sets and must
// use QueryContext. INSERT/UPDATE/DELETE without RETURNING should use ExecContext
// so DuckDB applies mutations reliably (Query-only INSERTs could be invisible
// to subsequent SELECTs on some paths).
func shouldUseSQLQuery(sql string) bool {
u := strings.TrimSpace(strings.ToUpper(sql))
if strings.Contains(u, "RETURNING") {
return true
}
switch {
case strings.HasPrefix(u, "SELECT"):
return true
case strings.HasPrefix(u, "WITH"):
return true
case strings.HasPrefix(u, "SHOW"):
return true
case strings.HasPrefix(u, "DESCRIBE"):
return true
case strings.HasPrefix(u, "PRAGMA"):
return true
case strings.HasPrefix(u, "EXPLAIN"):
return true
default:
return false
}
}
func sqlStringLiteral(value string) string {
escaped := strings.ReplaceAll(value, "'", "''")
return "'" + escaped + "'"
}
func addStorageColumnsToQuery(sql, lakeName, volumeName string) string {
upperSQL := strings.ToUpper(sql)
selectIdx := strings.Index(upperSQL, "SELECT")
fromIdx := strings.Index(upperSQL, "FROM")
if selectIdx == -1 || fromIdx == -1 || fromIdx < selectIdx {
return sql
}
selectPart := sql[selectIdx+len("SELECT") : fromIdx]
selectPartLower := strings.ToLower(selectPart)
if strings.Contains(selectPartLower, "storage_lake") || strings.Contains(selectPartLower, "storage_volume") {
return sql
}
trimmedSelect := strings.TrimSpace(selectPart)
if trimmedSelect == "" {
return sql
}
extraCols := fmt.Sprintf(
"%s AS storage_lake, %s AS storage_volume",
sqlStringLiteral(lakeName),
sqlStringLiteral(volumeName),
)
newSelect := trimmedSelect + ", " + extraCols
return sql[:selectIdx+len("SELECT")] + " " + newSelect + " " + sql[fromIdx:]
}
var sqlLimitRegexp = regexp.MustCompile(`(?is)\s+LIMIT\s+(\d+)\s*$`)
var (
sqlTimestampFromRegexp = regexp.MustCompile(`(?is)\btimestamp\s*>=\s*\(to_timestamp\((\d+)\s*/\s*1000(?:\.0)?\)\s*AT\s+TIME\s+ZONE\s+'UTC'\)`)
sqlTimestampToRegexp = regexp.MustCompile(`(?is)\btimestamp\s*(?:<=|<)\s*\(to_timestamp\((\d+)\s*/\s*1000(?:\.0)?\)\s*AT\s+TIME\s+ZONE\s+'UTC'\)`)
sqlGroupByRegexp = regexp.MustCompile(`(?is)\bGROUP\s+BY\b`)
sqlDistinctRegexp = regexp.MustCompile(`(?is)\bSELECT\s+DISTINCT\b`)
sqlAggregateRegexp = regexp.MustCompile(`(?is)\b(COUNT|SUM|AVG|MIN|MAX)\s*\(`)
)
const memorySplitThresholdMs = int64(time.Hour / time.Millisecond)
// sqlIsAggregateShape reports whether the query carries aggregation, grouping
// or DISTINCT anywhere. Such results cannot be merged row-wise across DuckDB
// instances (uuid/timestamp dedup keys collapse aggregate rows), so they need
// a single-SQL execution over a UNION of the underlying tables instead.
func sqlIsAggregateShape(sql string) bool {
return sqlGroupByRegexp.MatchString(sql) ||
sqlDistinctRegexp.MatchString(sql) ||
sqlAggregateRegexp.MatchString(sql)
}
var sqlOrderByTimestampAscRegexp = regexp.MustCompile(`(?is)\bORDER\s+BY\s+timestamp\s+ASC\b`)
// sortMergedRowsForQueryOrder restores the requested row order after
// mergeSelectResults, which always sorts newest-first. Queries like the QoS
// RTP/RTCP tabs ask for ORDER BY timestamp ASC and consume the rows as-is,
// so an ASC request must be re-sorted oldest-first (with LIMIT keeping the
// oldest N to match single-statement semantics).
func sortMergedRowsForQueryOrder(rows []map[string]interface{}, originalSQL string, limit int) []map[string]interface{} {
if !sqlOrderByTimestampAscRegexp.MatchString(originalSQL) {
return rows
}
sort.Slice(rows, func(i, j int) bool {
return rowTimestampSortKey(rows[i]) < rowTimestampSortKey(rows[j])
})
if limit > 0 && len(rows) > limit {
rows = rows[:limit]
}
return rows
}
func extractSQLLimit(sql string) int {
m := sqlLimitRegexp.FindStringSubmatch(sql)
if len(m) < 2 {
return 0
}
n, err := strconv.Atoi(m[1])
if err != nil || n < 0 {
return 0
}
return n
}
func scanAllSQLRows(rows *sql.Rows) ([]map[string]interface{}, []string, error) {
columns, err := rows.Columns()
if err != nil {
return nil, nil, err
}
var out []map[string]interface{}
for rows.Next() {
values := make([]interface{}, len(columns))
ptrs := make([]interface{}, len(columns))
for i := range values {
ptrs[i] = &values[i]
}
if err := rows.Scan(ptrs...); err != nil {
continue
}
row := make(map[string]interface{}, len(columns))
for i, c := range columns {
row[c] = values[i]
}
out = append(out, row)
}
if err := rows.Err(); err != nil {
return nil, nil, err
}
return out, columns, nil
}
func mergeColumnOrder(a, b []string) []string {
seen := make(map[string]bool)
var out []string
for _, c := range a {
if c != "" && !seen[c] {
seen[c] = true
out = append(out, c)
}
}
for _, c := range b {
if c != "" && !seen[c] {
seen[c] = true
out = append(out, c)
}
}
return out
}
func rowDedupKey(m map[string]interface{}) string {
if u, ok := m["uuid"]; ok && u != nil {
return "u:" + fmt.Sprint(u)
}
return "f:" + fmt.Sprint(m["session_id"]) + "|" + fmt.Sprint(m["timestamp"])
}
func rowTimestampSortKey(m map[string]interface{}) int64 {
v, ok := m["timestamp"]
if !ok || v == nil {
return 0
}
switch t := v.(type) {
case time.Time:
return t.UnixNano()
case []byte:
ts, err := time.Parse("2006-01-02 15:04:05.999999999", string(t))
if err != nil {
ts, err = time.Parse("2006-01-02 15:04:05", string(t))
}
if err == nil {
return ts.UnixNano()
}
}
return 0
}
func mergeSelectResults(a, b []map[string]interface{}, colsA, colsB []string, limit int) ([]map[string]interface{}, []string) {
cols := mergeColumnOrder(colsA, colsB)
byKey := make(map[string]map[string]interface{})
for _, row := range a {
k := rowDedupKey(row)
byKey[k] = row
}
for _, row := range b {
k := rowDedupKey(row)
if ex, ok := byKey[k]; ok {
if rowTimestampSortKey(row) > rowTimestampSortKey(ex) {
byKey[k] = row
}
} else {
byKey[k] = row
}
}
merged := make([]map[string]interface{}, 0, len(byKey))
for _, row := range byKey {
nr := make(map[string]interface{}, len(cols))
for _, c := range cols {
if v, ok := row[c]; ok {
nr[c] = v
} else {
nr[c] = nil
}
}
merged = append(merged, nr)
}
sort.Slice(merged, func(i, j int) bool {
return rowTimestampSortKey(merged[i]) > rowTimestampSortKey(merged[j])
})
if limit > 0 && len(merged) > limit {
merged = merged[:limit]
}
return merged, cols
}
// runSelectQuery executes a single read-only SELECT and scans all rows.
//
// The query is server-composed (rewritten from the request by the node/hub,
// see rewriteQueryForVolumes and buildMemoryUnionQueries); it is not a raw
// end-user string and cannot be parameterized because table names, volume
// UNIONs and the overall statement shape are built dynamically. As defence in
// depth we still reject anything that is not a single read-only SELECT before
// it reaches the driver, so a malformed/stacked statement can never run here.
func validateUserSQL(query string) error {
trimmed := strings.TrimSpace(query)
if trimmed == "" {
return fmt.Errorf("empty SQL query")
}
upper := strings.ToUpper(trimmed)
if !strings.HasPrefix(upper, "SELECT") && !strings.HasPrefix(upper, "WITH") {
return fmt.Errorf("only SELECT/CTE queries are allowed")
}
// Semicolons are always rejected regardless of position (defence in depth).
// Comment markers only rejected when outside string literals — session_ids
// containing "--" (e.g. base64-like provider Call-IDs) are legitimate data.
if strings.Contains(trimmed, ";") {
return fmt.Errorf("SQL contains forbidden comment or statement separator")
}
if sqlvalidator.ContainsUnsafeComment(trimmed) {
return fmt.Errorf("SQL contains forbidden comment or statement separator")
}
// Token-aware keyword check: ignore string literals so Call-IDs that embed
// words like "call" / "delete" do not false-positive (same class of bug as
// "--" inside session_id before ContainsUnsafeComment).
if sqlvalidator.ContainsForbiddenIdentifier(trimmed, sqlvalidator.ForbiddenReadOnlyKeywords) {
return fmt.Errorf("SQL contains forbidden keyword")
}
return nil
}
func runSelectQuery(ctx context.Context, db *sql.DB, query string) ([]map[string]interface{}, []string, error) {
if err := validateUserSQL(query); err != nil {
return nil, nil, err
}
if err := ensureReadOnlySingleStatement(query); err != nil {
return nil, nil, err
}
rows, err := db.QueryContext(ctx, query) //nolint:rowserrcheck // scanAllSQLRows checks rows.Err
if err != nil {
return nil, nil, err
}
defer rows.Close()
return scanAllSQLRows(rows)
}
// ensureReadOnlySingleStatement rejects stacked statements and non-SELECT
// (DDL/DML) queries before execution.
func ensureReadOnlySingleStatement(query string) error {
trimmed := strings.TrimSpace(query)
if trimmed == "" {
return fmt.Errorf("empty query")
}
// Disallow stacked statements (only a single trailing ';' is allowed).
if idx := strings.IndexByte(trimmed, ';'); idx >= 0 && strings.TrimSpace(trimmed[idx+1:]) != "" {
return fmt.Errorf("multiple statements are not allowed")
}
head := strings.ToUpper(trimmed)
if !strings.HasPrefix(head, "SELECT") && !strings.HasPrefix(head, "WITH") {
return fmt.Errorf("only read-only SELECT queries are allowed")
}
return nil
}
type memoryUnionQueries struct {
lakeSQL string
memSQL string
combinedSQL string
ok bool
}
type sharedQueryPlanLog struct {
mode string
lakeSQL string
memSQL string
combinedSQL string
lakeChunks int // number of time chunks the lake sub-query was split into
}
func normalizeSQLWhitespace(s string) string {
return strings.Join(strings.Fields(strings.ToLower(strings.TrimSpace(s))), " ")
}
func memorySplitRangeMs(sql string) (int64, bool) {
fromMs, toMs, ok := memorySplitBoundsMs(sql)
if !ok {
return 0, false
}
return toMs - fromMs, true
}
// memorySplitBoundsMs extracts the [from, to) epoch-millisecond bounds of the
// `timestamp >= ... AND timestamp < ...` predicate the UI builds for a search.
func memorySplitBoundsMs(sql string) (int64, int64, bool) {
fromM := sqlTimestampFromRegexp.FindStringSubmatch(sql)
toM := sqlTimestampToRegexp.FindStringSubmatch(sql)
if len(fromM) < 2 || len(toM) < 2 {
return 0, 0, false
}
fromMs, err := strconv.ParseInt(fromM[1], 10, 64)
if err != nil {
return 0, 0, false
}
toMs, err := strconv.ParseInt(toM[1], 10, 64)
if err != nil || toMs <= fromMs {
return 0, 0, false
}
return fromMs, toMs, true
}
// Lake top-N execution strategies (storage.ducklake.search.lake_topn_strategy).
const (
lakeTopNChunked = "chunked" // descending time windows, newest first, early stop
lakeTopNStream = "stream" // drop ORDER BY, plain streaming LIMIT (scan order)
lakeTopNFull = "full" // original single ORDER BY scan over the whole range
)
// defaultLakeTimeChunkMs is the fallback chunk width when search.lake_chunk_sec
// is unset. One hour keeps the per-chunk scan (wide SELECT * over payload-heavy
// SIP rows) well within a small memory_limit, where scanning the whole range at
// once OOMs.
const defaultLakeTimeChunkMs = int64(time.Hour / time.Millisecond)
// lakeTopNStrategy returns the configured lake top-N execution strategy,
// defaulting to "stream" (lowest memory; Go re-sorts the result newest-first).
func (n *Node) lakeTopNStrategy() string {
if n.config == nil {
return lakeTopNStream
}
switch n.config.DuckLake.Search.LakeTopNStrategy {
case lakeTopNChunked:
return lakeTopNChunked
case lakeTopNFull:
return lakeTopNFull
default: // "" and any unknown value
return lakeTopNStream
}
}
// sortRowsByTimestampDescLimit orders rows newest-first by their timestamp and
// trims to limit. Used to restore ordering after the "stream" strategy drops
// ORDER BY at the database to keep memory flat.
func sortRowsByTimestampDescLimit(rows []map[string]interface{}, limit int) []map[string]interface{} {
sort.Slice(rows, func(i, j int) bool {
return rowTimestampSortKey(rows[i]) > rowTimestampSortKey(rows[j])
})
if limit > 0 && len(rows) > limit {
rows = rows[:limit]
}
return rows
}
// lakeChunkMs returns the configured chunk width (ms) for the "chunked"
// strategy, defaulting to one hour.
func (n *Node) lakeChunkMs() int64 {
if n.config == nil || n.config.DuckLake.Search.LakeChunkSec <= 0 {
return defaultLakeTimeChunkMs
}
return int64(n.config.DuckLake.Search.LakeChunkSec) * 1000
}
// stripOrderByForStream rewrites a `... ORDER BY timestamp DESC LIMIT N` query
// into `... LIMIT N` (no ORDER BY). DuckDB then stops scanning after N rows, so
// memory stays tiny — at the cost of returning rows in scan order rather than
// strictly newest-first.
func stripOrderByForStream(sql string) string {
orderByClause, limitClause, base := extractOrderLimit(sql)
if orderByClause == "" {
return sql
}
out := strings.TrimSpace(base)
if limitClause != "" {
out += " " + limitClause
}
return out
}
// rewriteTimestampBoundsMs replaces the timestamp range predicate in a search
// SQL with new [from, to) epoch-millisecond bounds, preserving the exact shape
// DuckDB/DuckLake expect.
func rewriteTimestampBoundsMs(sql string, fromMs, toMs int64) string {
sql = sqlTimestampFromRegexp.ReplaceAllString(sql,
fmt.Sprintf("timestamp >= (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')", fromMs))
sql = sqlTimestampToRegexp.ReplaceAllString(sql,
fmt.Sprintf("timestamp < (to_timestamp(%d / 1000.0) AT TIME ZONE 'UTC')", toMs))
return sql
}
// runLakeSplitByTime executes a timestamp-DESC top-N lake query in descending
// time chunks (newest first), stopping as soon as it has gathered `limit` rows.
// Because the chunks are disjoint and processed newest→oldest, once `limit` rows
// are collected no older chunk can contribute to the top-N, so the scan stops
// early. Each chunk scans at most lakeTimeChunkMs of data, bounding peak memory
// regardless of the overall range (the whole-range scan OOMs on wide SIP rows).
func (n *Node) runLakeSplitByTime(
ctx context.Context, db *sql.DB, lakeSQL string, fromMs, toMs, chunkMs int64, limit int,
) ([]map[string]interface{}, []string, int, error) {
if chunkMs <= 0 {
chunkMs = defaultLakeTimeChunkMs
}
var all []map[string]interface{}
var cols []string
chunks := 0
for hi := toMs; hi > fromMs; hi -= chunkMs {
if err := ctx.Err(); err != nil {
return nil, nil, chunks, err
}
lo := hi - chunkMs
if lo < fromMs {
lo = fromMs
}
chunkSQL := rewriteTimestampBoundsMs(lakeSQL, lo, hi)
data, c, err := runSelectQuery(ctx, db, chunkSQL)
if err != nil {
return nil, nil, chunks, err
}
chunks++
if len(c) > 0 {
cols = c
}
all = append(all, data...)
if limit > 0 && len(all) >= limit {
break
}
}
// Chunks arrive newest-first and each is already DESC, but normalise the
// concatenation (sort DESC, dedup, apply limit) so the contract matches a
// single ORDER BY timestamp DESC LIMIT query.
merged, mcols := mergeSelectResults(all, nil, cols, nil, limit)
return merged, mcols, chunks, nil
}
// sqlSplitSafeShape reports whether a query is a `SELECT * ... LIMIT N` with no
// aggregation/grouping/distinct — the shape we can safely execute as
// independent time windows (with or without ORDER BY). Ordering is checked
// separately by the callers.
func sqlSplitSafeShape(baseSQL, limitClause string) bool {
if strings.TrimSpace(limitClause) == "" {
return false
}
upper := strings.ToUpper(baseSQL)
if sqlGroupByRegexp.MatchString(upper) || sqlDistinctRegexp.MatchString(upper) || sqlAggregateRegexp.MatchString(upper) {
return false
}
selectIdx := strings.Index(upper, "SELECT")
fromIdx := strings.Index(upper, "FROM")
if selectIdx == -1 || fromIdx == -1 || fromIdx <= selectIdx+len("SELECT") {
return false
}
selectList := strings.TrimSpace(baseSQL[selectIdx+len("SELECT") : fromIdx])
return strings.HasPrefix(selectList, "*")
}
func sqlSplitSafeForTimestampTopN(sql, baseSQL, orderByClause, limitClause string) bool {
if normalizeSQLWhitespace(orderByClause) != "order by timestamp desc" {
return false
}
return sqlSplitSafeShape(baseSQL, limitClause)
}
func (n *Node) buildMemoryUnionQueries(sql string) memoryUnionQueries {
out := memoryUnionQueries{lakeSQL: sql}
if n.sharedDB == nil {
return out
}
upper := strings.ToUpper(strings.TrimSpace(sql))
isSelect := strings.HasPrefix(upper, "SELECT")
isCTE := strings.HasPrefix(upper, "WITH")
if !isSelect && !isCTE {
return out
}
marker := ".main.hep_proto_"
markerIdx := strings.Index(sql, marker)
if markerIdx == -1 {
return out
}
lakeStart := markerIdx
for lakeStart > 0 {
ch := sql[lakeStart-1]
if ch == ' ' || ch == '\t' || ch == '\n' || ch == '(' || ch == ',' {
break
}
lakeStart--
}
lakeName := sql[lakeStart:markerIdx]
suffixStart := markerIdx + len(marker)
suffixEnd := suffixStart
for suffixEnd < len(sql) {
ch := sql[suffixEnd]
if ch == ' ' || ch == '\t' || ch == '\n' || ch == ',' || ch == ')' || ch == ';' {
break
}
suffixEnd++
}
tableSuffix := sql[suffixStart:suffixEnd]
memTableA := "mem_hep_proto_" + tableSuffix + "_a"
memTableB := "mem_hep_proto_" + tableSuffix + "_b"
lakeTableFQN := sql[lakeStart:suffixEnd]
// Aggregate/GROUP BY/DISTINCT results cannot be unioned row-wise (each
// branch would emit its own aggregate row — e.g. three count(*) rows), and
// CTE queries cannot be wrapped as UNION operands. For both, substitute
// the table reference in place with a derived UNION of the lake table and
// the two memory buffers so the query runs once with correct semantics.
if isCTE || sqlIsAggregateShape(sql) {
tableName := "hep_proto_" + tableSuffix
derived := "(SELECT * FROM " + lakeTableFQN +
" UNION ALL SELECT * FROM " + memTableA +
" UNION ALL SELECT * FROM " + memTableB + ")"
out.combinedSQL = replaceTableWithDerived(sql, lakeTableFQN, derived, tableName)
out.ok = true
return out
}
orderByClause, limitClause, baseSQL := extractOrderLimit(sql)
memSQLA := strings.Replace(baseSQL, lakeTableFQN, memTableA, 1)
memSQLB := strings.Replace(baseSQL, lakeTableFQN, memTableB, 1)
for _, memSQL := range []*string{&memSQLA, &memSQLB} {
*memSQL = strings.Replace(*memSQL, "'"+lakeName+"' AS storage_lake", "'memory' AS storage_lake", 1)
for _, vol := range n.volumes {
*memSQL = strings.Replace(*memSQL, "'"+vol.Name+"' AS storage_volume", "'buffer' AS storage_volume", 1)
}
}
memUnion := "SELECT * FROM (" + memSQLA + " UNION ALL " + memSQLB + ") _m"
combined := "SELECT * FROM (" + baseSQL + " UNION ALL " + memSQLA + " UNION ALL " + memSQLB + ") _u"
if orderByClause != "" {
memUnion += " " + orderByClause
combined += " " + orderByClause
}
if limitClause != "" {
memUnion += " " + limitClause
combined += " " + limitClause
}
out.memSQL = memUnion
out.combinedSQL = combined
out.ok = true
return out
}
// sqlHasNonTimestampFilter reports whether the WHERE clause carries predicates
// beyond the two timestamp range bounds (e.g. session_id/cid/method LIKE/=/IN).
//
// Time-slicing only helps the "fat" top-N case: an unfiltered `SELECT *` over a
// long range materialises huge wide result sets, so slicing + early exit bounds
// memory and stays fast. A *filtered* query is the opposite — it returns few
// rows (no memory risk) but a non-prunable filter (LIKE '%…%') forces a full
// scan, and slicing it into N tiny per-window scans multiplies the catalog/
// Parquet open overhead and runs them serially, which times out. Such queries
// must run as a single efficient scan per window instead.
func sqlHasNonTimestampFilter(baseSQL string) bool {
lower := strings.ToLower(baseSQL)
wi := strings.Index(lower, " where ")
if wi == -1 {
return false
}
where := baseSQL[wi+len(" where "):]
where = sqlTimestampFromRegexp.ReplaceAllString(where, " ")
where = sqlTimestampToRegexp.ReplaceAllString(where, " ")
where = strings.NewReplacer("(", " ", ")", " ").Replace(where)
for _, tok := range strings.Fields(where) {
switch strings.ToLower(tok) {
case "and", "or":
continue
default:
return true // a real predicate beyond the timestamp bounds
}
}
return false
}
func shouldSplitLakeAndMem(sql, baseSQL, orderByClause, limitClause string) bool {
if !sqlSplitSafeForTimestampTopN(sql, baseSQL, orderByClause, limitClause) {
return false
}
if sqlHasNonTimestampFilter(baseSQL) {
return false // filtered: run a single efficient scan, do not slice
}
rangeMs, ok := memorySplitRangeMs(sql)
return ok && rangeMs > memorySplitThresholdMs
}
func (n *Node) runSharedSelectWithMemoryPolicy(ctx context.Context, db *sql.DB, sql string) ([]map[string]interface{}, []string, sharedQueryPlanLog, error) {
plan := sharedQueryPlanLog{
mode: "no_mem_union",
lakeSQL: sql,
combinedSQL: sql,
}
mq := n.buildMemoryUnionQueries(sql)
if !mq.ok {
data, cols, err := runSelectQuery(ctx, db, sql)
return data, cols, plan, err
}
orderByClause, limitClause, baseSQL := extractOrderLimit(sql)
// mq.memSQL is empty for the derived-table rewrite (CTE/aggregate
// queries); those must run as a single combined statement.
if mq.memSQL != "" && shouldSplitLakeAndMem(sql, baseSQL, orderByClause, limitClause) {
plan.mode = "split_lake_and_mem"
plan.lakeSQL = mq.lakeSQL
plan.memSQL = mq.memSQL
plan.combinedSQL = ""
limitN := extractSQLLimit(sql)
// The lake sub-query (SELECT * ORDER BY timestamp DESC LIMIT N over a long
// range) is what OOMs on payload-heavy SIP rows under a small memory_limit.
// search.lake_topn_strategy picks how to run it.
var lakeData []map[string]interface{}
var lakeCols []string
var err error
switch n.lakeTopNStrategy() {
case lakeTopNFull:
plan.mode = "split_lake_and_mem:full"
lakeData, lakeCols, err = runSelectQuery(ctx, db, mq.lakeSQL)
case lakeTopNChunked:
plan.mode = "split_lake_and_mem:chunked"
if fromMs, toMs, ok := memorySplitBoundsMs(mq.lakeSQL); ok {
lakeData, lakeCols, plan.lakeChunks, err = n.runLakeSplitByTime(
ctx, db, mq.lakeSQL, fromMs, toMs, n.lakeChunkMs(), limitN)
} else {
lakeData, lakeCols, err = runSelectQuery(ctx, db, mq.lakeSQL)
}
default: // lakeTopNStream (default)
plan.mode = "split_lake_and_mem:stream"
streamSQL := stripOrderByForStream(mq.lakeSQL)
plan.lakeSQL = streamSQL
lakeData, lakeCols, err = runSelectQuery(ctx, db, streamSQL)
if err == nil {
// We dropped ORDER BY to keep DuckDB memory flat, so the rows come
// back in arbitrary scan order. Re-sort newest-first in Go before
// returning so the result ordering still matches the request.
lakeData = sortRowsByTimestampDescLimit(lakeData, limitN)
}
}
if err != nil {
return nil, nil, plan, fmt.Errorf("lake query: %w", err)
}
memData, memCols, err := runSelectQuery(ctx, db, mq.memSQL)
if err != nil {
return nil, nil, plan, fmt.Errorf("memory query: %w", err)
}
merged, cols := mergeSelectResults(lakeData, memData, lakeCols, memCols, limitN)
return merged, cols, plan, nil
}
plan.mode = "single_union"
plan.lakeSQL = mq.lakeSQL
plan.memSQL = mq.memSQL
plan.combinedSQL = mq.combinedSQL
data, cols, err := runSelectQuery(ctx, db, mq.combinedSQL)
return data, cols, plan, err
}
func (n *Node) querySelectMerged(ctx context.Context, sharedSQL string, sharedDB *sql.DB, tieredSQL string, tieredDB *sql.DB, originalSQL string) ([]map[string]interface{}, []string, error) {
rows1, err := sharedDB.QueryContext(ctx, sharedSQL)
if err != nil {
return nil, nil, fmt.Errorf("shared query: %w", err)
}
defer rows1.Close()
data1, cols1, err := scanAllSQLRows(rows1)
if err != nil {
return nil, nil, err
}
rows2, err := tieredDB.QueryContext(ctx, tieredSQL)
if err != nil {
return nil, nil, fmt.Errorf("tiered query: %w", err)
}
defer rows2.Close()
data2, cols2, err := scanAllSQLRows(rows2)
if err != nil {
return nil, nil, err
}
limit := extractSQLLimit(originalSQL)
merged, cols := mergeSelectResults(data1, data2, cols1, cols2, limit)
return merged, cols, nil
}
func (n *Node) tieredQueryDBForRead() *sql.DB {
n.mu.RLock()
defer n.mu.RUnlock()
return n.tieredQueryDB
}
// handleQuery handles POST /query requests
func (n *Node) handleQuery(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {