Skip to content

refactor: split store.rs into focused modules - #186

Merged
ajianaz merged 3 commits into
developfrom
refactor/split-store-and-commands
Jun 7, 2026
Merged

ajianaz merged 3 commits into
developfrom
refactor/split-store-and-commands

Conversation

@ajianaz

@ajianaz ajianaz commented Jun 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Extract store.rs (2,065 LOC monolith) into 6 focused modules per #179.

New files

File LOC Responsibility
schema.rs 183 init, migration, versioning
crud.rs 234 insert, get, delete, update, list, search, count
tags.rs 184 unique_tags, tags_with_counts, rename_tag, delete_tag
aging.rs 147 touch_access, find_aged, cleanup_aged, tier_counts
bulk.rs 150 bulk_delete_by_tag, bulk_delete_cold, bulk_delete_all, deprecate, prune_ttl

Slimmed files

File Before After Change
store.rs 2,065 985 struct, open(), helpers, all 80+ tests

Remaining

Verification

  • Pure reorganization — zero behavioral changes
  • All 80+ tests retained in store.rs
  • Cannot verify build locally (missing pkg-config for ort/openssl-sys) — CI will validate

Closes #179

Summary by CodeRabbit

Release Notes

  • New Features
    • Added core memory operations: insert, retrieve, update, and delete.
    • Introduced automatic aging and cleanup based on access patterns and timestamps.
    • Added comprehensive tag management with bulk operations and search capabilities.
    • Enabled TTL-based pruning and memory tiering (hot/warm/cold classification).
    • Added namespace isolation and memory statistics tracking.

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.
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ajianaz, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d1cfe47b-e9cb-4235-8bff-dc10ab83682f

📥 Commits

Reviewing files that changed from the base of the PR and between a11b3a5 and 26963d3.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • crates/uteke-core/src/memory/schema.rs
  • crates/uteke-core/src/memory/store.rs
  • crates/uteke-core/src/memory/tags.rs
📝 Walkthrough

Walkthrough

This PR refactors the monolithic crates/uteke-core/src/memory/store.rs (2,065 LOC) into six focused modules—crud, tags, aging, bulk, and schema—while maintaining backward compatibility through re-exports. All memory store methods remain public via impl Store blocks distributed across modules rather than concentrated in one file.

Changes

Store Module Organization and Refactoring

Layer / File(s) Summary
Store internal visibility and helpers
crates/uteke-core/src/memory/store.rs
Store.conn, schema constants (SCHEMA, CURRENT_SCHEMA_VERSION), and embedding helpers (serialize_embedding, deserialize_embedding, row_to_memory) are made pub(super) to support sibling modules. Extensive test formatting refactors preserve logic while compacting insert calls and simplifying assertion structure across 30+ tests.
Schema initialization and versioning
crates/uteke-core/src/memory/schema.rs
init_schema executes base schema with conditional legacy column migrations, ensure_schema_version manages the schema_version table with forward/backward compatibility, run_migrations applies version-by-version migrations, and helpers schema_version() and column_exists() support version tracking and column detection.
Core CRUD operations
crates/uteke-core/src/memory/crud.rs
Implements fundamental data operations: insert stores memories with embeddings/tags/metadata; get_by_id retrieves by ID; delete removes memories; update modifies existing memories; list queries with optional tag filtering and pagination; search_content performs substring searches; load_all loads all memories for index rebuilding; count returns totals; path exposes the database file path.
Tag management operations
crates/uteke-core/src/memory/tags.rs
Provides tag-specific queries: unique_tags lists distinct tags; tags_with_counts returns per-tag usage via single SQL query with json_each(); rename_tag updates tag occurrences across memories; delete_tag removes tags and updates memories; count_by_tag counts memories including a tag; list_namespaces enumerates distinct namespaces.
Memory access tracking and lifecycle
crates/uteke-core/src/memory/aging.rs
Implements access tracking: touch_access increments access count and updates last_accessed timestamp; find_aged queries memories eligible for cleanup; cleanup_aged deletes eligible memories; count_never_accessed counts untouched memories; tier_counts computes hot/warm/cold classification by comparing last_accessed timestamps against configurable day cutoffs.
Bulk and maintenance operations
crates/uteke-core/src/memory/bulk.rs
Provides batch operations: bulk_delete_by_tag deletes by tag match; bulk_delete_cold removes by age threshold; bulk_delete_all deletes entire namespace; deprecate marks memories as invalid; find_similar queries non-deprecated memories; prune_ttl removes deprecated memories after TTL; find_deprecated_for_prune performs dry-run query for TTL-eligible deprecated memories.
Module organization and public exports
crates/uteke-core/src/memory/mod.rs
Exposes new aging, bulk, crud, schema, and tags modules as public submodules alongside existing store export, preserving the public API surface while enabling focused internal organization.

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly Related PRs

  • ajianaz/uteke#160: Introduces schema versioning and migrations in memory/schema.rs that work alongside the refactored store layer and standardized Error::db(...) handling.

