Skip to content

fix(memory): break created_at ties by id when a store loads its traces - #831

Merged
jddunn merged 4 commits into
masterfrom
fix/memory-hydration-tie-break
Nov 14, 2026
Merged

jddunn merged 4 commits into
masterfrom
fix/memory-hydration-tie-break

Conversation

@jddunn

@jddunn jddunn commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

What changed

The store's two hydration reads, the whole-brain load at a store's first read and hydrateScope, sorted by created_at DESC alone, so traces filed in the same millisecond loaded in whatever order the engine returned them. SQLite returned them in the order they were filed; PostgreSQL in the order its plan and the rows' updates left, so two brains holding the same traces could load them, and return equally scored lines, in different orders.

Both reads now sort by created_at DESC, id ASC (hydrationOrder). On PostgreSQL the id compares under COLLATE "C", since the database's default collation sorts by language (a before B) where SQLite's binary comparison puts B first; with it both engines give one order. The red run shows PostgreSQL ordering by the language collation (mt-A, mt-b, …).

Which direction: neither keeps SQLite's current order. Trace ids are random UUIDs, so the order of filing, which SQLite returned for the whole-brain load, matches neither ascending nor descending ids. Ascending was picked to match the created_at ASC, id ASC reads the Memory facade already makes. SQLite's order of same-millisecond rows changes from filing order to id order; the docs carry an Upgrading line for it.

Issue

Part of #754

Spec, plan and design

None

Docs

docs/memory/COGNITIVE_MEMORY.md: the "Loading and moving one scope" paragraph that described the open order of same-millisecond traces now states the id order, and a new "Upgrading from 0.17.3 or earlier" section (0.17.3 is the latest on npm) records the change of order on SQLite.

Tests

MemoryStore.hydration-order.test.ts runs on SQLite and, in Test & Lint, on PostgreSQL. Two brains hold the same eight traces (six in one millisecond, filed in neither id order, two of them with capitals), with a different set of rows updated in each; a fresh store on each must load them in one order through the whole-brain hydration and through hydrateScope, and a recall must return the equally scored six in that order.

@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 3 billable files and costs up to $0.75.

  • Ask an admin to make reviews automatic

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Or wait 2 minutes for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between f5c452e and f1505b2.

Files selected for processing: 3

  • docs/memory/COGNITIVE_MEMORY.md
  • src/cognition/memory/retrieval/store/MemoryStore.ts
  • src/cognition/memory/retrieval/store/__tests__/MemoryStore.hydration-order.test.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@sourcery-ai

sourcery-ai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Add a dialect-aware hydration order that sorts newest traces first and breaks timestamp ties by id in character-code order for both engines, applying it to whole-brain and scope hydration.

  • src/cognition/memory/retrieval/store/MemoryStore.ts L346-357, L1841, L2829

Documentation

Document deterministic tie ordering for both hydration paths and note the ordering change for upgrades from 0.17.3 or earlier.

  • docs/memory/COGNITIVE_MEMORY.md L357, L720-723

Tests

Verify whole-brain hydration, scope hydration, and equally scored recall preserve the expected id order on SQLite and optionally PostgreSQL, including case-sensitive id ordering.

  • src/cognition/memory/retrieval/store/__tests__/MemoryStore.hydration-order.test.ts L1-169

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@jddunn
jddunn marked this pull request as ready for review November 14, 2026 06:54
@sourcery-ai

sourcery-ai Bot commented Nov 14, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 22 hours and 10 minutes by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T06:55:46.222928Z f1505b2 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Make memory hydration order deterministic across SQLite and PostgreSQL

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 10-20 Minutes

Grey Divider

AI Description

• Break same-millisecond trace ties by ascending ID in both store hydration paths.
• Use PostgreSQL’s C collation to match SQLite’s character-code ordering.
• Test both engines and document the ordering change for existing SQLite users.
Diagram

graph TD
  B[("Brain traces")] --> W["First-read load"] --> O["Shared SQL order"] --> H["Hydrate rows"] --> V["Vector index"] --> R["Equal-score recall"]
  B --> S["Scope load"] --> O
Loading
High-Level Assessment

Keep the shared SQL ordering helper: it makes both bounded hydration reads deterministic before rows enter the index. Sorting after hydration would not resolve which tied rows a limited query selects.

Files changed (3) +188 / -3

Bug fix (1) +14 / -2
MemoryStore.tsApply shared tie-breaking order to both hydration reads +14/-2

Apply shared tie-breaking order to both hydration reads

• Adds a dialect-aware SQL ordering helper and uses it for first-read whole-brain hydration and hydrateScope. PostgreSQL compares IDs under C collation so its ascending ID order matches SQLite’s.

src/cognition/memory/retrieval/store/MemoryStore.ts

Tests (1) +169 / -0
MemoryStore.hydration-order.test.tsVerify hydration and recall order across database engines +169/-0

Verify hydration and recall order across database engines

