Repository navigation
Stop collection-name collisions from hard-rejecting in create_node - #2126
Conversation
…loses #2117) SqliteStore::create_node hard-rejected on a collection-name collision via a hardcoded, type-specific check that predates ADR-065 and is unrelated to the schema-declared `unique` field mechanism. NodeSpace is local-first the same way for collections as anything else: two offline devices can each validly create a collection with the same name. When one converges into a peer's store via the normal sync-apply create_node path, the error propagated out of nodespace-sync's apply_node_upsert, which never advances the cursor past a failed row — a benign duplicate collection name could wedge a sync cursor permanently. Converts collection-name uniqueness to the same suggest-don't-block posture ADR-065 established for person.email: a collision is detected before the insert, the write proceeds unconditionally, and both the new and pre-existing nodes are stamped with a non-blocking `_possible_duplicate` marker (OCC-bypassing, event-free, local_only) instead of being rejected. The marker reuses the existing POSSIBLE_DUPLICATE_FIELD constant and property shape so it round-trips through nodespace-sync's schema-driven local_only push/pull filtering without any sync-side code change. The ops-layer create_collection/rename_collection guards (collection_ops.rs) are unchanged and continue to reject a duplicate name for the interactive "create/rename a collection" user action — that path is synchronous, not on the sync-apply path, and never risks wedging a cursor. Adds an adversarial two-device convergence test suite (collection_name_convergence_test.rs) mirroring person_duplicate_convergence_test.rs: confirmed failing against the pre-fix code with the exact reproduction described in the issue, now passing. Updates two existing collection_membership_test.rs tests that asserted the old hard-rejection behavior to assert the new marker-based behavior instead. Co-Authored-By: Claude <[email protected]>
- Concurrent convergence test now pre-seeds the hub with a collision target created before the race starts, so both concurrently-applied nodes' pre-insert collision checks are guaranteed to see it regardless of how the two applies interleave with each other — lets the test assert markers deterministically instead of only asserting no-rejection. - Add a three-way collision test: since collection marking is automatic on every create (unlike person's opt-in mark_possible_duplicates), sequential convergence of N mutually-colliding collections transitively marks the whole set, not a LIMIT-1 pair. Locks in that (stronger) guarantee. - Add a test documenting, explicitly, that SqliteStore::update_node has no collision detection/marking at all today (a sync-applied rename that introduces a name collision is neither rejected nor marked) — a known, deliberately-deferred gap, now visible in the test suite instead of silent. - Correct the collection._possible_duplicate schema field description: it previously claimed collisions are scoped to "active" collections, which get_collection_by_name's query does not actually filter for (no lifecycle_status clause, unlike find_conflicting_unique). Also note the marker is create-time only. - Correct CollectionNodeBehavior's doc comment to scope the marker claim to create time specifically, since update/rename introduces no marker. - Expand mark_collection_name_collision's doc comment with the TOCTOU best-effort caveat and the create-only scope, matching precedent already documented for mark_possible_duplicates. Filed #2127 to track the two deferred gaps (rename-path marking, lifecycle_status filtering in get_collection_by_name) as their own, appropriately-scoped follow-up. Co-Authored-By: Claude <[email protected]>
|
APPROVE Self-approving after an independent full re-verification and a completed adversarial review round. Design decision recap: Option (a) — suggest-don't-block, matching ADR-065's posture for Independent re-verification performed:
Adversarial review round: dispatched a general-purpose sub-agent with full repo access (core + sync) to independently trace the fix, verify the
Merging. |
…e collections (#2139) * Mark rename-path collection-name collisions and scope lookup to active collections (closes #2127) Follow-up to #2126 (create-path suggest-don't-block marking). Closes two deferred gaps its adversarial review surfaced: - SqliteStore::update_node and update_node_with_version_check now detect a collection-name collision the same way create_node does — before the write, excluding the node's own id so a no-op or case-only rename never self-marks — and mark both sides with the existing _possible_duplicate marker after a successful write. Covers both the version-checked path (NodeService::update_node, used by nodespace-sync's apply_node_upsert "node already exists locally" branch) and the plain update_node path (NodeService::update_node_unchecked). - get_collection_by_name now filters to lifecycle_status = 'active', matching the pattern find_conflicting_unique already established for the ADR-065 unique-field mechanism. An archived collection no longer holds its name, so archiving one and creating (or renaming) another collection onto that name is no longer detected as a collision. Updates the doc comments this touches (mark_collection_name_collision, CollectionNodeBehavior, the _possible_duplicate schema field description) that previously described both gaps as known limitations. Flips the test that documented the rename-path gap to assert the fixed behavior, and adds regression tests for the unchecked update path, case-only-rename self-exclusion, and archived-collection name reuse on both the create and rename paths. Co-Authored-By: Claude <[email protected]> * Address adversarial review: fix archived-name reuse PK collision, tighten tests - collection_ops::create_collection's AlreadyExists guard previously checked get_collection_by_name (now active-only per Gap 2), but the id it inserts under is deterministic_collection_id(name) — a pure hash of the normalized name, independent of lifecycle_status. Recreating a collection with an archived collection's exact name therefore passed the guard and then hit a raw primary-key-constraint violation on insert (NodeService::create_node has no get-or-create semantics for the collection type), surfacing as an opaque OpsError::Internal instead of a clean rejection. Fixed by checking node existence by the deterministic id directly (any node at that id, active or archived, already occupies it) rather than by name. - update_node's unwrap_or(current.content.clone()) now uses unwrap_or_else to avoid an unconditional clone on the common Some(content) path. - Documented the invariant the self-exclusion filter's correctness relies on (a self-match via LIMIT 1's unordered result can only occur when a genuine third-party collision would already have been caught earlier). - Added regression tests: create_collection_op_rejects_reusing_an_archived_collections_name (the PK-collision fix), and case_only_rename_never_self_marks_via_unchecked_path (closes a coverage gap where the two update entry points implement self-exclusion independently). Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
Summary
Closes #2117.
SqliteStore::create_nodehard-rejected on a collection-name collision via a hardcoded, type-specific check that predates ADR-065 and is unrelated to the schema-declareduniquefield mechanism. NodeSpace is local-first the same way for collections as anything else: two offline devices can each validly create a collection with the same name. When one converges into a peer's store via the normal sync-applycreate_nodepath, the error propagated out ofnodespace-sync'sapply_node_upsert, and per that function's contract the sync cursor never advances past a failed row — a benign duplicate collection name could wedge a sync cursor permanently. Confirmed via a real reproduction (two offline stores each create a collection named "Work", converging one into the other reproduces the error).Decision: option (a) — suggest-don't-block, not option (b)
I read the collection creation/UI flow and the sync-apply path before deciding. Findings that drove the choice:
get_collection_by_namematches onLOWER(title)(case-insensitive), the same predicate both the old hard check and this fix's collision detection use.CollectionService::create_collectionalready derives a deterministic id (deterministic_collection_id, a UUIDv5 of the normalized name) specifically so two devices creating the same name converge onto ONE node id — this is the officially-blessed creation path (UI, gRPCcreate_collectionop, markdown import'sresolve_path) and never hits this bug at all, because sync-apply's "node already exists" branch takes over instead of "node absent" ever colliding.collection-typed node directly with a non-deterministic id — critically, this is exactly what a sync-pulled peer node does (it keeps the peer's own id, which is only deterministic if the peer also went throughcreate_collection; nothing enforces that upstream). This is also reachable from imports/agent tools that construct acollectionnode without going through the id-deterministic helper.SqliteStore::update_nodehas no equivalent check — collection renames were already suggest-don't-block at the store layer; onlycreate_nodehad the hard block. So the fix is narrowly scoped tocreate_node.collection_service.rs'sresolve_pathcomments describe names as "globally unique" as a design intent for its own deterministic-id path, not as an enforced database constraint elsewhere — and that intent is unaffected by this change, sinceresolve_pathstill only ever creates collections via the deterministic-id helper.find_conflicting_unique(ADR-065's shared predicate) only checksproperties.<type>.<field>viajson_extract— collection name lives incontent/title, notproperties, so this fix cannot literally reuse that function without extending the schema-uniquemechanism itself, which the issue explicitly says is out of scope ("does not require touching that code"). Instead, this reusesget_collection_by_name(the original lookup ADR-065 §3 saysfind_conflicting_uniquewas itself modeled on) as the collision predicate, and reuses the exact same marker mechanics (set_property_bool, OCC-bypassing, event-free,local_onlyschema field)NodeService::mark_possible_duplicatesestablished for person.email.Given all of that, option (a) — convert to suggest-don't-block — is the natural fit: it collapses collections into the same posture the rest of the codebase just established for person identity, with no evidence any other part of the system assumes collection names are hard-unique in a way that would break.
What changed
packages/core/src/db/sqlite_store/nodes.rs—SqliteStore::create_node:bail!on a collection-name collision.get_collection_by_namelookup, before the insert (so it unambiguously identifies the pre-existing other node), but the write now proceeds unconditionally._possible_duplicatemarker viaset_property_bool(OCC-bypassing: no version bump, no domain event — the same low-level primitivemark_possible_duplicatesuses). Marker-write failures are logged and swallowed; they never undo or fail the node creation that already succeeded.packages/core/src/models/core_schemas.rs— declared a_possible_duplicateboolean field on thecollectionschema (mirroringperson._possible_duplicate),local_only: true. This is what makes the marker round-trip correctly throughnodespace-sync's schema-drivenlocal_onlypush/pull filtering (local_only.rsreadslocal_only-flagged fields straight fromnodespace_core::models::core_schemas::get_core_schemas()) — so the marker is automatically excluded from push and never overwritten by a peer's pull, with zero sync-side code changes required.packages/core/src/behaviors/mod.rs— updatedCollectionNodeBehavior's doc comment, which claimed "Collection names are globally unique" as a blanket invariant; that's no longer accurate at the store layer and was actively misleading next to the code being changed.Tests:
packages/core/tests/collection_name_convergence_test.rs, mirroringperson_duplicate_convergence_test.rs's style/rigor: two independentSqliteStore+NodeServicepairs (real two-device simulation, no mocking), converging via the actualNodeService::create_nodepathapply_node_upsertuses. Four tests: the core reproduction (never rejects, both nodes survive, both get marked), a no-collision control, a case-insensitive collision, and a concurrent-apply race. Verified this test fails against the pre-fix code (git-stashed the fix, reran — all 3 collision-involving tests failed with the exact"Collection with name '...' already exists"error from the issue) and passes after the fix (all 4 pass).collection_membership_test.rs(test_collection_name_uniqueness_enforced,test_collection_uniqueness_case_insensitive) that asserted the old hard-rejection behavior directly againststore.create_node— they now assert the new non-blocking, both-sides-marked behavior instead.Scope notes (what I deliberately did NOT change)
collection_ops::create_collection/rename_collection's ownAlreadyExistspre-checks are unchanged. Those are synchronous, interactive, ops-layer guards for the "create/rename a collection" user action — they never sit on the sync-apply path (apply_node_upsertcallsNodeService::create_nodedirectly, not this op), so they can't wedge a cursor. This mirrors the issue's own framing: the bug is specificallySqliteStore::create_node's hard rejection.find_conflicting_unique/mark_possible_duplicates(the ADR-065 schema-uniquemechanism) are untouched, per the issue's explicit scoping.nodespace-syncchanges. I readapply_node_upsertand itsis_already_exists_errorrecovery path — it matches on"Database record" && "already exists", which the collection-name bail message never matched (it said"Collection with name '...' already exists"), so that recovery path was never actually catching this error in the first place; the error propagated straight throughErr(e) => return Err(e). Removing the error at its source in core is sufficient; there's nothing left for the sync side to handle differently. (Nodespace-sync will pick this fix up whenever its pinned core rev is next bumped — no urgency to force that here, and I don't want to race a routine, unrelated core-rev pin-bump that may already be in flight there.)Testing
cargo test -p nodespace-core— 1154 + 32 + 4 + (other integration suites) passed, 0 failed.cargo test -p nodespace-daemon— 147 + integration suites passed, 0 failed (gRPC round-trip, per-db, import round-trip all green — confirms no downstream regression through the daemon layer).cargo clippy -p nodespace-core --all-targets— clean.cargo clippy -p nodespace-daemon --all-targets— clean.cargo fmt -p nodespace-core -- --check— clean.Adversarial review response
An independent adversarial review of this PR ran before merge. Verdict: no blocking issues — the wedge is genuinely fixed and correctly verified (traced the full
NodeService::create_node→SqliteStore::create_nodechain, independently verified againstnodespace-sync'sapply_node_upsert, and independently confirmed thelocal_onlypush/pull exclusion claim by readingnodespace_sync::local_onlydirectly). It surfaced real, non-blocking findings, all addressed:bail!entirely, no-rejection was already guaranteed with no remaining code path to test. Redesigned it to pre-seed the hub with a collision target before the race starts, so both concurrently-applied nodes' pre-insert collision checks are guaranteed to see it regardless of interleaving between the two applies — now asserts markers deterministically.create_nodecall (unlike person's opt-inmark_possible_duplicates), so sequential convergence of N mutually-colliding collections transitively marks the whole set. New test locks that in.SqliteStore::update_nodehas no collision detection at all (pre-existing, not a regression) — a sync-applied rename that introduces a name collision is neither rejected nor marked. Now an explicit, visible test contract instead of a silent gap.collection._possible_duplicate's description said collisions are scoped to "active" collections;get_collection_by_namedoesn't actually filter bylifecycle_status(unlikefind_conflicting_unique, the mechanism this claimed to mirror). Corrected the description and noted the marker is create-time only.get_collection_by_namehas nolifecycle_statusfilter so archiving a collection doesn't free its name for possible-duplicate purposes.All 6 tests in
collection_name_convergence_test.rs(was 4) pass, along with the fullnodespace-core(1154+ tests) andnodespace-daemonsuites, clippy, and fmt.