Poem

🐰 One store became five, a rabbit's delight,
Each module now shines with focused light,
From crud to tags, aging to bulk so fine,
A monolith split—no conflicts to mine,
Refactored with grace, the code reads just right! 📚✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Out of Scope Changes check ❓ Inconclusive The PR introduces deprecate and tier_counts in bulk.rs and aging.rs respectively, which are in-scope per #179's tier.rs/aging.rs responsibilities; however, split does not match the planned tier.rs file organization. Clarify whether tier_counts/deprecate placement in aging.rs/bulk.rs versus a dedicated tier.rs module aligns with #179's intended structure and future maintenance.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: split store.rs into focused modules' directly matches the primary change: reorganizing a monolithic 2,065 LOC file into multiple focused modules.
Linked Issues check ✅ Passed The PR implements the planned split from issue #179: creates schema.rs, crud.rs, tags.rs, aging.rs, and bulk.rs modules with the specified methods, retains tests, and maintains public API via mod.rs re-exports.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/split-store-and-commands

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

❤️ Share

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

@github-actions

github-actions Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

🔍 Cora AI Code Review

⚠️ Review could not complete. Cora produced an empty result. Check the workflow logs for errors.


Review powered by cora-cli · BYOK · MIT

- schema.rs: add missing  trait import
- cargo fmt across all split files for CI format check

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

♻️ Duplicate comments (8)
crates/uteke-core/src/memory/bulk.rs (6)

49-53: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Missing 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 win

Missing 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 win

Missing 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.rs 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/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 win

Silent 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 win

Silent 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 win

Silent 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.rs 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/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 win

Missing 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 win

Silent 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 win

Review #[allow(dead_code)] on actively used method.

The update method is marked #[allow(dead_code)], but it's called in multiple test cases (test_store_update and test_update_preserves_namespace in 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 win

Inconsistent 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 the column_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 win

Inefficient: 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 win

Reduce duplication in query execution branches.

The Some(ns) and None branches repeat identical query_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.rs documents that cleanup_aged “Does NOT touch the vector index” and it only deletes from SQLite. That doesn’t look critical on its own because crates/uteke-core/src/maintenance.rs calls store.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

📥 Commits

Reviewing files that changed from the base of the PR and between f27e71d and a11b3a5.

📒 Files selected for processing (7)
  • crates/uteke-core/src/memory/aging.rs
  • crates/uteke-core/src/memory/bulk.rs
  • crates/uteke-core/src/memory/crud.rs
  • crates/uteke-core/src/memory/mod.rs
  • crates/uteke-core/src/memory/schema.rs
  • crates/uteke-core/src/memory/store.rs
  • crates/uteke-core/src/memory/tags.rs

Comment on lines +88 to +106
/// 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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for callers of find_similar to understand usage context
rg -n -C5 'find_similar' --type rust

Repository: ajianaz/uteke

Length of output: 2972


Fix find_similar docs/API contract: it doesn’t compute cosine similarity

  • crates/uteke-core/src/memory/bulk.rs docs (lines 88-89) claim it finds “contradict” memories using “cosine similarity > threshold”, but the implementation takes only namespace + limit and the SQL only filters namespace = ?1 AND deprecated = 0, ordering by created_at DESC (no similarity/threshold logic).
  • The unit test crates/uteke-core/src/memory/store.rs (test_find_similar) expects recency ordering (asserts similar[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.

Comment thread crates/uteke-core/src/memory/schema.rs Resolved
Comment thread crates/uteke-core/src/memory/tags.rs Resolved
Comment thread crates/uteke-core/src/memory/tags.rs Resolved
Comment thread crates/uteke-core/src/memory/tags.rs Resolved
Comment thread crates/uteke-core/src/memory/tags.rs Outdated

let mut updated = 0;
for (id, tags_str) in &rows {
let mut tags: Vec<String> = serde_json::from_str(tags_str).unwrap_or_default();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.
@ajianaz
ajianaz merged commit d00328d into develop Jun 7, 2026
7 checks passed
@ajianaz
ajianaz deleted the refactor/split-store-and-commands branch June 7, 2026 01:38
ajianaz added a commit that referenced this pull request Aug 13, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: split store.rs (2,065 LOC) into focused modules

1 participant