Skip to content

feat(serenedb): add SereneDB doc-store engine (Go + Python connectors) - #17375

Merged
JinHai-CN merged 11 commits into
infiniflow:mainfrom
deadtrickster:ik-serenedb-go-engine
Aug 4, 2026
Merged

JinHai-CN merged 11 commits into
infiniflow:mainfrom
deadtrickster:ik-serenedb-go-engine

Conversation

@deadtrickster

@deadtrickster deadtrickster commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds SereneDB as a selectable doc-store engine on both RAGFlow paths:

  • the Go DocEngine (internal/engine/serenedb), alongside Elasticsearch and Infinity;
  • the Python DocStoreConnection (rag/utils/serenedb_conn.py) + DOC_ENGINE=serenedb registration.

SereneDB is a PostgreSQL-wire engine (DuckDB execution) whose single inverted index carries both a scored text column (@@, BM25) and an IVF vector column (<#>, inner product), so hybrid search is one SQL statement. The Go engine connects with database/sql + lib/pq (already a dependency, no new module); the Python connector uses psycopg2 (already a dependency).

Storage model

One table per tenant with kb_id as a filter column - the Elasticsearch / OceanBase model, not Infinity's per-dataset tables. This keeps BM25 statistics (IDF, avgdl) computed over the whole tenant corpus (global IDF). Both connectors use this identical layout, so they are storage- and retrieval-compatible: hybrid proxy routing and Python↔Go switching are safe. On the Python side the connector is wired as OceanBase's plain-SQL sibling (chunk_data JSON metadata, inline chunk vectors, verbatim ES field names); the ES tokenizer path is unchanged. Metadata stays one table per tenant (ragflow_doc_meta_<tenant>).

The query shapes mirror the Python connector, including the five empirically-found landmines: the scored dictionary needs frequency + norm (else BM25() silently returns 0.0), the @@ query is the tokenized query, the scored lexical branch matches one column, vectors use an L2-normalized shadow column with ip/sq8, and the similarity threshold goes directly in the ANN scan's WHERE. Minimum engine version: SereneDB 26.07.4.

Registration

EngineSereneDB in engine.go and server/config.go, the factory arm in global.go, a SereneDBConfig, and the DOC_ENGINE=serenedb + serenedb: config-mapping paths.

Retrieval quality (provenance, measured on the Python path, 247,665-chunk multilingual corpus)

Gold eval, weighted fusion 0.7·bm25_norm + 0.3·cos:

MRR mean rank latency
Elasticsearch hybrid 0.82 2.8 180 ms
SereneDB (lexical live) 0.82 3.0 35 ms
SereneDB + GTE rerank 0.83 2.0 (rerank on CPU; stage is engine-independent)

Recall on the same gold set: recall@8 3/5 (both ES and SereneDB), recall@64 5/5 (both).

Throughput / ingest:

Metric SereneDB Elasticsearch
QPS @ concurrency 16 514 241
p99 latency @ conc 16 42 ms 108 ms
Index build over 247k 5.6 s -

Migration of all 247,665 docs through the connector: 0 errors.

Why single-table (the BM25 point)

Infinity shards per-KB, which computes BM25 IDF per dataset. That is a quality regression versus whole-corpus IDF in two ways: small/narrow KBs give noisy term weights, and the per-table score normalization forces the best lexical hit in every KB to 1.0. Illustration - a weak best-in-a-sparse-KB chunk (raw BM25 5, table max 5) scores:

Normalization lexical score fused (0.7 lex + 0.3 [email protected])
per-KB (max = 5) 1.00 0.73
whole-corpus (global max = 40) 0.125 0.12

The single-table model avoids this entirely (global normalization, one query, no cross-KB merge).

Parity between the two connectors in this PR (real 247k corpus)

The Go engine and the Python connector, given identical (tokenized text, query vector, weights) inputs and hybrid fusion, return the identical ranked top-10 on the same single-tenant table:

Storage model top-1 agreement Jaccard@10
per-KB tables (evaluated, rejected) - single-KB 98% 0.78
per-KB tables (evaluated, rejected) - multi-KB 88% 0.64
single-table per tenant (this PR) 100% 1.000

The per-KB rows are why the single-table model was chosen: sharding BM25 per dataset diverges (local vs global IDF); the single-table model both connectors share makes them exactly equivalent.

Testing

  • Unit tests (serenedb_test.go) - pure SQL-builder and codec tests, no database, run under build.sh --test. Cover the fusion CTE, single-column scored branch, threshold-in-WHERE, upsert, kb_id scoping, array/JSON decoding, vector literal.
  • Integration tests (integration_test.go) - end-to-end against a live SereneDB (all four search modes, get/scores, update/delete, metadata lifecycle). Skipped unless SERENEDB_TEST_DSN is set, so the default run stays CI-safe.
  • Real-corpus validation - the engine ingested the full 247,665-chunk corpus through InsertChunks (0 errors) and served correct fulltext, exact-cosine vector, and hybrid-fusion retrieval; parity verified as above.

Scope

FilterDocIdsByMetaPushdown returns nil (the interface's defined in-memory fall-back); pushing metadata predicates into SQL is a later optimization. A gold-set MRR run for the Go path specifically was not reproduced here (needs the bge-m3 embedder); the parity result above establishes engine equivalence to the measured Python path.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds SereneDB as a document engine with configuration, Go and Python storage implementations, full-text, vector, and hybrid search, metadata and chunk CRUD, RAGFlow routing, and unit and integration tests.

Changes

SereneDB document engine

Layer / File(s) Summary
Configuration and backend wiring
common/settings.py, internal/server/config.go, internal/engine/..., api/db/services/..., rag/app/table.py, rag/nlp/search.py, rag/utils/table_es_metadata.py
Adds the serenedb engine mode, connection configuration, initialization paths, and backend-specific ingestion, metadata, vector, and reranking behavior.
Go engine foundation
internal/engine/serenedb/schema.go, common.go, client.go, serenedb.go
Defines SereneDB schema metadata, connection pooling, DSN handling, SQL conversion helpers, filters, vector normalization, and value decoding.
Go chunk, document, and metadata storage
internal/engine/serenedb/chunk.go, document.go, metadata.go
Implements tenant-scoped tables, document indexing, chunk upserts and updates, metadata persistence, deletion, lookup, and metadata search.
Go search and SQL execution
internal/engine/serenedb/search.go, sql.go
Adds full-text, vector, hybrid, filter-only, aggregation, highlighting, score helpers, and bounded SQL execution.
Python connector implementation
rag/utils/serenedb_conn.py
Adds pooled SereneDB access with schema lifecycle, search, hybrid scoring, CRUD, metadata handling, result helpers, and SQL passthrough.
Unit and integration validation
internal/engine/serenedb/*_test.go, test/unit_test/rag/utils/test_serenedb_conn.py
Adds deterministic SQL and helper tests and optional live SereneDB tests for chunk and metadata lifecycles.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Config
  participant RAGFlow
  participant SereneDBConnection
  participant SereneDB

  Config->>RAGFlow: Select serenedb engine
  RAGFlow->>SereneDBConnection: Initialize connection
  SereneDBConnection->>SereneDB: Create tenant tables and indexes
  RAGFlow->>SereneDBConnection: Insert or search chunks
  SereneDBConnection->>SereneDB: Execute SQL
  SereneDB-->>SereneDBConnection: Return chunks, scores, or metadata
  SereneDBConnection-->>RAGFlow: Return normalized results
Loading

Suggested labels: 💞 feature, 🌈 python

Poem

I’m a rabbit with a database tune,
Planting chunk tables beneath the moon.
Vectors hop, text blooms bright,
Metadata keeps its keys just right.
SereneDB joins the burrowed crew—
With tests that prove the paths run true!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the addition of a SereneDB doc-store engine for both Go and Python connectors.
Description check ✅ Passed The description clearly covers the purpose, architecture, testing, scope, compatibility requirements, and reported validation results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 2
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch ik-serenedb-go-engine
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@deadtrickster
deadtrickster force-pushed the ik-serenedb-go-engine branch 2 times, most recently from faf8d32 to 7ac58a5 Compare July 25, 2026 06:28
@deadtrickster deadtrickster changed the title feat(engine): add SereneDB Go doc-store engine feat(serenedb): add SereneDB doc-store engine (Go + Python connectors) Jul 25, 2026
@deadtrickster
deadtrickster marked this pull request as ready for review July 25, 2026 06:32
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 25, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

🟠 Major comments (20)
rag/utils/serenedb_conn.py-197-225 (1)

197-225: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Singleton __init__ isn't synchronized — TOCTOU on _initialized.

__new__ guards instance creation with _instance_lock, but __init__ runs unsynchronized on the shared instance. self._initialized = True (line 206) is set before self._pool, self._known_tables, and self._known_lock are constructed (lines 221-223). If two threads race to construct the first SereneDBConnection() concurrently, the second thread can see _initialized=True and return early while the first thread is still mid-construction, leaving self._pool/self._known_tables unset for any concurrent caller.

🔒 Proposed fix
     def __init__(self):
-        if getattr(self, "_initialized", False):
-            return
-        self._initialized = True
-        dsn = None
-        try:
+        with self._instance_lock:
+            if getattr(self, "_initialized", False):
+                return
+            self._initialized = True
+        dsn = None
+        try:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/serenedb_conn.py` around lines 197 - 225, Synchronize
initialization in SereneDBConnection.__init__ using the existing _instance_lock
so only one thread can initialize the singleton at a time. Check _initialized
while holding the lock, perform construction of _pool, _known_tables,
_known_lock, and _dsn_display, then set _initialized only after all fields are
ready.
rag/utils/serenedb_conn.py-279-286 (1)

279-286: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Skip dropping tenant-shared doc-meta tables unless the tenant is being removed.

ragflow_doc_meta_* tables are tenant shared, but this guard only protects regular chunk tables. Since metadata writers use a tenant-scoped index with per-kb_id rows, any path that calls delete_idx("ragflow_doc_meta_<tenant>", "<kb_id>") should not reach DROP TABLE IF EXISTS, otherwise metadata for other KBs under the same tenant is lost.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/serenedb_conn.py` around lines 279 - 286, The delete_idx method
must also skip dropping tenant-shared ragflow_doc_meta_* tables when called with
a dataset_id; update its guard so any per-KB deletion of a doc-meta index
returns before DROP INDEX or DROP TABLE, while still allowing the tenant-level
removal path to drop the shared table.
rag/utils/serenedb_conn.py-613-627 (1)

613-627: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

delete() lacks the try/except used by its sibling update()/insert().

update() wraps its _run call in try/except, logs, and returns False on error; insert() collects per-row errors. delete()'s _run(...) calls (count then delete) have no exception handling, so any SQL/DB error here propagates as an unhandled exception up through the DocStoreConnection contract, breaking the graceful-degradation pattern used elsewhere in this file.

♻️ Proposed fix
         where = " AND ".join(filters)
-        rows, _ = self._run(f"SELECT count(*) FROM {index_name} WHERE {where}")
-        n = rows[0][0]
-        if n:
-            self._run(f"DELETE FROM {index_name} WHERE {where}", fetch=False)
-        return n
+        try:
+            rows, _ = self._run(f"SELECT count(*) FROM {index_name} WHERE {where}")
+            n = rows[0][0]
+            if n:
+                self._run(f"DELETE FROM {index_name} WHERE {where}", fetch=False)
+            return n
+        except Exception as e:
+            logger.error(f"SereneDB delete error on {index_name}: {e}")
+            return 0
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/serenedb_conn.py` around lines 613 - 627, Update
DocStoreConnection.delete to wrap both _run calls—the count query and
conditional DELETE—in the same exception-handling pattern used by update,
logging the error and returning the method’s failure result instead of
propagating database exceptions. Preserve the existing early returns and
successful row-count behavior.
rag/utils/serenedb_conn.py-589-593 (1)

589-593: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

update()'s scalar "remove" branch skips column-name validation.

When new_value["remove"] is a plain string, items = {v: None} makes kk = v (the raw field name), and f"{kk} = NULL" is built without checking kk in COLUMN_DDL — unlike the dict form just below it (elif kk in ARRAY_COLUMNS) and every other identifier path in this file (_get_filters, the k in COLUMN_DDL branches). This both allows setting arbitrary/unintended columns to NULL and reopens the injection surface that the rest of the file carefully closes by validating identifiers.

🛡️ Proposed fix
                 for kk, vv in items.items():
                     if vv is None:
-                        sets.append(f"{kk} = NULL")
+                        if kk in COLUMN_DDL:
+                            sets.append(f"{kk} = NULL")
                     elif kk in ARRAY_COLUMNS:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/serenedb_conn.py` around lines 589 - 593, Validate the scalar
remove field name before constructing the SQL assignment in update(). In the
remove branch around items = {v: None}, require the raw field name to be present
in COLUMN_DDL, matching the validation used for dict-form removals and other
identifier paths, and reject invalid names before appending the “= NULL” clause.
rag/utils/serenedb_conn.py-211-217 (1)

211-217: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

URL-encode the SereneDB credentials and avoid hardcoding the connection pool size.

  • Build the DSN with urllib.parse.quote_plus(user) and quote_plus(password) so credentials containing :, @, or / don’t corrupt the parsed URI.
  • Read the pool size from config instead of assuming maxconn=8; with psycopg2 pool exhaustion, getconn() raises PoolError once maxconn is reached rather than waiting, so concurrency above the configured pool can explode as unhandled PoolErrors instead of using the intended limit.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/serenedb_conn.py` around lines 211 - 217, Update the SereneDB
connection setup around the DSN construction to import and apply
urllib.parse.quote_plus to both user and password before interpolating them into
the PostgreSQL URI. In the same connection-pool initialization flow, read
maxconn from the SereneDB configuration with the established default behavior
instead of hardcoding 8, preserving the configured concurrency limit.
rag/utils/serenedb_conn.py-477-485 (1)

477-485: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

agg_field isn't validated before SQL interpolation, unlike every other identifier path in this file.

_get_filters validates k against COLUMN_DDL/ARRAY_COLUMNS before use as an identifier, and the filter-only branch validates order_by fields against COLUMN_DDL. _aggregation's agg_field, however, is interpolated directly into SELECT {agg_field}, count(*) FROM ... GROUP BY {agg_field} (and the unnest({agg_field}) variant) with no such check. If agg_fields is ever populated from anything other than a fixed internal call site, this is a real SQL injection vector.

🛡️ Proposed fix
     def _aggregation(self, result: SearchResult, index_name: str, agg_fields, filters_expr):
         for agg_field in agg_fields:
+            if agg_field not in COLUMN_DDL:
+                continue
             if agg_field in ARRAY_COLUMNS:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/serenedb_conn.py` around lines 477 - 485, Validate each agg_field
in _aggregation against the permitted identifier sets, using the same
COLUMN_DDL/ARRAY_COLUMNS validation pattern as _get_filters and the order_by
path, before interpolating it into either SQL query. Reject or skip invalid
fields consistently with the existing identifier-validation behavior, while
preserving aggregation for valid scalar and array fields.
internal/engine/serenedb/search.go-55-113 (1)

55-113: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Defer offset until after merging multi-table results.

Search() pushes the same offset/limit into each table’s SQL, then merges, sorts, and slices only by limit. Offsets inside each table skip that table’s local top rows independently, so page 2+ across two or more tables can return the wrong global page. For score/beta-filtered search with multiple req.IndexNames, fetch from offset 0, merge, then apply the single global [offset : offset+limit] slice.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/search.go` around lines 55 - 113, Update Search to
avoid applying offset per table for scored or beta-filtered multi-table
searches: use offset 0 when building each table query, then merge and sort
result.Chunks before applying one global offset and limit slice. Preserve
existing behavior for single-table or unscored searches, and ensure pagination
handles offsets beyond the merged result length safely.
internal/engine/serenedb/client.go-108-108 (1)

108-108: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

sslmode=disable is hardcoded with no config escape hatch.

SereneDBConfig has no TLS knob, so any non-loopback deployment sends credentials and document content in cleartext unless operators bypass the whole config via SERENEDB_DSN. Consider adding an optional ssl_mode field (defaulting to disable to preserve local-compose behavior).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/client.go` at line 108, Add an optional ssl_mode
setting to SereneDBConfig and use it when constructing the SereneDB connection
DSN instead of hardcoding "sslmode=disable". Default the setting to "disable"
when unset to preserve existing local-compose behavior, while allowing
configured deployments to select a secure TLS mode.
internal/engine/serenedb/client.go-45-45 (1)

45-45: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

DSN redaction misses URL-form credentials.

dsnPasswordRe only matches the password= keyword form. SERENEDB_DSN may legitimately be a URL (postgres://user:secret@host:7890/db), which lib/pq accepts; in that case the password is logged verbatim at Line 76 and embedded in the ping error at Line 74.

🔒 Proposed fix
-var dsnPasswordRe = regexp.MustCompile(`(password=)[^ ]+`)
+var (
+	dsnPasswordRe    = regexp.MustCompile(`(password=)[^ ]+`)
+	dsnURLPasswordRe = regexp.MustCompile(`(://[^:/@]+:)[^@]+@`)
+)
+
+func redactDSN(dsn string) string {
+	s := dsnPasswordRe.ReplaceAllString(dsn, "${1}***")
+	return dsnURLPasswordRe.ReplaceAllString(s, "${1}***@")
+}
-	e := &serenedbEngine{db: db, dsnSafe: dsnPasswordRe.ReplaceAllString(dsn, "${1}***")}
+	e := &serenedbEngine{db: db, dsnSafe: redactDSN(dsn)}

Also applies to: 68-68, 74-76

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/client.go` at line 45, Update dsnPasswordRe and the
redaction flow in the SereneDB client to also mask passwords embedded in
URL-form DSNs such as postgres://user:secret@host:port/db. Ensure the sanitized
DSN is used for both ping errors and the log at the existing call sites, while
preserving redaction of keyword-form password= credentials.
internal/engine/serenedb/common.go-89-98 (1)

89-98: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Silently dropping unrecognized condition keys widens UPDATE/DELETE scope.

Any key that is not a known column, exists, or must_not is skipped without a trace. On the write paths this is destructive rather than merely lossy: DeleteChunks(ctx, {"unknown_field": "x"}, base, kb) reduces to WHERE kb_id = '<kb>' and wipes the entire dataset (chunk.go Lines 365-372); UpdateChunks has the same shape. Return an error (or at minimum log and refuse the write) when a condition key cannot be translated.

Also applies to: 140-143

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/common.go` around lines 89 - 98, Update buildFilters
and its callers in the write paths, including DeleteChunks and UpdateChunks, to
detect condition keys that are neither known columns nor exists or must_not.
Propagate an error, or otherwise refuse the write, instead of silently omitting
unsupported keys; ensure no UPDATE or DELETE proceeds with only the base
knowledge-base filter when translation fails.
internal/engine/serenedb/common.go-124-139 (1)

124-139: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Empty list value produces invalid SQL col IN ().

The nil/empty-string guards at Lines 91-97 do not catch an empty slice, so a condition like {"doc_id": []interface{}{}} renders doc_id IN (), which fails to parse and turns the whole search/update/delete into an error. The array-column branch already guards this with len(ors) > 0.

🐛 Proposed fix
 		case isKnownColumn(k):
-			if list, ok := v.([]interface{}); ok {
+			if list, ok := v.([]interface{}); ok {
+				if len(list) == 0 {
+					continue
+				}
 				parts := make([]string, 0, len(list))
 				for _, x := range list {
 					parts = append(parts, escapeLiteral(x))
 				}
 				filters = append(filters, fmt.Sprintf("%s IN (%s)", k, strings.Join(parts, ", ")))
-			} else if list, ok := v.([]string); ok {
+			} else if list, ok := v.([]string); ok {
+				if len(list) == 0 {
+					continue
+				}
 				parts := make([]string, 0, len(list))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/common.go` around lines 124 - 139, Update the
known-column list handling in the filter-building logic to detect empty
[]interface{} and []string values before generating an IN clause. Skip or
otherwise handle empty lists consistently with the existing array-column guard
so no condition renders invalid SQL such as IN ().
internal/engine/serenedb/schema.go-151-158 (1)

151-158: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Table names are interpolated into DDL/DML without validation or quoting.

chunkTableName(baseName) and buildMetadataTableName(tenantID) feed raw strings straight into CREATE TABLE, DROP TABLE, DELETE FROM, and SELECT statements across chunk.go, metadata.go, and document.go. Identifiers cannot be parameterized, so the only defense is validation at this boundary. Add a strict guard here (and return an error) so a malformed or attacker-influenced tenant/index name cannot alter the statement.

🔒 Suggested guard
+var safeIdentRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,55}$`)
+
+// validIdentifier reports whether a name is safe to interpolate as a SQL identifier.
+func validIdentifier(name string) bool { return safeIdentRe.MatchString(name) }

Then reject non-conforming baseName/tenantID in CreateChunkStore, CreateMetadataStore, ensureSkillTable, and the lookup paths.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/schema.go` around lines 151 - 158, Validate
identifiers in chunkTableName and buildMetadataTableName against a strict
safe-name policy before constructing table names, and change these helpers to
return errors for invalid baseName or tenantID. Propagate those errors through
CreateChunkStore, CreateMetadataStore, ensureSkillTable, and all chunk,
metadata, and document lookup paths so no unvalidated identifier reaches DDL or
DML statements.
internal/engine/serenedb/client.go-184-189 (1)

184-189: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

tableExists treats every error as "table absent", masking connectivity and permission failures.

The probe cannot distinguish "relation does not exist" from a dropped connection, timeout, or permission error. Callers rely on it for control flow, so a transient DB failure silently degrades into wrong success: DeleteChunks returns (0, nil), GetChunk returns (nil, nil), DropChunkStore returns nil, and InsertChunks re-runs DDL. Inspect the error and only report false for the undefined-table condition (pq error code 42P01), propagating anything else.

🛠️ Sketch
-// tableExists reports whether a relation exists by probing it.
-func (e *serenedbEngine) tableExists(ctx context.Context, tableName string) bool {
-	if err := e.exec(ctx, fmt.Sprintf("SELECT 1 FROM %s LIMIT 0", tableName)); err != nil {
-		return false
-	}
-	return true
-}
+// tableExists reports whether a relation exists by probing it. Errors other
+// than undefined_table are surfaced so callers do not mistake an outage for a
+// missing table.
+func (e *serenedbEngine) tableExists(ctx context.Context, tableName string) (bool, error) {
+	err := e.exec(ctx, fmt.Sprintf("SELECT 1 FROM %s LIMIT 0", tableName))
+	if err == nil {
+		return true, nil
+	}
+	var pqErr *pq.Error
+	if errors.As(err, &pqErr) && pqErr.Code == "42P01" {
+		return false, nil
+	}
+	return false, err
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/client.go` around lines 184 - 189, Update
serenedbEngine.tableExists to distinguish a missing relation from operational
failures: return false only when the exec error is a PostgreSQL undefined-table
error with code 42P01, and propagate all other errors through the method’s
callers. Adjust the method signature and callers as needed so connectivity,
timeout, and permission failures are not treated as an absent table.
internal/engine/serenedb/client.go-103-113 (1)

103-113: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Quote lib/pq DSN values with escaping

buildDSN emits a keyword DSN, where unquoted values containing spaces are split into separate parameters and literal quotes/backslashes can also be parsed incorrectly. Escape \ and ' before wrapping values in single quotes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/client.go` around lines 103 - 113, Update buildDSN
so every lib/pq keyword-DSN value is escaped and wrapped in single quotes,
including host, user, dbName, and the optional password: escape backslashes and
single quotes before quoting. Keep the existing parameter assembly and sslmode
value intact.
internal/engine/serenedb/schema.go-36-37 (1)

36-37: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Don’t assume SereneDB accepts IF NOT EXISTS here.

SereneDB’s documented dictionary DDL is CREATE TEXT SEARCH DICTIONARY ...; IF NOT EXISTS is not part of the supported syntax. Since CreateChunkStore executes chunkTableDDL, the second creation for the same tenant store will fail instead of being idempotent. Replace this with a supported idempotent pattern, such as DROP TEXT SEARCH DICTIONARY IF EXISTS followed by CREATE, or skip/create conditionally after checking the dictionary exists.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/schema.go` around lines 36 - 37, Update
dictionaryDDL to use SereneDB-supported syntax by removing IF NOT EXISTS and
implement idempotency in the CreateChunkStore flow: drop the existing dictionary
with DROP TEXT SEARCH DICTIONARY IF EXISTS before creating it, or check for its
existence and create only when absent. Preserve successful repeated creation for
the same tenant store.
internal/engine/serenedb/metadata.go-185-188 (1)

185-188: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

SelectFields is interpolated into the SELECT list unvalidated.

Any caller-supplied string becomes raw SQL (subqueries, *, expressions). Validate each entry against docMetaDDL before joining.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/metadata.go` around lines 185 - 188, Validate every
entry in req.SelectFields against the allowed columns defined by docMetaDDL
before constructing fields in the metadata query. Reject or safely handle any
unknown or non-column value, including expressions, subqueries, and wildcard
input, while preserving the existing default fields behavior when SelectFields
is empty.
internal/engine/serenedb/metadata.go-100-122 (1)

100-122: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Merge update is a read-modify-write with no transaction.

loadMetaFields then UPDATE/INSERT outside a transaction: concurrent updates to the same (id, kb_id) lose keys, and two concurrent misses both take the insert path (the second failing on the id conflict since there is no ON CONFLICT here). Wrap the read and write in one transaction, or do the merge server-side in a single upsert.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/metadata.go` around lines 100 - 122, Update
UpdateMetadata to perform the metadata merge atomically: either wrap
loadMetaFields and the subsequent INSERT/UPDATE in one transaction, or replace
them with a single server-side upsert that merges existing and incoming fields.
Preserve the existing merge semantics for the same (docID, datasetID) record and
handle concurrent missing rows without duplicate-key failures.
internal/engine/serenedb/chunk.go-382-398 (1)

382-398: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

GetChunk reports a DB failure as "chunk not found".

Line 394 collapses err into nil, nil, so a connection drop or SQL error is indistinguishable from a missing row. Callers will treat transient failures as deleted chunks.

🐛 Proposed fix
 	rows, err := e.queryMaps(ctx, query, chunkID)
-	if err != nil || len(rows) == 0 {
+	if err != nil {
+		return nil, fmt.Errorf("serenedb: get chunk %s from %s: %w", chunkID, tableName, err)
+	}
+	if len(rows) == 0 {
 		return nil, nil
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/chunk.go` around lines 382 - 398, Update
serenedbEngine.GetChunk so queryMaps errors are returned to the caller instead
of being collapsed into a missing-chunk result. Preserve the existing nil, nil
behavior only when the query succeeds with no rows, while continuing to return
the first row on success.
internal/engine/serenedb/chunk.go-360-378 (1)

360-378: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Avoid template SQL for DELETE predicates. buildFilters is an engine-internal path, but DeleteChunks/DeleteMetadata call it from public methods and render unknown column strings directly into ExecContext statements. Whitelist keys against the specific table DDL and emit parameter placeholders for scalar/list values instead of concatenating raw SQL text.

  • internal/engine/serenedb/chunk.go#L360-L378
  • internal/engine/serenedb/metadata.go#L156-L172
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/chunk.go` around lines 360 - 378, Update
DeleteChunks in internal/engine/serenedb/chunk.go at lines 360-378 and
DeleteMetadata in internal/engine/serenedb/metadata.go at lines 156-172 to
validate condition keys against each table’s DDL whitelist, generate
parameterized predicates with placeholders for scalar and list values, and pass
the corresponding arguments to ExecContext instead of rendering raw keys or
values into SQL; preserve the existing no-table, empty-filter, execution-error,
and affected-row behavior.

Source: Linters/SAST tools

internal/engine/serenedb/sql.go-48-58 (1)

48-58: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Limit RunSQL to safe, scoped reads.

RunSQL passes LLM-generated SQL straight through queryMaps without applying tableName, kbIDs, or a read-only execution path. Since SereneDB stores chunk rows in a tenant-wide table keyed by kb_id, any generated SELECT missing that predicate can read other datasets, and UPDATE/DELETE/DROP statements can mutate/drop data. Reject statements that are not read-only by nature and enforce kbIDs scope in SereneDB’s execution path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/sql.go` around lines 48 - 58, Update
serenedbEngine.RunSQL and its queryMaps execution path to reject non-read-only
SQL, allowing only safe read statements and preventing UPDATE, DELETE, DROP, or
other mutations. Apply tableName and kbIDs as enforced scope predicates in the
SereneDB query execution, ensuring every read is restricted to the requested
knowledge bases and never exposes tenant-wide rows; preserve the existing error
wrapping and empty-result behavior.
🟡 Minor comments (5)
internal/engine/serenedb/integration_test.go-17-24 (1)

17-24: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the repository's build.sh in the run instructions.

The header tells maintainers to run go test -run Integration ./internal/engine/serenedb/, which skips the required CGO flags and native library setup.

As per coding guidelines: "Do not default to raw go test, go build, or IDE Run/Debug; use the repository's build.sh so required CGO flags and native libraries are configured" and "Run the narrowest relevant validation after changes: ... package-scoped bash build.sh --test ... for Go work".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/integration_test.go` around lines 17 - 24, Update
the run instructions in the integration test header to use the repository’s
build.sh test command instead of raw go test, including the Integration filter
and package scope so CGO flags and native libraries are configured.

Source: Coding guidelines

internal/engine/serenedb/integration_test.go-49-51 (1)

49-51: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

t.TempDir() captured in a sync.Once outlives its owning test.

The directory is cleaned up when the first test that ran the Once finishes, so TestIntegrationMetadata logs into a removed path. Use os.MkdirTemp (or os.DevNull) for the process-wide logger.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/integration_test.go` around lines 49 - 51, The
process-wide logger initialized by logOnce must not use t.TempDir(), whose
cleanup is tied to the first test. Replace the temporary path in the logOnce
initializer with a process-independent destination created via os.MkdirTemp or
os.DevNull, while preserving the existing common.Init setup.
internal/engine/serenedb/sql.go-36-43 (1)

36-43: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

hasLimitRe matches a LIMIT anywhere, so the bound is easy to bypass.

SELECT * FROM (SELECT id FROM t LIMIT 5) x (or any statement containing the word limit in a string literal or quoted identifier) skips the appended LIMIT, leaving the outer query unbounded — the exact case this guard exists to prevent. Consider wrapping the statement (SELECT * FROM (<txt>) _b LIMIT n) instead of pattern-matching, or anchor the check to a trailing LIMIT <n>.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/sql.go` around lines 36 - 43, Update boundRunSQL so
inner LIMIT clauses, string literals, and quoted identifiers cannot bypass the
outer row bound; replace the broad hasLimitRe guard with wrapping the eligible
statement in an outer SELECT with LIMIT, or otherwise detect only a trailing
top-level LIMIT while preserving existing trimming and limit conditions.
internal/engine/serenedb/chunk.go-145-150 (1)

145-150: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Vector values that fail coercion are dropped silently.

If toFloatSlice can't coerce (e.g. []string, or a []interface{} containing a non-numeric), the key is skipped entirely: the row is inserted with no embedding and no error, so retrieval degrades silently. Return an error (or at minimum log) instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/chunk.go` around lines 145 - 150, Update the
vector-column handling around toFloatSlice so coercion failures are not silently
ignored: when a key matches vectorColumnPattern but toFloatSlice returns false,
propagate an error from the enclosing row-processing function (or use the
established error/logging mechanism if propagation is unavailable). Preserve the
existing vecCols assignment for successful conversions and continue behavior for
non-vector fields.
internal/engine/serenedb/integration_test.go-102-106 (1)

102-106: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Teardown does not drop the table, contradicting the comment.

DropChunkStore with a non-empty datasetID only deletes that dataset's rows (chunk.go Lines 87-89); the tenant table and its inverted index survive the run. A rerun with a different vectorSize will then insert against the stale schema and fail confusingly. Pass an empty dataset id to actually drop.

💚 Proposed fix
-	// Start clean and always tear down the throwaway table.
-	_ = e.DropChunkStore(ctx, base, kb)
-	defer func() { _ = e.DropChunkStore(ctx, base, kb) }()
+	// Start clean and always tear down the throwaway table (empty dataset id
+	// drops the whole tenant table, not just this dataset's rows).
+	_ = e.DropChunkStore(ctx, base, "")
+	defer func() { _ = e.DropChunkStore(ctx, base, "") }()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/integration_test.go` around lines 102 - 106, Update
both DropChunkStore calls in the integration test to pass an empty dataset ID so
teardown removes the tenant table and inverted index, preserving the clean-start
and deferred cleanup behavior described by the comment.
🧹 Nitpick comments (8)
rag/utils/serenedb_conn.py (2)

560-576: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

_insert_doc_meta swallows per-row errors without logging.

Errors are appended to errors but never logged, unlike the parallel main insert() path which calls logger.error(...) on the same kind of failure (line 553-555). As per coding guidelines ("Add logging for new flows" for **/*.py), this metadata-insert failure path should log too, or a failed metadata write for a document will be invisible in the logs.

📝 Proposed fix
             except Exception as e:
+                logger.error(f"SereneDB doc-meta insert error on {index_name}: {e}")
                 errors.append(str(e))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/serenedb_conn.py` around lines 560 - 576, Update the exception
handler in _insert_doc_meta to log each failed metadata insertion with the
existing logger, matching the error logging behavior used by insert(), while
preserving the current errors.append(str(e)) return behavior.

Source: Coding guidelines


208-219: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent except Exception: pass on config load masks real misconfiguration.

If get_base_config("serenedb", ...) raises for a reason other than "not configured" (e.g. malformed config), the error is discarded with no trace, and initialization silently falls through to the env-var/hardcoded default DSN. As per coding guidelines ("Add logging for new flows" for **/*.py), this should at least log at debug/warning level.

📝 Proposed fix
         except Exception:
-            pass
+            logger.debug("No SereneDB config found via get_base_config; falling back to env/default DSN", exc_info=True)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/utils/serenedb_conn.py` around lines 208 - 219, Update the
configuration-loading try/except around get_base_config in the SereneDB
connection initialization to log the caught exception at an appropriate debug or
warning level before falling back to environment variables or the default DSN.
Preserve the existing fallback behavior while ensuring configuration-load
failures are no longer silently discarded.

Source: Coding guidelines

internal/engine/serenedb/serenedb_test.go (1)

142-157: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add decodeValue coverage for a vector/float-array column.

Existing cases cover string arrays, JSON, scalars, and nil, but not a q_N_vec-style FLOAT[] column — the exact data type the fusion/vector search paths depend on. Worth adding a case asserting it decodes to []float64 (or documenting the actual returned type) so a serialization regression on vector columns doesn't slip through silently.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/serenedb_test.go` around lines 142 - 157, Extend
TestDecodeValue with a q_N_vec-style FLOAT[] input and assert that decodeValue
returns the expected vector representation, preferably []float64 with the
correct values. If the implementation returns another type, document and assert
that actual type instead.
internal/engine/serenedb/search.go (1)

213-255: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Fragile 22-argument positional fmt.Sprintf in buildFusionSQL.

I traced every %s/%d placeholder against the argument list and it's currently correct, but a flat 22-element positional arg list matched against a multi-line SQL template is a classic footgun: adding/removing one placeholder silently shifts every argument after it with no compiler error. Consider at least annotating each argument with an inline comment naming which placeholder it fills, or building the query with named substitutions, to make future edits safe.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/search.go` around lines 213 - 255, Make the argument
mapping in buildFusionSQL explicit and maintainable instead of relying on the
fragile positional fmt.Sprintf list. Use named substitutions or clearly
associate each SQL placeholder with its corresponding value, preserving the
current generated query and all existing argument values.
internal/engine/serenedb/client.go (1)

56-58: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Failed type assertion silently degrades to defaults.

If cfg is ever a non-*server.SereneDBConfig (or a nil interface), sdbCfg becomes nil and the engine quietly connects to serenedb:7890/postgres instead of reporting a misconfiguration. Return an error unless SERENEDB_DSN is set.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/client.go` around lines 56 - 58, Update NewEngine to
validate the cfg assertion before calling buildDSN: if cfg is not a non-nil
*server.SereneDBConfig, return a configuration error unless the SERENEDB_DSN
environment override is set; otherwise preserve the DSN override path and
existing engine initialization.
internal/engine/serenedb/document.go (1)

74-97: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

BulkIndex issues one statement per document and duplicates IndexDocument.

buildUpsert already accepts multiple rows, and InsertChunks (chunk.go Lines 236-262) has the group-by-column-set logic. Extract that grouping into a shared helper and reuse it here so bulk indexing is a handful of multi-row upserts instead of len(docs) round trips. It also removes the copy/paste of Lines 90-91.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/document.go` around lines 74 - 97, Refactor
BulkIndex to group documents by their column sets using a shared helper
extracted from InsertChunks, then build and execute one multi-row upsert per
group via buildUpsert instead of one statement per document. Reuse the shared
insertion logic to eliminate the duplicated per-document upsert flow while
preserving ensureSkillTable and bulk error handling.
internal/engine/serenedb/metadata.go (1)

78-96: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Batch the metadata upsert.

One round trip per record, non-atomic on partial failure. buildUpsert (chunk.go Line 268) already renders multi-row ON CONFLICT statements for a fixed column set — reuse it here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/metadata.go` around lines 78 - 96, Update
InsertMetadata to batch metadata upserts using the existing buildUpsert helper
from chunk.go, rather than executing one statement per record. Preserve the
current metadata table creation and empty-input behavior, pass the fixed
id/kb_id/meta_fields columns with converted metaFieldsJSON values, and propagate
errors while keeping each batch operation atomic.
internal/engine/serenedb/chunk.go (1)

219-264: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

InsertChunks mutates the caller's chunk maps and has no atomicity across groups.

Two points:

  • Line 245 writes kb_id into the caller-owned map, so a retry with a different datasetID will keep the first stamp (the !ok guard skips it). Stamp into the prepared row instead of the input.
  • Groups are executed as independent statements; a mid-loop failure leaves some column-set groups committed. Wrap the group loop in a transaction.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/serenedb/chunk.go` around lines 219 - 264, Update
InsertChunks so dataset stamping does not mutate caller-owned chunk maps: apply
the fallback datasetID while constructing each prepared row, preserving any
explicit kb_id. Execute all buildUpsert statements for the groups within one
transaction, committing only after every group succeeds and rolling back on any
error.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/engine/serenedb/chunk.go`:
- Around line 315-356: Update buildUpdateSets so nil-valued entries in the
remove branch are emitted only when their column key passes the same appropriate
whitelist validation used for update identifiers, such as isArrayColumn,
isJSONColumn, or columnDDL. Do not interpolate an unvalidated kk into the SQL
assignment; preserve existing array-removal behavior and ordering for valid
keys.

In `@rag/utils/serenedb_conn.py`:
- Around line 383-385: Update the FusionExpr weighted_sum handling to preserve
both independent weights from fusion_params["weights"], assigning the first
value to text_weight and the second to vector_weight. In _fusion_search, use
text_weight directly for the lexical/BM25 score instead of deriving it as 1.0 -
vector_weight, while retaining vector_weight for the dense score so the standard
"0.001,1" configuration blends both signals.

---

Major comments:
In `@internal/engine/serenedb/chunk.go`:
- Around line 382-398: Update serenedbEngine.GetChunk so queryMaps errors are
returned to the caller instead of being collapsed into a missing-chunk result.
Preserve the existing nil, nil behavior only when the query succeeds with no
rows, while continuing to return the first row on success.
- Around line 360-378: Update DeleteChunks in internal/engine/serenedb/chunk.go
at lines 360-378 and DeleteMetadata in internal/engine/serenedb/metadata.go at
lines 156-172 to validate condition keys against each table’s DDL whitelist,
generate parameterized predicates with placeholders for scalar and list values,
and pass the corresponding arguments to ExecContext instead of rendering raw
keys or values into SQL; preserve the existing no-table, empty-filter,
execution-error, and affected-row behavior.

In `@internal/engine/serenedb/client.go`:
- Line 108: Add an optional ssl_mode setting to SereneDBConfig and use it when
constructing the SereneDB connection DSN instead of hardcoding
"sslmode=disable". Default the setting to "disable" when unset to preserve
existing local-compose behavior, while allowing configured deployments to select
a secure TLS mode.
- Line 45: Update dsnPasswordRe and the redaction flow in the SereneDB client to
also mask passwords embedded in URL-form DSNs such as
postgres://user:secret@host:port/db. Ensure the sanitized DSN is used for both
ping errors and the log at the existing call sites, while preserving redaction
of keyword-form password= credentials.
- Around line 184-189: Update serenedbEngine.tableExists to distinguish a
missing relation from operational failures: return false only when the exec
error is a PostgreSQL undefined-table error with code 42P01, and propagate all
other errors through the method’s callers. Adjust the method signature and
callers as needed so connectivity, timeout, and permission failures are not
treated as an absent table.
- Around line 103-113: Update buildDSN so every lib/pq keyword-DSN value is
escaped and wrapped in single quotes, including host, user, dbName, and the
optional password: escape backslashes and single quotes before quoting. Keep the
existing parameter assembly and sslmode value intact.

In `@internal/engine/serenedb/common.go`:
- Around line 89-98: Update buildFilters and its callers in the write paths,
including DeleteChunks and UpdateChunks, to detect condition keys that are
neither known columns nor exists or must_not. Propagate an error, or otherwise
refuse the write, instead of silently omitting unsupported keys; ensure no
UPDATE or DELETE proceeds with only the base knowledge-base filter when
translation fails.
- Around line 124-139: Update the known-column list handling in the
filter-building logic to detect empty []interface{} and []string values before
generating an IN clause. Skip or otherwise handle empty lists consistently with
the existing array-column guard so no condition renders invalid SQL such as IN
().

In `@internal/engine/serenedb/metadata.go`:
- Around line 185-188: Validate every entry in req.SelectFields against the
allowed columns defined by docMetaDDL before constructing fields in the metadata
query. Reject or safely handle any unknown or non-column value, including
expressions, subqueries, and wildcard input, while preserving the existing
default fields behavior when SelectFields is empty.
- Around line 100-122: Update UpdateMetadata to perform the metadata merge
atomically: either wrap loadMetaFields and the subsequent INSERT/UPDATE in one
transaction, or replace them with a single server-side upsert that merges
existing and incoming fields. Preserve the existing merge semantics for the same
(docID, datasetID) record and handle concurrent missing rows without
duplicate-key failures.

In `@internal/engine/serenedb/schema.go`:
- Around line 151-158: Validate identifiers in chunkTableName and
buildMetadataTableName against a strict safe-name policy before constructing
table names, and change these helpers to return errors for invalid baseName or
tenantID. Propagate those errors through CreateChunkStore, CreateMetadataStore,
ensureSkillTable, and all chunk, metadata, and document lookup paths so no
unvalidated identifier reaches DDL or DML statements.
- Around line 36-37: Update dictionaryDDL to use SereneDB-supported syntax by
removing IF NOT EXISTS and implement idempotency in the CreateChunkStore flow:
drop the existing dictionary with DROP TEXT SEARCH DICTIONARY IF EXISTS before
creating it, or check for its existence and create only when absent. Preserve
successful repeated creation for the same tenant store.

In `@internal/engine/serenedb/search.go`:
- Around line 55-113: Update Search to avoid applying offset per table for
scored or beta-filtered multi-table searches: use offset 0 when building each
table query, then merge and sort result.Chunks before applying one global offset
and limit slice. Preserve existing behavior for single-table or unscored
searches, and ensure pagination handles offsets beyond the merged result length
safely.

In `@internal/engine/serenedb/sql.go`:
- Around line 48-58: Update serenedbEngine.RunSQL and its queryMaps execution
path to reject non-read-only SQL, allowing only safe read statements and
preventing UPDATE, DELETE, DROP, or other mutations. Apply tableName and kbIDs
as enforced scope predicates in the SereneDB query execution, ensuring every
read is restricted to the requested knowledge bases and never exposes
tenant-wide rows; preserve the existing error wrapping and empty-result
behavior.

In `@rag/utils/serenedb_conn.py`:
- Around line 197-225: Synchronize initialization in SereneDBConnection.__init__
using the existing _instance_lock so only one thread can initialize the
singleton at a time. Check _initialized while holding the lock, perform
construction of _pool, _known_tables, _known_lock, and _dsn_display, then set
_initialized only after all fields are ready.
- Around line 279-286: The delete_idx method must also skip dropping
tenant-shared ragflow_doc_meta_* tables when called with a dataset_id; update
its guard so any per-KB deletion of a doc-meta index returns before DROP INDEX
or DROP TABLE, while still allowing the tenant-level removal path to drop the
shared table.
- Around line 613-627: Update DocStoreConnection.delete to wrap both _run
calls—the count query and conditional DELETE—in the same exception-handling
pattern used by update, logging the error and returning the method’s failure
result instead of propagating database exceptions. Preserve the existing early
returns and successful row-count behavior.
- Around line 589-593: Validate the scalar remove field name before constructing
the SQL assignment in update(). In the remove branch around items = {v: None},
require the raw field name to be present in COLUMN_DDL, matching the validation
used for dict-form removals and other identifier paths, and reject invalid names
before appending the “= NULL” clause.
- Around line 211-217: Update the SereneDB connection setup around the DSN
construction to import and apply urllib.parse.quote_plus to both user and
password before interpolating them into the PostgreSQL URI. In the same
connection-pool initialization flow, read maxconn from the SereneDB
configuration with the established default behavior instead of hardcoding 8,
preserving the configured concurrency limit.
- Around line 477-485: Validate each agg_field in _aggregation against the
permitted identifier sets, using the same COLUMN_DDL/ARRAY_COLUMNS validation
pattern as _get_filters and the order_by path, before interpolating it into
either SQL query. Reject or skip invalid fields consistently with the existing
identifier-validation behavior, while preserving aggregation for valid scalar
and array fields.

---

Minor comments:
In `@internal/engine/serenedb/chunk.go`:
- Around line 145-150: Update the vector-column handling around toFloatSlice so
coercion failures are not silently ignored: when a key matches
vectorColumnPattern but toFloatSlice returns false, propagate an error from the
enclosing row-processing function (or use the established error/logging
mechanism if propagation is unavailable). Preserve the existing vecCols
assignment for successful conversions and continue behavior for non-vector
fields.

In `@internal/engine/serenedb/integration_test.go`:
- Around line 17-24: Update the run instructions in the integration test header
to use the repository’s build.sh test command instead of raw go test, including
the Integration filter and package scope so CGO flags and native libraries are
configured.
- Around line 49-51: The process-wide logger initialized by logOnce must not use
t.TempDir(), whose cleanup is tied to the first test. Replace the temporary path
in the logOnce initializer with a process-independent destination created via
os.MkdirTemp or os.DevNull, while preserving the existing common.Init setup.
- Around line 102-106: Update both DropChunkStore calls in the integration test
to pass an empty dataset ID so teardown removes the tenant table and inverted
index, preserving the clean-start and deferred cleanup behavior described by the
comment.

In `@internal/engine/serenedb/sql.go`:
- Around line 36-43: Update boundRunSQL so inner LIMIT clauses, string literals,
and quoted identifiers cannot bypass the outer row bound; replace the broad
hasLimitRe guard with wrapping the eligible statement in an outer SELECT with
LIMIT, or otherwise detect only a trailing top-level LIMIT while preserving
existing trimming and limit conditions.

---

Nitpick comments:
In `@internal/engine/serenedb/chunk.go`:
- Around line 219-264: Update InsertChunks so dataset stamping does not mutate
caller-owned chunk maps: apply the fallback datasetID while constructing each
prepared row, preserving any explicit kb_id. Execute all buildUpsert statements
for the groups within one transaction, committing only after every group
succeeds and rolling back on any error.

In `@internal/engine/serenedb/client.go`:
- Around line 56-58: Update NewEngine to validate the cfg assertion before
calling buildDSN: if cfg is not a non-nil *server.SereneDBConfig, return a
configuration error unless the SERENEDB_DSN environment override is set;
otherwise preserve the DSN override path and existing engine initialization.

In `@internal/engine/serenedb/document.go`:
- Around line 74-97: Refactor BulkIndex to group documents by their column sets
using a shared helper extracted from InsertChunks, then build and execute one
multi-row upsert per group via buildUpsert instead of one statement per
document. Reuse the shared insertion logic to eliminate the duplicated
per-document upsert flow while preserving ensureSkillTable and bulk error
handling.

In `@internal/engine/serenedb/metadata.go`:
- Around line 78-96: Update InsertMetadata to batch metadata upserts using the
existing buildUpsert helper from chunk.go, rather than executing one statement
per record. Preserve the current metadata table creation and empty-input
behavior, pass the fixed id/kb_id/meta_fields columns with converted
metaFieldsJSON values, and propagate errors while keeping each batch operation
atomic.

In `@internal/engine/serenedb/search.go`:
- Around line 213-255: Make the argument mapping in buildFusionSQL explicit and
maintainable instead of relying on the fragile positional fmt.Sprintf list. Use
named substitutions or clearly associate each SQL placeholder with its
corresponding value, preserving the current generated query and all existing
argument values.

In `@internal/engine/serenedb/serenedb_test.go`:
- Around line 142-157: Extend TestDecodeValue with a q_N_vec-style FLOAT[] input
and assert that decodeValue returns the expected vector representation,
preferably []float64 with the correct values. If the implementation returns
another type, document and assert that actual type instead.

In `@rag/utils/serenedb_conn.py`:
- Around line 560-576: Update the exception handler in _insert_doc_meta to log
each failed metadata insertion with the existing logger, matching the error
logging behavior used by insert(), while preserving the current
errors.append(str(e)) return behavior.
- Around line 208-219: Update the configuration-loading try/except around
get_base_config in the SereneDB connection initialization to log the caught
exception at an appropriate debug or warning level before falling back to
environment variables or the default DSN. Preserve the existing fallback
behavior while ensuring configuration-load failures are no longer silently
discarded.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cbc762ef-9ba7-446f-a010-f0e806655fca

📥 Commits

Reviewing files that changed from the base of the PR and between f4646d4 and 99b9bae.

📒 Files selected for processing (22)
  • api/db/services/dialog_service.py
  • api/db/services/doc_metadata_service.py
  • common/settings.py
  • internal/engine/engine.go
  • internal/engine/global.go
  • internal/engine/serenedb/chunk.go
  • internal/engine/serenedb/client.go
  • internal/engine/serenedb/common.go
  • internal/engine/serenedb/document.go
  • internal/engine/serenedb/integration_test.go
  • internal/engine/serenedb/metadata.go
  • internal/engine/serenedb/schema.go
  • internal/engine/serenedb/search.go
  • internal/engine/serenedb/serenedb.go
  • internal/engine/serenedb/serenedb_test.go
  • internal/engine/serenedb/sql.go
  • internal/server/config.go
  • rag/app/table.py
  • rag/nlp/search.py
  • rag/utils/serenedb_conn.py
  • rag/utils/table_es_metadata.py
  • test/unit_test/rag/utils/test_serenedb_conn.py

Comment thread internal/engine/serenedb/chunk.go Resolved
Comment thread rag/utils/serenedb_conn.py Resolved
@deadtrickster

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough sweep. Addressed the substantive findings in 54876b7f (SQL hardening) and dcee5ced (the remove-branch whitelist), across both the Go engine and the Python connector:

Fixed

  • Empty IN/array list now reduces to a never-match predicate instead of invalid col IN ().
  • DeleteChunks/UpdateChunks/DeleteMetadata reject conditions with unrecognized keys, so a stray key cannot widen the affected rows.
  • tableExists validates the identifier and queries the catalog, returning an error on connectivity/permission failures instead of masking them as "absent"; GetChunk surfaces query errors instead of "not found".
  • Table names validated against an identifier pattern before interpolation.
  • SearchMetadata keeps only real columns in the projection; the Python agg_field is validated before aggregation.
  • DSN: redact URL-form and keyword-form credentials, quote lib/pq values, URL-encode the Python DSN.
  • InsertChunks no longer mutates the caller's chunk maps.
  • Added unit tests for the empty-IN guard, key recognition, identifier validation, DSN redaction, and value quoting; the live integration suite passes against SereneDB 26.07.4 with the new catalog-based existence check.

Not changing

  • Fusion weights: not a real degradation. The fusion _score only orders first-stage candidates; the final ranking is recomputed by self.rerank(question, term_similarity_weight, vector_similarity_weight) (the DOC_ENGINE_SERENEDB branch in rag/nlp/search.py), which applies the user's real lexical and vector weights, and the content_ltks @@ branch still recalls text matches. So BM25 is applied end to end.
  • RunSQL scoping: this is the text-to-SQL passthrough, arbitrary SQL by design.
  • Multi-table offset merge: moot for the single-table-per-tenant layout (IndexNames is normally one table).

The remaining nitpicks (batching, no-transaction merges, the 22-arg fmt.Sprintf, extra logging) are noted as follow-ups; none are correctness or security issues.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/engine/serenedb/client.go`:
- Around line 211-212: Update tableExists so the existence query scopes
table_name to the resolved target schema rather than matching across schemas.
Ensure the lookup distinguishes an inaccessible table or schema, propagating the
database permission/connectivity error instead of returning (false, nil), while
retaining false only for a genuinely absent relation.
- Line 128: Update buildDSN so it no longer unconditionally appends
sslmode=disable; configure encrypted connections by default using the
appropriate secure lib/pq sslmode, while preserving an explicit opt-in path for
trusted local plaintext deployments. Keep SERENEDB_DSN behavior unchanged so
callers can provide their own sslmode.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 971d71a5-5830-4798-b561-6234af510d01

📥 Commits

Reviewing files that changed from the base of the PR and between dcee5ce and 54876b7.

📒 Files selected for processing (9)
  • internal/engine/serenedb/chunk.go
  • internal/engine/serenedb/client.go
  • internal/engine/serenedb/common.go
  • internal/engine/serenedb/document.go
  • internal/engine/serenedb/metadata.go
  • internal/engine/serenedb/schema.go
  • internal/engine/serenedb/search.go
  • internal/engine/serenedb/serenedb_test.go
  • rag/utils/serenedb_conn.py
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/engine/serenedb/document.go
  • internal/engine/serenedb/schema.go
  • internal/engine/serenedb/common.go
  • internal/engine/serenedb/serenedb_test.go
  • internal/engine/serenedb/metadata.go
  • internal/engine/serenedb/chunk.go
  • internal/engine/serenedb/search.go
  • rag/utils/serenedb_conn.py

Comment thread internal/engine/serenedb/client.go Resolved
Comment thread internal/engine/serenedb/client.go Resolved
@deadtrickster

Copy link
Copy Markdown
Contributor Author

@xugangqiang ping :-)

