Skip to content

Adopt-existing suggestion UI + convergence duplicate marker (ADR-065) - #2115

Merged
mstomar125 merged 2 commits into
mainfrom
worktree-issue-1734-person-uniqueness
Aug 17, 2026
Merged

mstomar125 merged 2 commits into
mainfrom
worktree-issue-1734-person-uniqueness

Conversation

@mstomar125

@mstomar125 mstomar125 commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #1734. Completes the store-aware unique validation mechanism designed in ADR-065 — the prevention layer against duplicate PersonNodes. 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_identities UNIQUE 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.svelte calls find_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 existing navigateToNodeInOtherPane pattern) 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_id on FindDuplicateRequest (so the lookup can't match the node against itself), a find_duplicate Tauri command, backendAdapter.findDuplicateFor() on TauriAdapter/HttpAdapter/MockAdapter, and a dev-proxy.ts route 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 flags unique (generic, not hardcoded to person/email), re-runs the same find_conflicting_unique predicate the creation-time suggestion uses, and on a hit stamps properties.<node_type>._possible_duplicate = true on both colliding nodes via set_property_bool — OCC-bypassing, event-free, so the marker can't look like a content edit. person._possible_duplicate is declared local_only.

nodespace-sync already implements this same convergence marking independently in production (merged there before this PR existed), built directly against find_conflicting_unique since no shared core API existed at the time. mark_possible_duplicates is 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 correctly

node_type/field are spliced into SQL text (no bind-parameter form exists for a JSON-path segment), and schema-driven extension types can declare arbitrary field names with unique: true — this issue's own acceptance criterion. Rejects anything outside the same <namespace>:<bare> grammar validate_schema_field_name already 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 independent SqliteStore + NodeService pairs (separate temp dirs, zero shared state):

  1. Main case: Device A and Device B each independently create "Alice" with the same (differently-cased) email, unaware of each other. Device B's node is applied into Device A's store via the same create_node path 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_duplicates marks both nodes, and marking preserves version/modified_at on both sides.
  2. No-collision convergence: nothing gets marked, still never rejects.
  3. Three-way convergence: three devices, sequential applies, all survive; asserts the actual LIMIT 1 pairwise-marking behavior (2 of 3 marked).
  4. Update-path convergence: a node already present locally (as if pulled earlier) receives an incoming update via update_node — not create_node — that introduces a fresh collision. Every other test only exercised the create branch of a real apply; this exercises the update branch.
  5. Concurrent convergence: two devices' colliding nodes applied via tokio::spawn racing 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

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 failed
  • cargo test -p nodespace-daemon --lib — 147 passed, 0 failed
  • cargo test -p nodespace-app --lib — 61 passed, 0 failed
  • cargo clippy --all-targets -- -D warnings -D clippy::unused-async — clean, whole workspace
  • cargo fmt --all applied
  • Frontend: bunx vitest run --coverage, cold cache — 4677 passed across 214 files, 0 failed
  • svelte-check — 0 errors, 0 warnings
  • eslint on all changed TS/Svelte files — clean
  • bun run quality:fix — clean
  • Pre-push gate re-ran the full suite on every push — green
  • Two independent adversarial review passes — findings addressed, see review-response comment

🤖 Generated with Claude Code

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]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Review response

Two independent adversarial review passes on the previous commit found real bugs. Fixed in the follow-up commit (257ace95).

Blocker — desktop suggestion had a systematic self-collision false-negative

The 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 ORDER BY on the lookup and no server-side self-exclusion, which one came back was unspecified, and the client-side match.id !== nodeId filter could discard the node's own match and hide the real, different duplicate. This wasn't an edge case — an old contact finally getting an email typed in would systematically never show a suggestion.

Fix: threaded exclude_id through the whole chain (proto → find_duplicate_for → daemon RPC → Tauri command → backendAdapter → the Svelte component), and changed the check to fire concurrently with the save rather than after it. Kept the client-side self-check as a defensive backstop now that it's no longer the only line of defense. Also fixed two related staleness gaps: the suggestion now resets when nodeId changes (a reused form instance no longer shows a stale suggestion for a previous person), and the staleness guard now covers the lookup's catch branch, not just its success branch. New/updated tests cover all of this (daemon-level exclude_id test with a real second colliding node, and five frontend tests including a concurrency-ordering assertion).

Blocker — the SQL-injection guard rejected legitimate namespaced field names

[A-Za-z0-9_-] has no :, so it rejected every <namespace>:<bare> field name — exactly the form ADR-063 requires for a field added to a core type, and exactly what unique must support for "declarable on schema-driven types" to mean anything on a core-type extension. unique: true on custom:employeeId was silently dead on arrival with no error. Fixed to accept the same grammar validate_schema_field_name already enforces at declaration time (Unicode-alphanumeric segments, at most one :), with a tracing::warn! on rejection so a future reader isn't left debugging a silent no-op. New test proves a namespaced field is actually matched, not just that garbage is still rejected.

mark_possible_duplicates correctness

  • A missing node (e.g. a concurrent delete a sync-apply caller can legitimately race) now returns Ok(false) instead of propagating an error — the method's own docstring promises it never errors on this class of thing, and it didn't.
  • A node with more than one colliding unique field no longer gets double-written its own marker (hoisted the self-write out of the per-field loop).
  • _possible_duplicate the string now has one source of truth (core_schemas::POSSIBLE_DUPLICATE_FIELD) instead of being duplicated.
  • Docstring corrected: it calls find_conflicting_unique directly, not "via find_duplicate_for" as previously (mis)stated — same predicate, different caller.
  • Documented, rather than silently shipped, the real divergence from nodespace-sync's already-production-live equivalent (marks-both vs. marks-incoming-only, checks-all-fields vs. stops-at-first, propagates-errors vs. swallows) — offered as a tested consolidation candidate, not a claimed drop-in replacement.

Test file fixes

  • A vacuous assertion (queried Device A's own byte-identical email with no exclusion — passed before convergence ever happened, and would have passed even with case-folding completely broken) is now a real one: queries Device B's casing with A excluded, asserts identity.
  • An asymmetric version/modified_at-preservation assertion (checked only the incoming node, not the one it collides with) now checks both.
  • The three-way convergence test's name and assertions now match what the LIMIT 1 predicate actually does (2 of 3 nodes marked, not all 3) instead of asserting a boolean that let the name overclaim.
  • Added a test for the update_node branch of a real apply (a node already present locally receiving a pulled update that introduces a fresh collision) — every previous test only exercised the create_node branch.
  • Added a concurrent-apply test (two devices' nodes applied via tokio::spawn racing into one store) — every previous test was strictly sequential.
  • Scoped the module doc and assertion language to the schema-declared unique rule specifically, rather than an unqualified "sync apply never rejects on any uniqueness collision" claim.

Follow-ups filed for what's genuinely out of scope here

Re-verified after all fixes: cargo test -p nodespace-core --lib --tests (1322 passed), -p nodespace-daemon --lib (147 passed), -p nodespace-app --lib (61 passed), cargo clippy --all-targets -- -D warnings -D clippy::unused-async (clean), frontend bunx vitest run --coverage cold cache (4677 passed / 214 files), svelte-check (0/0), eslint (clean), pre-push gate (green).

@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE

Independent final re-verification, after the two adversarial review passes and the fixes above:

Correctness

  • mark_possible_duplicates: correctly self-excludes (Some(&node.id) in find_conflicting_unique), correctly walks all unique-flagged fields with no cross-field bleed, correctly returns Ok(false) (not an error) for a vanished node, correctly writes each colliding node's marker exactly once even with multiple colliding fields. POSSIBLE_DUPLICATE_FIELD has one source of truth.
  • find_conflicting_unique's identifier guard is now a strict superset of validate_schema_field_name's grammar (verified: allows <namespace>:<bare>, Unicode-alphanumeric segments) — proven by a positive test (namespaced field actually matches) alongside the existing negative (injection attempt rejected, store unharmed).
  • find_duplicate_for's new exclude_id threads cleanly through proto → daemon → Tauri → adapter → component; verified end to end with a daemon-level test that creates a second, genuinely different colliding node and confirms exclusion surfaces it rather than nothing.
  • The Svelte component's check/save concurrency fix, staleness guards (success AND error path), and nodeId-change reset are all covered by dedicated tests, not just described in comments.

The convergence tests are real — re-read line by line. Two independent SqliteStore/NodeService pairs, zero shared state, id preservation verified, no-rejection assertions paired with positive detection (not vacuous), version/modified_at preservation checked on both colliding nodes, update-path and concurrent-apply branches now covered in addition to the create-path.

Full verification, this session, on the final commit:

  • cargo build --workspace — clean
  • cargo test -p nodespace-core --lib --tests — 1322 passed, 0 failed
  • cargo test -p nodespace-daemon --lib — 147 passed, 0 failed
  • cargo test -p nodespace-app --lib — 61 passed, 0 failed
  • cargo clippy --all-targets -- -D warnings -D clippy::unused-async — clean
  • cargo fmt --all — no diff
  • bunx vitest run --coverage, cold cache — 4677 passed, 214 files, 0 failed
  • svelte-check — 0/0
  • eslint — clean
  • bun run quality:fix — clean, no further changes
  • Pre-push gate — green on every push

Scope check against the issue's acceptance criteria: unique rule store-aware and per-database ✓; person.email case-insensitive, ignores empty ✓; creation-time adopt-existing suggestion, create-anyway preserved ✓; sync-apply-equivalent adversarial test proving no rejection + both-nodes-present + duplicate indicator ✓; declarable on schema-driven extension types (now genuinely, after the B2 fix) ✓; test:all / quality:fix clean ✓; docs companion opened (nodespace-docs#80) ✓.

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.

@mstomar125
mstomar125 merged commit a23226c into main Aug 17, 2026
@mstomar125
mstomar125 deleted the worktree-issue-1734-person-uniqueness branch August 17, 2026 13:25
mstomar125 added a commit that referenced this pull request Aug 18, 2026
* 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]>
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.

PersonNode duplicate prevention: schema-level uniqueness validation class, creation-time adoption, convergence policy

1 participant