• Creates two Brains with identical same-millisecond traces but different row updates, then checks whole-brain hydration, scope hydration, and equally scored recall. Runs on SQLite and, when configured, PostgreSQL; mixed-case IDs expose collation differences.

src/cognition/memory/retrieval/store/tests/MemoryStore.hydration-order.test.ts

Documentation (1) +5 / -1
COGNITIVE_MEMORY.mdDocument deterministic hydration order and SQLite upgrade impact +5/-1

Document deterministic hydration order and SQLite upgrade impact

• Explains character-code ID ordering for same-millisecond traces on both engines and its effect on equally scored recall. Adds an upgrade note warning that SQLite results may change order relative to 0.17.3 and earlier.

docs/memory/COGNITIVE_MEMORY.md

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can ask Qodo to dismiss a finding you disagree with, with your reason on record

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@jddunn
jddunn merged commit 3c7780a into master Nov 14, 2026
20 checks passed
@jddunn
jddunn deleted the fix/memory-hydration-tie-break branch November 14, 2026 07:06
@jddunn

jddunn commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

Review after merge, of f5c452e5..f1505b20.

No change needed in the code. Checked:

  • hydrationOrder covers every engine. The storage adapter names a dialect 'sqlite' or 'postgres' and nothing else, and the store's other engine checks read the same field.
  • The order is total. id is TEXT NOT NULL under PRIMARY KEY (brain_id, id), so no two rows of one brain tie on both keys, and COLLATE "C" applies to a text column.
  • hydrateRows files the rows one at a time in the order read. The cache, the stable sort in listTraces and the in-process index all keep the SQL order.
  • hydrateScope keeps idx_memory_traces_brain_scope_id (brain_id, scope, scope_id, created_at) for its first key. The id only sorts the rows inside one millisecond, and the LIMIT still ends the scan early. No index ordered the whole-brain read before this change either.
  • The test fails without the change on both engines, at its first assertion: run 43565213128 and run 43566179337. It passes with the change in run 43567016387, and Test & Lint runs the PostgreSQL case. No existing test changed.
  • Master is green on the merge commit 3c7780ac.

One docs detail, left as it is. The Upgrading line says SQLite used to load tied traces in the order they were stored, and it names both reads. That holds for the whole-brain read: the first red run shows mt-c, mt-A, …. For hydrateScope, SQLite most likely walked idx_memory_traces_brain_scope_id backwards, which returns tied rows in descending rowid, the reverse of the order they were stored. The red runs stop at the first assertion, so no run shows it. The line's advice holds either way: on SQLite, two equally scored traces of one millisecond can come back in the other order than before.

CodeRabbit and Sourcery did not review this head.

@jddunn

jddunn commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

QA: end to end through agent({ runtime: 'gmi' })

Result: pass. The fix holds on the path a host takes, on SQLite and on PostgreSQL. The test is in #833.

What was run. gmi-runtime.memory-tiebreak.e2e.test.ts builds a GMI over a durable store, on a SQLite file and on CI's PostgreSQL. One agent files twelve turns with the clock standing still, so every memory has one created_at, then closes. Rows are written again in a different set for each store, which moves them on PostgreSQL. A second agent built on the store then answers a question. The test reads the memory block the model received and the turn's memoryRecall record, and checks:

  • each group of equally scored candidates is listed by id in character-code order, and the block lists six equally scored replies in that order;
  • two stores holding the same memories send the same block and the same record;
  • SQLite and PostgreSQL send the same block and the same record.

The ids mix cases out of order, so a group sorted by filing order, by its reverse or by en collation would fail. The test also checks that its groups tell those orders apart.

Red before the fix. Run 43572324210, on master before this PR (test only, a3b6846):

  • SQLite listed one tied group newest filed first: B0007, z0005, M0003, a0001.
  • PostgreSQL listed a0001, M0003, z0005, B0007 in one store and M0003, a0001, B0007, z0005 in another, depending on which rows had been updated.

Green with the fix. Run 43573444894 on #833's head (b6d0907): all three cases pass. gmi-runtime.memory-recall.e2e.test.ts passes beside them.

Findings, fixed in #833

  1. The Upgrading line said that through 0.17.3 SQLite loaded same-millisecond traces in the order they were stored. On the GMI path the red run shows the newest filed first. The order followed how the engine read the rows, as it also did in this PR's own store-level red run. The line now says that.
  2. The Upgrading line did not say where a host sees the change. It now names the GMI's memory block and memoryRecall.candidates, and says the two engines give the same block.
  3. The comment in gmi-runtime.memory-recall.e2e.test.ts still said memories of one millisecond load in an order the engine picks. It now says they load by id.

Not covered end to end. hydrateScope is not reached through agent(), since a GMI's first recall runs the whole-brain hydration. hydrateScope is covered by MemoryStore.hydration-order.test.ts in this PR. Hybrid retrieval breaks fused-score ties by id on its own (fuse.ts), so it was not part of this check.

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.

1 participant