@JinHai-CN

Copy link
Copy Markdown
Member

@deadtrickster

We have reviewed the PR and confirm that the code is solid and ready to be merged. However, we’d like to raise a few points for consideration:

Merging code does not guarantee adoption. If we want users to actually use SereneDB with RAGFlow, we will need proper documentation that explains how to configure and deploy it, as well as how to handle data migration during upgrades.

RAGFlow is evolving rapidly. We are currently working on a new knowledge compilation feature, which will involve changes to the document engine. Once those changes are merged, SereneDB will need to stay in sync with ongoing development to remain compatible and fully functional.

To drive wider adoption, it would be highly beneficial to have blog posts or technical articles that highlight the improvements brought by integrating SereneDB with RAGFlow—covering aspects such as performance, functionality, and resource efficiency.

With that in mind, we’d like to ask: after we merge this PR, would you be able to take on the above responsibilities? If you are part of the SereneDB team and have ecosystem partners who can help drive collaboration, that would be an even better approach to ensure long-term success.

Looking forward to your thoughts.

@deadtrickster

deadtrickster commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor Author

@JinHai-CN glad to hear PR is solid and ready to be merged.

It is absolutely clear that this integration will be fully supported down the road.

As you see I'm already contributing fixes and improvements to RAGFlow. Same goes with SereneDB. So, this effort already proved to be mutually beneficial for both projects.

