Repository navigation
feat(serenedb): add SereneDB doc-store engine (Go + Python connectors) - #17375
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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. ChangesSereneDB document engine
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
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2⚔️ Resolve merge conflicts 💡
🛠️ 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. Comment |
faf8d32 to
7ac58a5
Compare
There was a problem hiding this comment.
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 winSingleton
__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 beforeself._pool,self._known_tables, andself._known_lockare constructed (lines 221-223). If two threads race to construct the firstSereneDBConnection()concurrently, the second thread can see_initialized=Trueand return early while the first thread is still mid-construction, leavingself._pool/self._known_tablesunset 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 liftSkip 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_idrows, any path that callsdelete_idx("ragflow_doc_meta_<tenant>", "<kb_id>")should not reachDROP 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 siblingupdate()/insert().
update()wraps its_runcall in try/except, logs, and returnsFalseon 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 theDocStoreConnectioncontract, 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}makeskk = v(the raw field name), andf"{kk} = NULL"is built without checkingkk 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, thek in COLUMN_DDLbranches). 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 winURL-encode the SereneDB credentials and avoid hardcoding the connection pool size.
- Build the DSN with
urllib.parse.quote_plus(user)andquote_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()raisesPoolErroroncemaxconnis reached rather than waiting, so concurrency above the configured pool can explode as unhandledPoolErrors 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_fieldisn't validated before SQL interpolation, unlike every other identifier path in this file.
_get_filtersvalidateskagainstCOLUMN_DDL/ARRAY_COLUMNSbefore use as an identifier, and the filter-only branch validatesorder_byfields againstCOLUMN_DDL._aggregation'sagg_field, however, is interpolated directly intoSELECT {agg_field}, count(*) FROM ... GROUP BY {agg_field}(and theunnest({agg_field})variant) with no such check. Ifagg_fieldsis 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 liftDefer
offsetuntil after merging multi-table results.
Search()pushes the sameoffset/limitinto 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 multiplereq.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=disableis hardcoded with no config escape hatch.
SereneDBConfighas no TLS knob, so any non-loopback deployment sends credentials and document content in cleartext unless operators bypass the whole config viaSERENEDB_DSN. Consider adding an optionalssl_modefield (defaulting todisableto 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 winDSN redaction misses URL-form credentials.
dsnPasswordReonly matches thepassword=keyword form.SERENEDB_DSNmay 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 winSilently dropping unrecognized condition keys widens
UPDATE/DELETEscope.Any key that is not a known column,
exists, ormust_notis skipped without a trace. On the write paths this is destructive rather than merely lossy:DeleteChunks(ctx, {"unknown_field": "x"}, base, kb)reduces toWHERE kb_id = '<kb>'and wipes the entire dataset (chunk.go Lines 365-372);UpdateChunkshas 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 winEmpty 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{}{}}rendersdoc_id IN (), which fails to parse and turns the whole search/update/delete into an error. The array-column branch already guards this withlen(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 winTable names are interpolated into DDL/DML without validation or quoting.
chunkTableName(baseName)andbuildMetadataTableName(tenantID)feed raw strings straight intoCREATE TABLE,DROP TABLE,DELETE FROM, andSELECTstatements 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/tenantIDinCreateChunkStore,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
tableExiststreats 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:
DeleteChunksreturns(0, nil),GetChunkreturns(nil, nil),DropChunkStorereturnsnil, andInsertChunksre-runs DDL. Inspect the error and only reportfalsefor the undefined-table condition (pq error code42P01), 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 winQuote lib/pq DSN values with escaping
buildDSNemits 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 winDon’t assume SereneDB accepts
IF NOT EXISTShere.SereneDB’s documented dictionary DDL is
CREATE TEXT SEARCH DICTIONARY ...;IF NOT EXISTSis not part of the supported syntax. SinceCreateChunkStoreexecuteschunkTableDDL, the second creation for the same tenant store will fail instead of being idempotent. Replace this with a supported idempotent pattern, such asDROP TEXT SEARCH DICTIONARY IF EXISTSfollowed byCREATE, 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
SelectFieldsis interpolated into the SELECT list unvalidated.Any caller-supplied string becomes raw SQL (subqueries,
*, expressions). Validate each entry againstdocMetaDDLbefore 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 winMerge update is a read-modify-write with no transaction.
loadMetaFieldsthenUPDATE/INSERToutside 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 theidconflict since there is noON CONFLICThere). 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
GetChunkreports a DB failure as "chunk not found".Line 394 collapses
errintonil, 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 winAvoid template SQL for DELETE predicates.
buildFiltersis an engine-internal path, butDeleteChunks/DeleteMetadatacall it from public methods and render unknown column strings directly intoExecContextstatements. 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-L378internal/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 winLimit
RunSQLto safe, scoped reads.
RunSQLpasses LLM-generated SQL straight throughqueryMapswithout applyingtableName,kbIDs, or a read-only execution path. Since SereneDB stores chunk rows in a tenant-wide table keyed bykb_id, any generatedSELECTmissing that predicate can read other datasets, andUPDATE/DELETE/DROPstatements can mutate/drop data. Reject statements that are not read-only by nature and enforcekbIDsscope inSereneDB’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 winUse the repository's
build.shin 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'sbuild.shso required CGO flags and native libraries are configured" and "Run the narrowest relevant validation after changes: ... package-scopedbash 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 async.Onceoutlives its owning test.The directory is cleaned up when the first test that ran the
Oncefinishes, soTestIntegrationMetadatalogs into a removed path. Useos.MkdirTemp(oros.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
hasLimitRematches aLIMITanywhere, so the bound is easy to bypass.
SELECT * FROM (SELECT id FROM t LIMIT 5) x(or any statement containing the wordlimitin a string literal or quoted identifier) skips the appendedLIMIT, 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 trailingLIMIT <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 winVector values that fail coercion are dropped silently.
If
toFloatSlicecan'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 winTeardown does not drop the table, contradicting the comment.
DropChunkStorewith a non-emptydatasetIDonly deletes that dataset's rows (chunk.go Lines 87-89); the tenant table and its inverted index survive the run. A rerun with a differentvectorSizewill 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_metaswallows per-row errors without logging.Errors are appended to
errorsbut never logged, unlike the parallel maininsert()path which callslogger.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 winSilent
except Exception: passon 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 winAdd
decodeValuecoverage 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 winFragile 22-argument positional
fmt.SprintfinbuildFusionSQL.I traced every
%s/%dplaceholder 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 valueFailed type assertion silently degrades to defaults.
If
cfgis ever a non-*server.SereneDBConfig(or a nil interface),sdbCfgbecomes nil and the engine quietly connects toserenedb:7890/postgresinstead of reporting a misconfiguration. Return an error unlessSERENEDB_DSNis 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
BulkIndexissues one statement per document and duplicatesIndexDocument.
buildUpsertalready accepts multiple rows, andInsertChunks(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 oflen(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 winBatch the metadata upsert.
One round trip per record, non-atomic on partial failure.
buildUpsert(chunk.go Line 268) already renders multi-rowON CONFLICTstatements 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
InsertChunksmutates the caller's chunk maps and has no atomicity across groups.Two points:
- Line 245 writes
kb_idinto the caller-owned map, so a retry with a differentdatasetIDwill keep the first stamp (the!okguard 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
📒 Files selected for processing (22)
api/db/services/dialog_service.pyapi/db/services/doc_metadata_service.pycommon/settings.pyinternal/engine/engine.gointernal/engine/global.gointernal/engine/serenedb/chunk.gointernal/engine/serenedb/client.gointernal/engine/serenedb/common.gointernal/engine/serenedb/document.gointernal/engine/serenedb/integration_test.gointernal/engine/serenedb/metadata.gointernal/engine/serenedb/schema.gointernal/engine/serenedb/search.gointernal/engine/serenedb/serenedb.gointernal/engine/serenedb/serenedb_test.gointernal/engine/serenedb/sql.gointernal/server/config.gorag/app/table.pyrag/nlp/search.pyrag/utils/serenedb_conn.pyrag/utils/table_es_metadata.pytest/unit_test/rag/utils/test_serenedb_conn.py
|
Thanks for the thorough sweep. Addressed the substantive findings in Fixed
Not changing
The remaining nitpicks (batching, no-transaction merges, the 22-arg |
There was a problem hiding this comment.
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
📒 Files selected for processing (9)
internal/engine/serenedb/chunk.gointernal/engine/serenedb/client.gointernal/engine/serenedb/common.gointernal/engine/serenedb/document.gointernal/engine/serenedb/metadata.gointernal/engine/serenedb/schema.gointernal/engine/serenedb/search.gointernal/engine/serenedb/serenedb_test.gorag/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
|
@xugangqiang ping :-) |
|
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. |
|
@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. 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). |
|
The ruff-format check did not pass: |
|
@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. |
|
@deadtrickster Please help to check CI issue - seems like relating to Lefthook |
b686d7a to
f033c29
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
f033c29 to
0de1afb
Compare
|
Rebased, also added serene to CI, let's see how it goes. I would appreciate if we could merge it soon. |
|
CI didn't pick up serene jobs - I assume they come from |
|
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? |
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]>
…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]>
0507df3 to
3746a0a
Compare
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]>
3746a0a to
01f75a5
Compare
|
@JinHai-CN, rebased. Removed Serene from the main CI matrix, but kept the yaml so it can be ran locally (with I hope it can be merged now. |
|
Looks good to me. |
|
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? |
|
@JinHai-CN amazing! we will be writing to you soon. Thank you. |
What
Adds SereneDB as a selectable doc-store engine on both RAGFlow paths:
DocEngine(internal/engine/serenedb), alongside Elasticsearch and Infinity;DocStoreConnection(rag/utils/serenedb_conn.py) +DOC_ENGINE=serenedbregistration.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 withdatabase/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_idas 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:hybridproxy 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(elseBM25()silently returns 0.0), the@@query is the tokenized query, the scored lexical branch matches one column, vectors use an L2-normalized shadow column withip/sq8, and the similarity threshold goes directly in the ANN scan'sWHERE. Minimum engine version: SereneDB 26.07.4.Registration
EngineSereneDBinengine.goandserver/config.go, the factory arm inglobal.go, aSereneDBConfig, and theDOC_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:Recall on the same gold set: recall@8 3/5 (both ES and SereneDB), recall@64 5/5 (both).
Throughput / ingest:
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:
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: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
serenedb_test.go) - pure SQL-builder and codec tests, no database, run underbuild.sh --test. Cover the fusion CTE, single-column scored branch, threshold-in-WHERE, upsert, kb_id scoping, array/JSON decoding, vector literal.integration_test.go) - end-to-end against a live SereneDB (all four search modes, get/scores, update/delete, metadata lifecycle). Skipped unlessSERENEDB_TEST_DSNis set, so the default run stays CI-safe.InsertChunks(0 errors) and served correct fulltext, exact-cosine vector, and hybrid-fusion retrieval; parity verified as above.Scope
FilterDocIdsByMetaPushdownreturnsnil(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.