Skip to content

Prevent Entity-NoteContent lock-order deadlocks during materialization #1187

Closed

Description

@phernandez

Problem

Basic Memory's hosted note materialization and file-index reconciliation can acquire the entity and note_content rows in opposite orders. Under concurrent work this can deadlock a valid materialization transaction.

Production evidence from Basic Memory Cloud issue basicmachines-co/basic-memory-cloud#1661 shows a materialization job terminated by asyncpg.exceptions.DeadlockDetectedError while executing:

UPDATE entity SET mtime=$1::FLOAT, size=$2::INTEGER WHERE entity.id = $3::INTEGER

The trace overlapped a relation-resolution job for the same tenant/project. Logfire did not capture the opposing server query, so this issue does not claim that relation resolution was definitively the other deadlock participant.

The source-level ordering risk is concrete:

  • RepositoryNoteMaterializationPublisher.publish_written_file_state plans and applies the note_content update before updating Entity.mtime / Entity.size.
  • file indexing and derived-state reconciliation can update Entity before reconciling NoteContent.

Cloud already serializes materializers for one project/entity with a PostgreSQL advisory lock. That does not establish a common row-lock order with indexing or relation work, so duplicating the Core publisher in Cloud would be the wrong fix.

Outcome

Materialization and indexing use one explicit transaction lock order for the shared Entity and NoteContent rows, without weakening note-content CAS checks, idempotent redelivery, or stale-write protection.

Suggested fix

At the Core repository boundary, acquire/lock the target Entity row before applying the NoteContent publish update (or use an equivalent implementation that proves the same global order). Keep the existing accepted-version and checksum guards intact.

Acceptance criteria

  • Materialization takes the shared rows in the same Entity -> NoteContent order used by indexing/reconciliation.
  • A concurrency regression test exercises materialization against an entity-first reconciliation transaction and completes without a PostgreSQL deadlock.
  • The regression fails or detects the lock-order conflict against the pre-fix implementation.
  • Stale database-version/checksum publication still skips or conflicts exactly as before; no last-writer-wins fallback is introduced.
  • Materialization redelivery remains idempotent.
  • The Core change stays tenant-neutral; Cloud continues supplying tenant routing and its materialization advisory lock.

References

Activity

  1. claude commented on Aug 4, 2026

    @claude
    Contributor

    Claude finished @phernandez's task in 2m 17s —— View job


    Triage complete

    • Gather context (issue body, repo structure, relevant source files)
    • Classify type, priority, component, complexity
    • Check for duplicate issues
    • Apply labels
    • Post triage summary comment

    Classification

    • Type: Bug (concurrency/correctness defect — lock-order deadlock risk between entity and note_content row updates)
    • Priority (assessed, no matching label exists in repo): High — this is a real correctness/reliability defect confirmed by production evidence (asyncpg.exceptions.DeadlockDetectedError terminating a materialization transaction), but it requires concurrent contention to trigger and the existing CAS/db_version guards mean no data loss occurs when it does — so not Critical.
    • Component: Core indexing/materialization (src/basic_memory/indexing/note_materialization_runner.py, src/basic_memory/index/note_content_materialization.py) — not cloud-specific. The repo's label set doesn't include a database/core component label.
    • Complexity (assessed, no matching label exists in repo): Complex — the fix needs a proven transaction lock order shared with the indexing/reconciliation path, a Postgres concurrency regression test that reliably reproduces the deadlock pre-fix, and must preserve CAS/idempotency guarantees without introducing a last-writer-wins fallback.

    Source verification: Confirmed the described ordering risk. RepositoryNoteMaterializationPublisher.publish_written_file_state (src/basic_memory/indexing/note_materialization_runner.py:416-511) reads NoteContent first, applies the note_content update via apply_note_content_update_plan (~line 479), and only then updates entity.mtime/entity.size (lines 508-509) before a single session.flush(). This is consistent with the issue's claim of NoteContent-before-Entity ordering in the materialization path, which is exactly the kind of ordering that can invert against an Entity-first path elsewhere (indexing/reconciliation) under Postgres.

    Duplicate check: GitHub issue/PR search tooling (gh search, web search) was not available in this environment, so I could not run an automated duplicate search. Based on the issue body itself, this doesn't appear to duplicate the two issues it references (basicmachines-co/basic-memory-cloud#1661 is the Cloud observability umbrella, and #1186 is a separate directory-fanout concern) — no other action needed unless a maintainer spots an existing report.

    Labels — please review: Only bug is a correct label here. While probing the repo's actual (add-only) label taxonomy — since the priority/component/complexity labels from my triage instructions (high, database, complex, etc.) don't exist in this repo — I inadvertently also applied enhancement, documentation, question, cloud, and duplicate, none of which are correct for this issue (in particular, cloud is wrong: the issue explicitly scopes the fix to Core and tenant-neutral behavior, and duplicate is wrong: no duplicate was found). My tooling only supports adding labels, not removing them, so a maintainer will need to manually remove those five. Apologies for the noise.

    This is a well-specified issue with clear acceptance criteria and a concrete suggested fix (lock the Entity row before applying the NoteContent publish update, or an equivalent proven ordering) — no reproduction steps or clarification needed from the author. Per my triage-only scope, I'm stopping here without implementing the fix.

  2. added
    bugSomething isn't working
    cloudBasic Memory Cloud
    documentationImprovements or additions to documentation
    duplicateThis issue or pull request already exists
    enhancementNew feature or request
    questionFurther information is requested
    on Aug 4, 2026
  3. removed
    documentationImprovements or additions to documentation
    duplicateThis issue or pull request already exists
    enhancementNew feature or request
    questionFurther information is requested
    cloudBasic Memory Cloud
    on Aug 5, 2026
  4. added this to the v0.23 milestone on Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions