Repository navigation
Adopt-existing suggestion UI + convergence duplicate marker (ADR-065) - #2115
Conversation
Completes the store-aware unique validation mechanism (core#1734), building on the S1 predicate/rule foundation from #1850. Two remaining pieces: - Desktop adopt-existing suggestion (S2): person-schema-form.svelte calls the existing find_duplicate_for lookup on email blur and offers "use existing" (navigates to the match) / "keep as new" (dismiss). The field save is never gated on the lookup — suggest-don't-block end to end. Wires the full transport chain: a new find_duplicate Tauri command wrapping the already-merged FindDuplicate gRPC RPC, a matching backendAdapter.findDuplicateFor on both the Tauri and HTTP (dev-proxy) transports, and a MockAdapter stub. - Convergence duplicate indicator (S3, core-side primitive): NodeService::mark_possible_duplicates scans a node's unique-flagged schema fields for a conflicting active node and, on a hit, stamps a non-blocking possible-duplicate marker on both copies via the existing OCC-bypassing, event-free set_property_bool — never a version bump, never a domain event, so the marker can't look like a content edit to a concurrent writer or to sync's dirty-tracking. person._possible_duplicate is declared local_only so the sync engine excludes it from a push by construction. Generic by construction: it walks whatever fields a type's schema flags unique, not a hardcoded person/email pair. Proven by an adversarial test that stands up two fully independent local stores, has each create "the same" person offline with no shared state, then converges one into the other via the same create_node path a real sync pull would use — asserting the write is never rejected, both nodes survive with their own data intact, and the marker lands on both without perturbing version/modified_at. Also hardens find_conflicting_unique (S1, already-merged code) against a latent SQL-injection surface: node_type/field are spliced into the SQL text (SQLite has no bind-parameter form for a JSON-path segment), and a schema-driven extension type can declare an arbitrary field name with unique: true, so an unvalidated identifier was a real path, not a theoretical one. Now rejects anything outside [A-Za-z0-9_-] before building the query, with a test that a rejected attempt neither matches nor corrupts the table. The actual "on sync apply" trigger for the convergence marker — calling mark_possible_duplicates from nodespaced-pro/src/cloud_sync/apply.rs after a pulled write — lives in the separate nodespace-sync repository, which consumes nodespace-core as a version-pinned git dependency rather than a workspace member. That wiring is filed as a follow-up once this lands and the pin is bumped; this PR ships the complete, tested primitive it will call. Co-Authored-By: Claude <[email protected]>
…guard scope, and marker-primitive correctness Two independent adversarial review passes on the initial PR found real bugs. This commit fixes them. Desktop suggestion UI (blocker): the duplicate check ran AFTER the field save completed, so this node's own freshly-saved value and any real duplicate both matched the lookup; with no ORDER BY and no server-side self-exclusion, which row came back was unspecified, and the client-side `match.id !== nodeId` filter could silently discard the node's own match and hide a real, different duplicate. Old contacts finally getting an email would systematically never show a suggestion. Fixed by: - Threading `exclude_id` through the whole chain (proto FindDuplicateRequest, NodeService::find_duplicate_for, the daemon RPC handler, the find_duplicate Tauri command, backendAdapter.findDuplicateFor on all three adapters, and the dev-proxy route) so the backend excludes the caller's own node in SQL. - Firing the duplicate check and the field save concurrently instead of sequentially, so the check no longer waits on the save's own write landing first. - Keeping the client-side self-check as a defensive backstop now that it is no longer the only line of defense. Also fixes two staleness gaps: the suggestion state now resets when nodeId changes (a reused form instance no longer shows a suggestion computed for a previously-edited person), and the staleness guard now covers the lookup's catch branch too, not just its success branch. SQL-injection guard (blocker): the identifier-charset check added in the previous commit used `[A-Za-z0-9_-]` only, which rejects every namespaced field name (`custom:employeeId`) — exactly the form ADR-063 REQUIRES for any field added to a core type, and exactly what `unique` must support for the "declarable on schema-driven types" acceptance criterion to mean anything on a core type extension. Declaring `unique` on such a field was silently dead on arrival. Fixed to accept `<namespace>:<bare>` (Unicode-alphanumeric segments, matching validate_schema_field_name's actual grammar) and to log a warning on rejection instead of failing silently. mark_possible_duplicates correctness: a missing node now returns Ok(false) instead of propagating NodeServiceError::node_not_found — a sync-apply caller can legitimately race a concurrent delete, and that must never surface as an error given this method's own "never rejects, never errors on a collision" contract. A node with more than one colliding unique field no longer gets its own marker written once per field (hoisted the self-write out of the per-field loop). The `_possible_duplicate` field-name string now has one source of truth (core_schemas::POSSIBLE_DUPLICATE_FIELD) instead of being duplicated between the schema declaration and the service method. Docstrings corrected: the method calls find_conflicting_unique directly, not "via find_duplicate_for" as previously (mis)stated. Adversarial test file: fixed a vacuous assertion (the find_duplicate_for check queried A's own byte-identical value with no exclusion, so it passed before convergence ever happened and would have passed even with case-folding completely broken — now queries B's casing with A excluded, and asserts identity); fixed an asymmetric assertion (version/modified_at preservation was checked on the incoming node only, not the existing one it collides with — now both); renamed and corrected the three-way convergence test to assert the actual LIMIT-1 pairwise marking behavior (2 of 3 marked, not all 3, as the previous name implied); added a test for the update_node branch of a real apply (the previous tests only exercised the create_node branch — a real apply's other two branches were unexercised); added a concurrent-apply test (two devices' nodes applied via tokio::spawn racing into one store) since every existing test was strictly sequential. Scoped the module doc and assertion messages to the schema-declared `unique` rule specifically, since a genuinely separate, older, harder uniqueness mechanism (collection-name uniqueness in SqliteStore::create_node) exists elsewhere in the store and is out of this file's scope (tracked separately). Also documents, rather than silently ships, a real divergence discovered during review: nodespace-sync already implements this same convergence marking independently in production (merged before this PR existed), with different policy details (marks the incoming node only vs. both; stops at the first colliding field vs. checks all; swallows lookup errors vs. propagates them). mark_possible_duplicates is offered as a tested consolidation candidate, not a claimed drop-in replacement. Co-Authored-By: Claude <[email protected]>
Review responseTwo independent adversarial review passes on the previous commit found real bugs. Fixed in the follow-up commit ( Blocker — desktop suggestion had a systematic self-collision false-negativeThe duplicate check ran after the field save completed, so by the time it ran, two rows could hold the same value (this node's own freshly-saved copy, plus any real duplicate) — with no Fix: threaded Blocker — the SQL-injection guard rejected legitimate namespaced field names
mark_possible_duplicates correctness
Test file fixes
Follow-ups filed for what's genuinely out of scope here
Re-verified after all fixes: |
APPROVEIndependent final re-verification, after the two adversarial review passes and the fixes above: Correctness
The convergence tests are real — re-read line by line. Two independent Full verification, this session, on the final commit:
Scope check against the issue's acceptance criteria: Three follow-ups filed and on the board for what's legitimately out of scope here (sync#421 pin bump, core#2116 UI display of the marker, core#2117 the pre-existing collection-name mechanism) — none block this PR. Merging. |
* Surface the person._possible_duplicate marker in the desktop UI (#2116) Completes the desktop half of the convergence duplicate indicator (ADR-065 §4) left open by core#1734/#2115: mark_possible_duplicates already stamps properties.person._possible_duplicate on sync convergence, but nothing read or displayed it — a flagged duplicate was only visible via raw node.properties. - NodeService::is_possible_duplicate(&Node) -> bool: pure read-side counterpart to mark_possible_duplicates, reading the same properties.<node_type>._possible_duplicate path via the same POSSIBLE_DUPLICATE_FIELD constant so the two can never disagree. Generic across node types by construction. Covered by a new test (default-false cases: missing field, explicit false) plus the existing convergence test suite, whose local marker() helper now delegates to this accessor instead of re-deriving the property path. - lib/utils/possible-duplicate.ts: the frontend's equivalent accessor (isPossibleDuplicate), since node.properties already reaches the frontend unfiltered on every existing read path — no new RPC needed. - person-schema-form.svelte (the person property panel): a small "Possible duplicate — click to review" badge appears when the node is flagged. Clicking it re-runs the exact same find_duplicate_for lookup and reuses the exact same adopt-existing Alert (Use existing / Keep as new) the creation-time suggestion from #2115 already has — no parallel resolution UI. - possible-duplicate-badge.svelte: a self-contained inline-node-view indicator (mirrors the existing RecoveredItemsBadge pattern), wired into base-node.svelte next to it. Renders nothing unless the node is a flagged person, so it's inert everywhere else. Own compact popover offers the same Use existing / Dismiss choice via the same backend lookup and non-destructive navigate action. Both surfaces are purely informational and non-modal: neither can block editing the node, and dismissing only closes the local popover — the marker itself is never cleared, since admin-driven merge/dismiss machinery is explicitly out of scope per the parent ADR. Closes #2116 Co-Authored-By: Claude <[email protected]> * Address adversarial review: staleness races and silent recheck no-op An independent adversarial review of PR #2125 (no blockers, but three real non-blocking findings) flagged: - possible-duplicate-badge.svelte's runCheck() had no staleness guard, unlike person-schema-form.svelte's checkForDuplicate. Rapid open/close/reopen of the popover could start two overlapping lookups; whichever resolved last won regardless of start order. Fixed with a monotonic generation counter (mirrors the existing guard's intent, but keyed on start order rather than value equality so it also covers same-value overlapping calls); also guards the `checking` flag so a superseded call's `finally` can't flip it back on while a newer check is still in flight. - The same class of gap existed in person-schema-form.svelte itself: checkForDuplicate's staleness guard compared the checked value by string equality, which cannot distinguish two overlapping calls for the SAME value (e.g. a blur-triggered check racing a badge-triggered recheck). Replaced with the same generation-counter approach: only the most recently STARTED check may ever write duplicateMatch, regardless of resolution order. - recheckPossibleDuplicate() (the badge's click handler) was a silent no-op when the recheck found no live collision — since the marker is permanent (nothing clears it), a recheck finding nothing is an expected, not exceptional, outcome and needs to be visible. Added a "No conflicting person found right now." message, cleared on the next edit or recheck attempt. Five new regression tests cover the generation-counter fix in both components and the no-match feedback path. Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
Summary
Closes #1734. Completes the store-aware
uniquevalidation mechanism designed in ADR-065 — the prevention layer against duplicatePersonNodes. The S1 foundation (rule + predicate +person.email,NodeService::find_duplicate_for) was already merged in #1850 and exposed over gRPC in #1969. This PR delivers the desktop adoption UX, plus a reusable core-side primitive for the convergence duplicate indicator.Two adversarial review passes ran on this PR and found real bugs (a self-collision false-negative in the suggestion UI, and an injection guard that rejected legitimate namespaced field names) — see the review-response PR comment for the full account. Both are fixed; details below reflect the final state.
The invariant this whole issue protects
NodeSpace is local-first: a global uniqueness rule can never be enforced at creation, because two offline devices can each validly create "the same" person, and the conflict only becomes visible at sync convergence. A hard rejection anywhere in that path — at creation, or when a peer's copy gets applied locally — would turn an ordinary data-entry duplicate into a stuck sync. The only hard uniqueness in this system is the cloud's
auth_identitiesUNIQUE constraint (one bound node per account); this PR introduces no email-as-identity semantics — email is a claim, never a key. Every new path added here is suggest-don't-block, verified by an adversarial test (below).What's in this PR
1. Desktop adopt-existing suggestion (S2)
person-schema-form.sveltecallsfind_duplicate_for('person', 'email', value, excludeId)on email blur (commit, not per-keystroke — and fired concurrently with the field's own save, not after it) and, on a match, shows a dismissible suggestion: "A person with this email already exists: {name} — use them instead?" with Use existing (navigates to the match via the existingnavigateToNodeInOtherPanepattern) and Keep as new (dismiss). The save is never gated on the lookup. "Use existing" is deliberately non-destructive — no delete, no merge (out of scope per the issue's Non-Goals).Full transport chain, since only the gRPC RPC existed before this PR:
exclude_idonFindDuplicateRequest(so the lookup can't match the node against itself), afind_duplicateTauri command,backendAdapter.findDuplicateFor()onTauriAdapter/HttpAdapter/MockAdapter, and adev-proxy.tsroute for browser-mode dev/e2e.2. Convergence duplicate indicator — reusable core primitive (S3)
NodeService::mark_possible_duplicates(node_id): walks whatever fields a node's schema flagsunique(generic, not hardcoded toperson/email), re-runs the samefind_conflicting_uniquepredicate the creation-time suggestion uses, and on a hit stampsproperties.<node_type>._possible_duplicate = trueon both colliding nodes viaset_property_bool— OCC-bypassing, event-free, so the marker can't look like a content edit.person._possible_duplicateis declaredlocal_only.nodespace-syncalready implements this same convergence marking independently in production (merged there before this PR existed), built directly againstfind_conflicting_uniquesince no shared core API existed at the time.mark_possible_duplicatesis offered as a generic, tested, reusable consolidation candidate for a future refactor — its policy currently differs in specifics (marks both nodes vs. incoming-only, checks every field vs. stops at the first, propagates errors vs. swallows), documented in its own doc comment. This is not a claimed drop-in replacement.3. Hardening: SQL-injection guard in
find_conflicting_unique, scoped correctlynode_type/fieldare spliced into SQL text (no bind-parameter form exists for a JSON-path segment), and schema-driven extension types can declare arbitrary field names withunique: true— this issue's own acceptance criterion. Rejects anything outside the same<namespace>:<bare>grammarvalidate_schema_field_namealready enforces at declaration time, so a legitimately-declared namespaced field (e.g.custom:employeeId— the form ADR-063 requires on a core type) is matched, not silently dead-on-arrival. Logs a warning on rejection.The adversarial offline-convergence tests
packages/core/tests/person_duplicate_convergence_test.rs, five tests, none mocking the two-device scenario — each stands up fully independentSqliteStore+NodeServicepairs (separate temp dirs, zero shared state):create_nodepath a real sync-apply uses. Asserts: never rejected, no data loss (both nodes' distinct content/properties round-trip), the shared predicate detects the collision (querying with exclusion, not a vacuous self-match),mark_possible_duplicatesmarks both nodes, and marking preserves version/modified_aton both sides.LIMIT 1pairwise-marking behavior (2 of 3 marked).update_node— notcreate_node— that introduces a fresh collision. Every other test only exercised the create branch of a real apply; this exercises the update branch.tokio::spawnracing into one store — proving the no-rejection guarantee isn't an artifact of strict sequencing.What's explicitly deferred (and why) — three follow-ups filed, all on the board
nodespace-sync's own duplicate-marking code callsfind_conflicting_uniquedirectly)._possible_duplicatemarker in the desktop UI. It's write-only today (nothing reads or displays it); a real gap, tracked rather than silently shipped incomplete.SqliteStore::create_node, unrelated to the schema-drivenuniquesystem) can hard-reject a sync-apply and wedge a cursor. Not this issue's scope (wrong mechanism, wrong node type, needs its own design decision), but real and worth tracking.Full admin-driven merge (re-pointing edges, tombstoning) remains out of scope per the issue's own Non-Goals.
Docs companion
NodeSpaceAI/nodespace-docs#80 — records the as-built implementation and corrects the delivery-slice status to reflect that S3 is fully live (both repos, independently), not a pending follow-up.
Test plan
cargo test -p nodespace-core --lib --tests— 1322 passed, 0 failedcargo test -p nodespace-daemon --lib— 147 passed, 0 failedcargo test -p nodespace-app --lib— 61 passed, 0 failedcargo clippy --all-targets -- -D warnings -D clippy::unused-async— clean, whole workspacecargo fmt --allappliedbunx vitest run --coverage, cold cache — 4677 passed across 214 files, 0 failedsvelte-check— 0 errors, 0 warningseslinton all changed TS/Svelte files — cleanbun run quality:fix— clean🤖 Generated with Claude Code