Blog posts are also planned exactly on topics you've already mentioned.
For the context: right now we have 2Tb+ ingestion test going - RAGFLow + SereneDB.

Would it be possible to have a post about SereneDB integration in the RAGFlow Blog (https://ragflow.io/blog)? Content will obviously be provided (if needed).

@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 31, 2026
@JinHai-CN

Copy link
Copy Markdown
Member

The ruff-format check did not pass:

┃  ruff-format ❯ 
Would reformat: test/unit_test/rag/utils/test_serenedb_conn.py
1 file would be reformatted, 7 files already formatted

exit status 1

@JinHai-CN

Copy link
Copy Markdown
Member

@deadtrickster We're very glad to know that you're committed to maintaining the integration long-term. The 2TB+ ingestion test sounds impressive. Once you have any articles or posts published, we'll be happy to share and promote them across our X (Twitter) and LinkedIn channels to help reach a wider audience.

@xugangqiang

Copy link
Copy Markdown
Contributor

@deadtrickster Please help to check CI issue - seems like relating to Lefthook

@deadtrickster
deadtrickster force-pushed the ik-serenedb-go-engine branch from b686d7a to f033c29 Compare July 31, 2026 10:24
@codecov

codecov Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (ef9feef) to head (01f75a5).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17375   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@deadtrickster
deadtrickster force-pushed the ik-serenedb-go-engine branch from f033c29 to 0de1afb Compare July 31, 2026 11:20
@deadtrickster

Copy link
Copy Markdown
Contributor Author

Rebased, also added serene to CI, let's see how it goes. I would appreciate if we could merge it soon.

@deadtrickster

Copy link
Copy Markdown
Contributor Author

CI didn't pick up serene jobs - I assume they come from main. I tested the whole thing locally tho.

@JinHai-CN

Copy link
Copy Markdown
Member

we currently have limited CI resources, and we are unable to add new workflows at this time. In fact, we are also planning to phase out the Elasticsearch CI workflow in the near future to free up capacity.

Additionally, could you please resolve those conflicts?

@coderabbitai coderabbitai Bot mentioned this pull request Aug 3, 2026
deadtrickster and others added 7 commits August 3, 2026 09:30
SereneDB is a PostgreSQL-wire engine whose single inverted index carries both a
scored text column (@@, BM25) and an IVF vector column (<#>, inner product), so
hybrid search is one SQL statement. This adds it as a selectable DocEngine
alongside Elasticsearch and Infinity.

The engine connects with database/sql + lib/pq (already a dependency) and emits
SQL directly; the query shapes mirror the Python SereneDBConnection that reached
Elasticsearch retrieval parity on a 247k-chunk corpus. It uses the
Elasticsearch/OceanBase storage model: one table per tenant with kb_id as a
filter column, so BM25 statistics are computed over the whole tenant corpus.

- internal/engine/serenedb: chunk CRUD, the four search modes (fulltext, vector,
  window-normalized BM25 + ANN fusion, filter), metadata store, skill index
  ops, and RunSQL, with pure SQL-builder unit tests that need no database.
- Registration: EngineSereneDB in engine.go and server/config.go, the factory
  arm in global.go, a SereneDBConfig struct, and the DOC_ENGINE=serenedb
  selection and config-mapping paths. The DSN override env var is SERENEDB_DSN.

FilterDocIdsByMetaPushdown returns nil (the interface's in-memory fall-back);
metadata pushdown is a later optimization. Minimum engine version: 26.07.4.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
End-to-end tests that drive the engine against a real SereneDB: chunk lifecycle
across all four search modes, get/scores, update/delete, and the metadata
lifecycle. Skipped unless SERENEDB_TEST_DSN points at a live instance, so the
default test run stays pure and CI-safe.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Registers serenedb as a selectable Python doc-store engine and teaches the
engine-type branch points about it. SereneDB is the plain-SQL sibling of
OceanBase (one table per tenant, kb_id filter column, ES field names kept
verbatim, native array/JSON types, a SearchResult with .chunks), so it joins
OceanBase in the branches that assume that shape and stays on the Elasticsearch
default for tokenization.

- common/settings.py: DOC_ENGINE_SERENEDB flag and the dispatch arm building
  SereneDBConnection (imported lazily so psycopg2 is only touched when selected).
- rag/nlp/search.py, api/db/services/dialog_service.py: return chunk vectors
  inline and take the local-rerank path (no ES second-pass KNN).
- rag/utils/table_es_metadata.py, rag/app/table.py: read/write table-parser
  metadata from the chunk_data JSON column, not ES flat fields.
- api/db/services/doc_metadata_service.py: use the delete+insert metadata path
  instead of the ES scripted partial update.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The Python doc-store connector for SereneDB, the plain-SQL sibling of ob_conn:
one table per tenant (ragflow_{tenant}) with kb_id as a filter column, ES field
names kept verbatim, and one inverted index carrying both the scored text
columns (@@, BM25) and the normalized vector shadow (<#>, ip/sq8). Hybrid
fusion is a single window-normalized BM25 + ANN statement. Connects with
psycopg2. Minimum engine version: SereneDB 26.07.4.

This is the Python counterpart of the Go engine in this PR; both use the same
single-table layout, so the two paths are storage- and retrieval-compatible.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pure SQL-builder tests for the SereneDB connector (_escape, _strip_es_query,
_l2_normalize, _get_filters, and the name helpers). They import the helpers
directly and need no live database, matching test_ob_conn.py.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
buildUpdateSets emitted `<key> = NULL` for any key in an update's `remove`
map without checking it against the known columns, unlike every other branch.
A crafted key could write unintended columns or inject SQL. Skip keys that are
not real columns, in both the Go engine and the Python connector, and add a
regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Addresses the CodeRabbit review sweep across both connectors:

- buildFilters: an empty IN/array list now reduces to a never-match predicate
  instead of emitting invalid `col IN ()`.
- DeleteChunks/UpdateChunks/DeleteMetadata reject conditions carrying keys the
  filter builder does not recognize, so a stray key cannot silently widen the
  affected row set.
- tableExists validates the identifier and queries the catalog, returning an
  error on connectivity/permission failures instead of masking them as
  "table absent"; GetChunk likewise surfaces query errors instead of reporting
  "not found". Callers updated for the (bool, error) signature.
- Table names are validated against an identifier pattern before being
  interpolated into DDL/DML.
- SearchMetadata keeps only real metadata columns in the projection; the Python
  connector validates agg_field before aggregating.
- DSN handling: redact URL-form as well as keyword-form credentials, quote
  lib/pq keyword values, and URL-encode the Python DSN credentials.
- InsertChunks no longer mutates the caller's chunk maps (the kb_id stamp moved
  into prepareChunkRow).

Adds unit tests for the empty-IN guard, key recognition, identifier validation,
DSN redaction, and value quoting. The fusion-weight finding is not a defect:
the final ranking is recomputed by the local rerank with the real term/vector
weights (rag/nlp/search.py), so lexical relevance is applied end to end.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
deadtrickster and others added 3 commits August 3, 2026 10:09
…k by schema

Follow-up to the review:

- buildDSN no longer forces sslmode=disable. A new ssl_mode config (Go
  SereneDBConfig.SSLMode / Python `ssl_mode`) selects the lib/pq sslmode;
  it still defaults to disable for a trusted local deployment, so an operator
  can require encryption. SERENEDB_DSN remains a full override.
- tableExists now scopes the information_schema lookup to current_schema(), so a
  same-named relation in another schema is not mistaken for the target table.
  Verified against SereneDB 26.07.4 (current_schema() is public and tables are
  created there).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ruff format normalizes the nested-quote string in test_serenedb_conn.py. Fixes
the lefthook ruff format check that CI runs on changed files.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add the serenedb service to docker-compose-base.yml (profiles: [serenedb],
serenedb/serenedb:26.07.5, host-mapped 7890, pg_isready healthcheck), the
serenedb block in service_conf.yaml.template so the Python connector resolves
host/port/creds inside the compose network, and SERENEDB_* defaults in .env.

Without this DOC_ENGINE=serenedb fell back to the connector's hardcoded
defaults and was not deployable through the standard stack.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@deadtrickster
deadtrickster force-pushed the ik-serenedb-go-engine branch 2 times, most recently from 0507df3 to 3746a0a Compare August 3, 2026 08:30
SereneDB has no dedicated CI capacity upstream, so instead of adding a job to
tests.yml/sep-tests.yml this ships .github/workflows/serenedb.yml gated on
workflow_dispatch. It never runs on push or pull_request - trigger it by hand
from the Actions tab, or run it locally with nektos/act. It brings up a real
SereneDB and runs the Go engine integration tier against it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@deadtrickster
deadtrickster force-pushed the ik-serenedb-go-engine branch from 3746a0a to 01f75a5 Compare August 3, 2026 08:31
@deadtrickster

deadtrickster commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@JinHai-CN, rebased. Removed Serene from the main CI matrix, but kept the yaml so it can be ran locally (with act)

I hope it can be merged now.

@JinHai-CN

Copy link
Copy Markdown
Member

Looks good to me.

@JinHai-CN
JinHai-CN merged commit 197b142 into infiniflow:main Aug 4, 2026
5 checks passed
@JinHai-CN

Copy link
Copy Markdown
Member

@deadtrickster

Thanks again for the contribution—the PR has been successfully merged!

Moving forward, we'd like to invite you and your organization to become one of our ecosystem partners. This would allow us to collaborate more closely on community events, co-marketing efforts, and social media promotions. We believe this partnership could be mutually beneficial and help drive broader adoption of both RAGFlow and SereneDB.

In addition, as RAGFlow continues to release new versions, we would like to keep you in the loop. When we prepare a new release, we'll reach out to you so that your team can help test the SereneDB integration against the upcoming changes.

Could you please send me an email at [email protected] so we can establish a direct channel for future communications?

@deadtrickster

Copy link
Copy Markdown
Contributor Author

@JinHai-CN amazing! we will be writing to you soon. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants