Repository navigation
refactor: split store.rs into focused modules - #186
Conversation
Extract store.rs (2,065 LOC) into 6 focused modules: - schema.rs (183 LOC) — init, migration, versioning - crud.rs (234 LOC) — insert, get, delete, update, list, search, count - tags.rs (184 LOC) — unique_tags, tags_with_counts, rename_tag, delete_tag - aging.rs (147 LOC) — touch_access, find_aged, cleanup_aged, tier_counts - bulk.rs (150 LOC) — bulk_delete_by_tag, bulk_delete_cold, bulk_delete_all, deprecate, prune_ttl store.rs slimmed to 985 LOC (struct, open(), helpers, all tests). Zero behavioral changes — pure reorganization. Note: Cannot verify build locally (missing pkg-config for ort/openssl-sys). CI will validate compilation and test pass.
|
Warning Review limit reached
More reviews will be available in 42 minutes and 15 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis PR refactors the monolithic ChangesStore Module Organization and Refactoring
🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly Related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
🔍 Cora AI Code ReviewReview powered by cora-cli · BYOK · MIT |
- schema.rs: add missing trait import - cargo fmt across all split files for CI format check
There was a problem hiding this comment.
Actionable comments posted: 6
♻️ Duplicate comments (8)
crates/uteke-core/src/memory/bulk.rs (6)
49-53:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing transaction wrapper risks partial deletes.
Same issue as in
bulk_delete_by_tag(lines 25-29).🤖 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 `@crates/uteke-core/src/memory/bulk.rs` around lines 49 - 53, The loop that deletes each id individually can leave the DB in a partially-deleted state; wrap the per-id deletes in a single transaction by opening a transaction via self.conn.transaction(), prepare or execute the DELETE inside the transaction (use tx.execute("DELETE FROM memories WHERE id = ?1", rusqlite::params![id]) and propagate errors with Error::db as before), and commit the transaction at the end so all deletes succeed or none do (mirror the pattern used in bulk_delete_by_tag).
68-72:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing transaction wrapper risks partial deletes.
Same issue as in
bulk_delete_by_tag(lines 25-29).🤖 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 `@crates/uteke-core/src/memory/bulk.rs` around lines 68 - 72, The loop that deletes each id individually uses self.conn.execute("DELETE FROM memories ...") and risks partial deletes; wrap the whole deletion loop in a single rusqlite transaction (use self.conn.transaction() to get a Transaction, call transaction.execute(...) for each id, then transaction.commit()), mirror the pattern used in bulk_delete_by_tag, and propagate errors via Error::db as before so either all IDs are deleted or none are.
25-29:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing transaction wrapper risks partial deletes.
The loop deletes multiple memories without a transaction. If an error occurs mid-loop (e.g., a constraint violation or I/O error), some memories will be deleted while others remain, leaving the system in an inconsistent state.
Wrap the delete loop in a transaction (similar pattern to the fix suggested for
tags.rsrename_tag lines 91-112).🤖 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 `@crates/uteke-core/src/memory/bulk.rs` around lines 25 - 29, The delete loop currently performs individual DELETEs without a transaction, risking partial deletes on error; wrap the loop in a rusqlite transaction by calling self.conn.transaction() (e.g., let txn = self.conn.transaction()?) then run txn.execute("DELETE FROM memories WHERE id = ?1", rusqlite::params![id]) for each id, map errors to Error::db as before, and finally call txn.commit() to persist all deletes atomically (mirror the transaction pattern used in rename_tag in tags.rs).
47-47:⚠️ Potential issue | 🟠 Major | ⚡ Quick winSilent error suppression hides database issues.
Same issue as in
bulk_delete_by_tag(line 23).🤖 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 `@crates/uteke-core/src/memory/bulk.rs` at line 47, The current use of filter_map(|r| r.ok()) in the bulk read path silently drops errors (same problem noted in bulk_delete_by_tag); change the code to surface and handle errors instead of swallowing them: replace the filter_map(|r| r.ok()) call with a pattern that collects Results (e.g., map to Result and collect into Result<Vec<_>, E> or use try_for_each/try_collect) so database errors are propagated or logged, and update the surrounding function (the bulk read function and/or bulk_delete_by_tag) signature to return a Result if needed so callers can handle the error.
66-66:⚠️ Potential issue | 🟠 Major | ⚡ Quick winSilent error suppression hides database issues.
Same issue as in
bulk_delete_by_tag(line 23).🤖 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 `@crates/uteke-core/src/memory/bulk.rs` at line 66, The current use of .filter_map(|r| r.ok()) in the bulk iterator silently drops errors and hides DB failures; update the iterator in the memory::bulk module to not swallow Result::Err — either propagate the Result (change the consumer to work with Result<T, E> and return an Err) or map errors to a logged failure before skipping (e.g., replace .filter_map(|r| r.ok()) with an explicit match that logs the error using the module's logger and then returns None, or collect Results and handle Errs); apply the same fix pattern used to correct bulk_delete_by_tag so database errors are surfaced or logged instead of being suppressed.
23-23:⚠️ Potential issue | 🟠 Major | ⚡ Quick winSilent error suppression hides database issues.
.filter_map(|r| r.ok())discards IDs that fail to fetch. If rusqlite returns errors for some rows, this method will silently skip those memories and return an incomplete list of deleted IDs.Apply the same fix pattern as suggested in
tags.rsrename_tag (line 87).🤖 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 `@crates/uteke-core/src/memory/bulk.rs` at line 23, The iterator currently uses .filter_map(|r| r.ok()) which silently drops rusqlite errors; change this to collect and propagate errors instead (same pattern used in tags.rs::rename_tag): map the row results into Result items and use collect::<Result<Vec<...>, _>>() (or otherwise propagate the first Err) so that database errors return Err from the surrounding function rather than being hidden; update the surrounding function's signature/return type as needed to return Result<Vec<Id>, rusqlite::Error> (or the crate's error type) and replace the silent filter_map with the fallible collect.crates/uteke-core/src/memory/tags.rs (2)
135-151:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing transaction wrapper risks partial updates.
Same issue as in
rename_tag: the loop updates multiple rows without a transaction, risking partial completion if an error occurs mid-loop.Apply the same transaction-wrapping fix as suggested in
rename_tag(lines 91-112).🤖 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 `@crates/uteke-core/src/memory/tags.rs` around lines 135 - 151, Wrap the loop that iterates over rows and calls self.conn.execute (the block that deserializes tags_str, mutates tags, and updates memories) inside a single database transaction to avoid partial updates: begin a transaction (e.g., let tx = self.conn.transaction()?), perform the updates against tx (use tx.execute with params![new_tags_json, now, id]) and only commit after the loop, returning errors before commit so the transaction rolls back; mirror the same transaction pattern used in rename_tag to ensure atomicity and to use tx.commit()? to finalize.
131-131:⚠️ Potential issue | 🟠 Major | ⚡ Quick winSilent error suppression hides database issues.
Same issue as in
rename_tag:.filter_map(|r| r.ok())discards rows that fail to fetch, causing silent under-reporting of deleted tags.Apply the same fix as suggested in
rename_tag(line 87).🤖 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 `@crates/uteke-core/src/memory/tags.rs` at line 131, The iterator chain in tags.rs that currently uses `.filter_map(|r| r.ok())` silently swallows database errors; change it to collect and propagate (or explicitly log) the Err instead of discarding it—replace the `.filter_map(|r| r.ok())` usage with collecting into a Result (e.g., `.collect::<Result<Vec<_>, _>>()`) and then handle the Err by returning the error or logging it (matching the same error-handling pattern used in `rename_tag`), so any failed row fetch surfaces rather than being dropped.
🧹 Nitpick comments (5)
crates/uteke-core/src/memory/crud.rs (1)
69-69: ⚡ Quick winReview
#[allow(dead_code)]on actively used method.The
updatemethod is marked#[allow(dead_code)], but it's called in multiple test cases (test_store_updateandtest_update_preserves_namespacein store.rs). If the tests pass, this allow may be unnecessary. If the compiler still warns, consider documenting why the allow is needed (e.g., cross-module test visibility limitation).🤖 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 `@crates/uteke-core/src/memory/crud.rs` at line 69, The #[allow(dead_code)] on the update method is incorrect for an actively used method; either remove the attribute from the update function or, if the warning persists due to visibility across modules, make the method appropriately visible (e.g., pub or pub(crate)) or add a short doc comment explaining why the allow is required; locate the update method referenced by tests test_store_update and test_update_preserves_namespace and either delete the #[allow(dead_code)] annotation or replace it with proper visibility or a documented justification.crates/uteke-core/src/memory/schema.rs (1)
15-26: ⚡ Quick winInconsistent column existence check for namespace.
Lines 16-19 check for the namespace column using
prepare(...).is_ok(), while all subsequent migrations (lines 36-73) use thecolumn_exists()helper. This inconsistency makes the code harder to maintain.♻️ Refactor to use column_exists consistently
- // Migration: add namespace column if missing (existing DBs) - let has_namespace: bool = self - .conn - .prepare("SELECT namespace FROM memories LIMIT 1") - .is_ok(); - if !has_namespace { + // Migration: add namespace column if missing (existing DBs) + if !self.column_exists("namespace") { self.conn .execute_batch(🤖 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 `@crates/uteke-core/src/memory/schema.rs` around lines 15 - 26, The namespace existence check uses prepare(...).is_ok() (creating has_namespace) while later migrations use the column_exists() helper; replace the prepare-based check with the same helper (call column_exists("memories", "namespace") or the existing column_exists method on the same object) and keep the current execute_batch ALTER TABLE branch and Error::db mapping intact so behavior doesn't change but checks are consistent with other migrations.crates/uteke-core/src/memory/bulk.rs (1)
17-29: ⚡ Quick winInefficient: use single DELETE query instead of SELECT + loop.
The current implementation queries all matching IDs into memory, then deletes them one-by-one in a loop. This is inefficient and risks partial completion. A single
DELETE ... WHERE ... AND EXISTS (SELECT 1 FROM json_each(...))would be atomic and faster.⚡ Proposed fix to use a single DELETE query
pub fn bulk_delete_by_tag( &self, tag: &str, namespace: Option<&str>, ) -> Result<Vec<String>, Error> { let ns = namespace.unwrap_or(DEFAULT_NAMESPACE); + // First, collect IDs to return let ids: Vec<String> = self .conn .prepare("SELECT id FROM memories WHERE namespace = ?1 AND EXISTS (SELECT 1 FROM json_each(memories.tags) WHERE value = ?2)") .map_err(|e| Error::db("database operation", e))? .query_map(rusqlite::params![ns, tag], |row| row.get(0)) .map_err(|e| Error::db("database operation", e))? - .filter_map(|r| r.ok()) - .collect(); - for id in &ids { - self.conn - .execute("DELETE FROM memories WHERE id = ?1", rusqlite::params![id]) - .map_err(|e| Error::db("database operation", e))?; - } + .collect::<Result<Vec<_>, _>>() + .map_err(|e| Error::db("database operation", e))?; + + // Then delete in a single query + self.conn + .execute( + "DELETE FROM memories WHERE namespace = ?1 AND EXISTS (SELECT 1 FROM json_each(memories.tags) WHERE value = ?2)", + rusqlite::params![ns, tag], + ) + .map_err(|e| Error::db("database operation", e))?; + Ok(ids) }🤖 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 `@crates/uteke-core/src/memory/bulk.rs` around lines 17 - 29, The current delete implementation in bulk.rs first collects ids via a SELECT and then loops to delete each (the block using self.conn.prepare(... SELECT id ...) and the for id in &ids loop); replace this with a single atomic DELETE statement executed via self.conn.execute that uses the same WHERE clause and EXISTS (SELECT 1 FROM json_each(memories.tags) WHERE value = ?2) and the same rusqlite::params![ns, tag], and preserve error handling by mapping rusqlite errors with Error::db("database operation", e) as done elsewhere.crates/uteke-core/src/memory/tags.rs (1)
24-35: ⚡ Quick winReduce duplication in query execution branches.
The
Some(ns)andNonebranches repeat identicalquery_map/collect/error-handling logic. Extract the common pattern to avoid maintaining two copies.♻️ Proposed refactor to eliminate duplication
- let rows = match namespace { - Some(ns) => stmt - .query_map(rusqlite::params![ns], |row: &rusqlite::Row| row.get::<_, String>(0)) - .map_err(|e| Error::db("database operation", e))? - .collect::<Result<Vec<_>, _>>() - .map_err(|e| Error::db("database operation", e))?, - None => stmt - .query_map([], |row: &rusqlite::Row| row.get::<_, String>(0)) - .map_err(|e| Error::db("database operation", e))? - .collect::<Result<Vec<_>, _>>() - .map_err(|e| Error::db("database operation", e))?, - }; + let params: &[&dyn rusqlite::ToSql] = match namespace { + Some(ns) => &[&ns], + None => &[], + }; + let rows = stmt + .query_map(params, |row: &rusqlite::Row| row.get::<_, String>(0)) + .map_err(|e| Error::db("database operation", e))? + .collect::<Result<Vec<_>, _>>() + .map_err(|e| Error::db("database operation", e))?; Ok(rows)🤖 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 `@crates/uteke-core/src/memory/tags.rs` around lines 24 - 35, The two branches that call stmt.query_map(...).collect(...).map_err(...) are duplicated; instead compute the parameter binding first (e.g., let params = match namespace { Some(ns) => rusqlite::params![ns], None => rusqlite::params![] }; or create an enum/trait object representing the params), then call stmt.query_map(params, |row: &rusqlite::Row| row.get::<_, String>(0)).map_err(|e| Error::db("database operation", e))?.collect::<Result<Vec<_>, _>>().map_err(|e| Error::db("database operation", e))? to produce rows, keeping the same error mapping and using the existing variables stmt, namespace, rows.crates/uteke-core/src/memory/aging.rs (1)
67-90: cleanup_aged intentionally skips the vector index; maintenance path handles it
crates/uteke-core/src/memory/aging.rsdocuments thatcleanup_aged“Does NOT touch the vector index” and it only deletes from SQLite. That doesn’t look critical on its own becausecrates/uteke-core/src/maintenance.rscallsstore.cleanup_aged(...)and then has a separate “Remove from vector index” step (and its docs state cleanup aged removes from both SQLite and the vector index).Main remaining risk is only for any caller that bypasses the maintenance cleanup path. If that’s a real possibility, clarify documentation/call-site guidance (e.g., explicitly direct users to the maintenance API).
🤖 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 `@crates/uteke-core/src/memory/aging.rs` around lines 67 - 90, cleanup_aged currently only deletes rows from the SQLite store and does not remove entries from the vector index; update the public docs and the function docstring for cleanup_aged (and add a clear comment where store.cleanup_aged(...) is invoked in maintenance.rs) to explicitly state that callers must use the maintenance API to also remove vector-index entries or else handle vector-index removal themselves; alternatively, consider adding an optional parameter to cleanup_aged (or a new method) to also remove from the vector index and document the new behavior so callers of cleanup_aged, maintenance::cleanup_aged, and any direct store.cleanup_aged usages are unambiguous.
🤖 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 `@crates/uteke-core/src/memory/bulk.rs`:
- Around line 88-106: The docstring for find_similar is incorrect: the function
(find_similar) and its SQL only return non-deprecated memories in a namespace
ordered by created_at DESC with a limit (and the unit test test_find_similar
expects recency), so either rename the function or update the docs to reflect
the current behavior; specifically, change the Rust doc comment on pub fn
find_similar(&self, namespace: &str, limit: usize) -> Result<Vec<Memory>, Error>
to say it returns recent (most-recent-first) non-deprecated memories in the
given namespace up to limit, or if you prefer to implement true similarity,
change the signature to accept an embedding slice and threshold (e.g.,
embedding: &[f32], threshold: f32), decode stored embedding blobs in the row
(from the embedding column), compute cosine similarity, filter by threshold,
sort by similarity descending, and then apply limit—ensure updates to tests
(test_find_similar) and references accordingly.
In `@crates/uteke-core/src/memory/schema.rs`:
- Around line 96-104: The call to .optional() on the query_row result is failing
because rusqlite::OptionalExtension is not imported; add a use import for
OptionalExtension so the extension method is in scope (e.g., add use
rusqlite::OptionalExtension;) near other imports referenced by schema handling
where self.conn.query_row(...) -> .optional() is used (the code creating
current: Option<i32>, the query_row call, and Error::db mapping will then
compile).
In `@crates/uteke-core/src/memory/tags.rs`:
- Line 92: The current initialization let mut tags: Vec<String> =
serde_json::from_str(tags_str).unwrap_or_default() silently treats invalid JSON
as an empty tag list and will erase tags; replace this with proper error
handling: call serde_json::from_str(tags_str) and propagate or surface the error
(return a Result or early-return from the enclosing function), or at minimum log
the parse error and skip mutating that memory entry instead of defaulting to an
empty Vec; locate the occurrence using the symbols tags_str and tags (in
tags.rs) and update the surrounding function to handle serde_json::Error rather
than swallowing it.
- Line 136: The code currently uses
serde_json::from_str(tags_str).unwrap_or_default() (e.g., in the tags handling
in tags.rs) which silently treats malformed JSON as an empty Vec and can corrupt
or hide data; change this to explicitly handle parse errors by returning or
propagating an error (or converting into a Result) instead of defaulting—locate
the usage of serde_json::from_str in the remove_tag/rename_tag logic, replace
unwrap_or_default with proper error propagation (e.g., map_err/try? or return
Err) and ensure the caller surfaces the parse error so malformed JSON in the
tags column is not silently ignored or overwritten.
- Around line 91-112: The loop that updates rows (iterating over rows,
deserializing tags, modifying them, and calling self.conn.execute) must be
wrapped in a single database transaction to avoid partial commits; start a
transaction via self.conn.transaction(), perform the per-row
serde_json::to_string and UPDATEs against the Transaction object (not
self.conn), increment updated as you do now, and commit the transaction at the
end (letting it roll back on error) so the entire rename operation is atomic;
ensure any map_err conversions (Error::db) propagate out to cause rollback on
failure.
---
Duplicate comments:
In `@crates/uteke-core/src/memory/bulk.rs`:
- Around line 49-53: The loop that deletes each id individually can leave the DB
in a partially-deleted state; wrap the per-id deletes in a single transaction by
opening a transaction via self.conn.transaction(), prepare or execute the DELETE
inside the transaction (use tx.execute("DELETE FROM memories WHERE id = ?1",
rusqlite::params![id]) and propagate errors with Error::db as before), and
commit the transaction at the end so all deletes succeed or none do (mirror the
pattern used in bulk_delete_by_tag).
- Around line 68-72: The loop that deletes each id individually uses
self.conn.execute("DELETE FROM memories ...") and risks partial deletes; wrap
the whole deletion loop in a single rusqlite transaction (use
self.conn.transaction() to get a Transaction, call transaction.execute(...) for
each id, then transaction.commit()), mirror the pattern used in
bulk_delete_by_tag, and propagate errors via Error::db as before so either all
IDs are deleted or none are.
- Around line 25-29: The delete loop currently performs individual DELETEs
without a transaction, risking partial deletes on error; wrap the loop in a
rusqlite transaction by calling self.conn.transaction() (e.g., let txn =
self.conn.transaction()?) then run txn.execute("DELETE FROM memories WHERE id =
?1", rusqlite::params![id]) for each id, map errors to Error::db as before, and
finally call txn.commit() to persist all deletes atomically (mirror the
transaction pattern used in rename_tag in tags.rs).
- Line 47: The current use of filter_map(|r| r.ok()) in the bulk read path
silently drops errors (same problem noted in bulk_delete_by_tag); change the
code to surface and handle errors instead of swallowing them: replace the
filter_map(|r| r.ok()) call with a pattern that collects Results (e.g., map to
Result and collect into Result<Vec<_>, E> or use try_for_each/try_collect) so
database errors are propagated or logged, and update the surrounding function
(the bulk read function and/or bulk_delete_by_tag) signature to return a Result
if needed so callers can handle the error.
- Line 66: The current use of .filter_map(|r| r.ok()) in the bulk iterator
silently drops errors and hides DB failures; update the iterator in the
memory::bulk module to not swallow Result::Err — either propagate the Result
(change the consumer to work with Result<T, E> and return an Err) or map errors
to a logged failure before skipping (e.g., replace .filter_map(|r| r.ok()) with
an explicit match that logs the error using the module's logger and then returns
None, or collect Results and handle Errs); apply the same fix pattern used to
correct bulk_delete_by_tag so database errors are surfaced or logged instead of
being suppressed.
- Line 23: The iterator currently uses .filter_map(|r| r.ok()) which silently
drops rusqlite errors; change this to collect and propagate errors instead (same
pattern used in tags.rs::rename_tag): map the row results into Result items and
use collect::<Result<Vec<...>, _>>() (or otherwise propagate the first Err) so
that database errors return Err from the surrounding function rather than being
hidden; update the surrounding function's signature/return type as needed to
return Result<Vec<Id>, rusqlite::Error> (or the crate's error type) and replace
the silent filter_map with the fallible collect.
In `@crates/uteke-core/src/memory/tags.rs`:
- Around line 135-151: Wrap the loop that iterates over rows and calls
self.conn.execute (the block that deserializes tags_str, mutates tags, and
updates memories) inside a single database transaction to avoid partial updates:
begin a transaction (e.g., let tx = self.conn.transaction()?), perform the
updates against tx (use tx.execute with params![new_tags_json, now, id]) and
only commit after the loop, returning errors before commit so the transaction
rolls back; mirror the same transaction pattern used in rename_tag to ensure
atomicity and to use tx.commit()? to finalize.
- Line 131: The iterator chain in tags.rs that currently uses `.filter_map(|r|
r.ok())` silently swallows database errors; change it to collect and propagate
(or explicitly log) the Err instead of discarding it—replace the
`.filter_map(|r| r.ok())` usage with collecting into a Result (e.g.,
`.collect::<Result<Vec<_>, _>>()`) and then handle the Err by returning the
error or logging it (matching the same error-handling pattern used in
`rename_tag`), so any failed row fetch surfaces rather than being dropped.
---
Nitpick comments:
In `@crates/uteke-core/src/memory/aging.rs`:
- Around line 67-90: cleanup_aged currently only deletes rows from the SQLite
store and does not remove entries from the vector index; update the public docs
and the function docstring for cleanup_aged (and add a clear comment where
store.cleanup_aged(...) is invoked in maintenance.rs) to explicitly state that
callers must use the maintenance API to also remove vector-index entries or else
handle vector-index removal themselves; alternatively, consider adding an
optional parameter to cleanup_aged (or a new method) to also remove from the
vector index and document the new behavior so callers of cleanup_aged,
maintenance::cleanup_aged, and any direct store.cleanup_aged usages are
unambiguous.
In `@crates/uteke-core/src/memory/bulk.rs`:
- Around line 17-29: The current delete implementation in bulk.rs first collects
ids via a SELECT and then loops to delete each (the block using
self.conn.prepare(... SELECT id ...) and the for id in &ids loop); replace this
with a single atomic DELETE statement executed via self.conn.execute that uses
the same WHERE clause and EXISTS (SELECT 1 FROM json_each(memories.tags) WHERE
value = ?2) and the same rusqlite::params![ns, tag], and preserve error handling
by mapping rusqlite errors with Error::db("database operation", e) as done
elsewhere.
In `@crates/uteke-core/src/memory/crud.rs`:
- Line 69: The #[allow(dead_code)] on the update method is incorrect for an
actively used method; either remove the attribute from the update function or,
if the warning persists due to visibility across modules, make the method
appropriately visible (e.g., pub or pub(crate)) or add a short doc comment
explaining why the allow is required; locate the update method referenced by
tests test_store_update and test_update_preserves_namespace and either delete
the #[allow(dead_code)] annotation or replace it with proper visibility or a
documented justification.
In `@crates/uteke-core/src/memory/schema.rs`:
- Around line 15-26: The namespace existence check uses prepare(...).is_ok()
(creating has_namespace) while later migrations use the column_exists() helper;
replace the prepare-based check with the same helper (call
column_exists("memories", "namespace") or the existing column_exists method on
the same object) and keep the current execute_batch ALTER TABLE branch and
Error::db mapping intact so behavior doesn't change but checks are consistent
with other migrations.
In `@crates/uteke-core/src/memory/tags.rs`:
- Around line 24-35: The two branches that call
stmt.query_map(...).collect(...).map_err(...) are duplicated; instead compute
the parameter binding first (e.g., let params = match namespace { Some(ns) =>
rusqlite::params![ns], None => rusqlite::params![] }; or create an enum/trait
object representing the params), then call stmt.query_map(params, |row:
&rusqlite::Row| row.get::<_, String>(0)).map_err(|e| Error::db("database
operation", e))?.collect::<Result<Vec<_>, _>>().map_err(|e| Error::db("database
operation", e))? to produce rows, keeping the same error mapping and using the
existing variables stmt, namespace, rows.
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: ebe03ec9-5725-4ae8-a297-47fda34ddc2c
📒 Files selected for processing (7)
crates/uteke-core/src/memory/aging.rscrates/uteke-core/src/memory/bulk.rscrates/uteke-core/src/memory/crud.rscrates/uteke-core/src/memory/mod.rscrates/uteke-core/src/memory/schema.rscrates/uteke-core/src/memory/store.rscrates/uteke-core/src/memory/tags.rs
| /// Find memories that contradict a new embedding (high similarity, same namespace). | ||
| /// Returns memories with cosine similarity > threshold that are not already deprecated. | ||
| pub fn find_similar(&self, namespace: &str, limit: usize) -> Result<Vec<Memory>, Error> { | ||
| let mut stmt = self | ||
| .conn | ||
| .prepare( | ||
| "SELECT id, content, embedding, tags, metadata, created_at, updated_at, namespace, access_count, last_accessed, deprecated, valid_from, valid_until, memory_type | ||
| FROM memories WHERE namespace = ?1 AND deprecated = 0 ORDER BY created_at DESC LIMIT ?2", | ||
| ) | ||
| .map_err(|e| Error::db("database operation", e))?; | ||
| let rows = stmt | ||
| .query_map(params![namespace, limit], row_to_memory) | ||
| .map_err(|e| Error::db("database operation", e))?; | ||
| let mut memories = Vec::new(); | ||
| for row in rows { | ||
| memories.push(row.map_err(|e| Error::db("database operation", e))?); | ||
| } | ||
| Ok(memories) | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Search for callers of find_similar to understand usage context
rg -n -C5 'find_similar' --type rustRepository: ajianaz/uteke
Length of output: 2972
Fix find_similar docs/API contract: it doesn’t compute cosine similarity
crates/uteke-core/src/memory/bulk.rsdocs (lines 88-89) claim it finds “contradict” memories using “cosine similarity > threshold”, but the implementation takes onlynamespace+limitand the SQL only filtersnamespace = ?1 AND deprecated = 0, ordering bycreated_at DESC(no similarity/threshold logic).- The unit test
crates/uteke-core/src/memory/store.rs(test_find_similar) expects recency ordering (assertssimilar[0].id == "2"), not similarity-based ranking.
Update the documentation/name to match the current behavior, or change the API to accept an embedding + threshold and implement cosine similarity filtering/ranking.
🤖 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 `@crates/uteke-core/src/memory/bulk.rs` around lines 88 - 106, The docstring
for find_similar is incorrect: the function (find_similar) and its SQL only
return non-deprecated memories in a namespace ordered by created_at DESC with a
limit (and the unit test test_find_similar expects recency), so either rename
the function or update the docs to reflect the current behavior; specifically,
change the Rust doc comment on pub fn find_similar(&self, namespace: &str,
limit: usize) -> Result<Vec<Memory>, Error> to say it returns recent
(most-recent-first) non-deprecated memories in the given namespace up to limit,
or if you prefer to implement true similarity, change the signature to accept an
embedding slice and threshold (e.g., embedding: &[f32], threshold: f32), decode
stored embedding blobs in the row (from the embedding column), compute cosine
similarity, filter by threshold, sort by similarity descending, and then apply
limit—ensure updates to tests (test_find_similar) and references accordingly.
|
|
||
| let mut updated = 0; | ||
| for (id, tags_str) in &rows { | ||
| let mut tags: Vec<String> = serde_json::from_str(tags_str).unwrap_or_default(); |
There was a problem hiding this comment.
Critical: JSON parse failure silently corrupts tags.
Same issue as in rename_tag: unwrap_or_default() treats malformed JSON as an empty array. If the stored tags column contains invalid JSON, this code will detect "no change" (since tags.retain(|t| t != tag) on an empty Vec produces an empty Vec) and skip the update, leaving the malformed JSON intact. However, if the malformed JSON happens to deserialize to a non-empty invalid structure, data could be lost.
🛡️ Proposed fix to surface JSON parse errors
- let mut tags: Vec<String> = serde_json::from_str(tags_str).unwrap_or_default();
+ let mut tags: Vec<String> = serde_json::from_str(tags_str)
+ .map_err(|e| Error::db("failed to parse tags JSON", 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 `@crates/uteke-core/src/memory/tags.rs` at line 136, The code currently uses
serde_json::from_str(tags_str).unwrap_or_default() (e.g., in the tags handling
in tags.rs) which silently treats malformed JSON as an empty Vec and can corrupt
or hide data; change this to explicitly handle parse errors by returning or
propagating an error (or converting into a Result) instead of defaulting—locate
the usage of serde_json::from_str in the remove_tag/rename_tag logic, replace
unwrap_or_default with proper error propagation (e.g., map_err/try? or return
Err) and ensure the caller surfaces the parse error so malformed JSON in the
tags column is not silently ignored or overwritten.
- Replace filter_map(|r| r.ok()) with proper Result propagation - Log warning and skip rows with corrupted JSON instead of silently using empty tags - Wrap rename_tag/delete_tag in SQLite transactions for atomicity Pre-existing issues identified during split — no behavioral change for valid data.
* refactor: split store.rs into focused modules (#179) Extract store.rs (2,065 LOC) into 6 focused modules: - schema.rs (183 LOC) — init, migration, versioning - crud.rs (234 LOC) — insert, get, delete, update, list, search, count - tags.rs (184 LOC) — unique_tags, tags_with_counts, rename_tag, delete_tag - aging.rs (147 LOC) — touch_access, find_aged, cleanup_aged, tier_counts - bulk.rs (150 LOC) — bulk_delete_by_tag, bulk_delete_cold, bulk_delete_all, deprecate, prune_ttl store.rs slimmed to 985 LOC (struct, open(), helpers, all tests). Zero behavioral changes — pure reorganization. Note: Cannot verify build locally (missing pkg-config for ort/openssl-sys). CI will validate compilation and test pass. * fix: add OptionalExtension import + cargo fmt - schema.rs: add missing trait import - cargo fmt across all split files for CI format check * fix: address CodeRabbit findings in tags.rs - Replace filter_map(|r| r.ok()) with proper Result propagation - Log warning and skip rows with corrupted JSON instead of silently using empty tags - Wrap rename_tag/delete_tag in SQLite transactions for atomicity Pre-existing issues identified during split — no behavioral change for valid data. --------- Co-authored-by: Zeko (Hermes) <[email protected]>
Summary
Extract
store.rs(2,065 LOC monolith) into 6 focused modules per #179.New files
schema.rscrud.rstags.rsaging.rsbulk.rsSlimmed files
store.rsRemaining
vector.rsandtypes.rswere already separate modules (no changes needed)commands.rssplit will follow in separate PR (refactor: split commands.rs (820 LOC) into per-command modules #180)Verification
Closes #179
Summary by CodeRabbit
Release Notes