Skip to content

Store-aware unique schema validation: rule + predicate + person.email (slice 1) - #1850

Merged
mstomar125 merged 1 commit into
mainfrom
wt-1734-unique-validation
Jul 31, 2026
Merged

mstomar125 merged 1 commit into
mainfrom
wt-1734-unique-validation

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Part of #1734 (slice 1 of 3 — does not close). Architecture recorded in ADR-065 (nodespace-docs).

Decision (mine, per the issue owner's direction — recorded on the issue + ADR)

The unique rule is evaluated at the service/store layer, not on the NodeBehavior trait (Option B): the trait stays pure/storeless so schema-only extension types inherit the rule by flagging a property. And enforcement is suggest-don't-block — no create/update path rejects on a collision (a duplicate create still succeeds); the suggestion (S2) and the convergence indicator (S3) consume a read-only lookup. This is stricter local-first behavior than a hard block and matches the issue's "create-anyway remains possible".

This slice (headless core foundation)

  • SchemaField gains optional unique / unique_case_insensitive flags (generic across core + extension types; ~56 constructor sites updated).
  • SqliteStore::find_conflicting_unique — one indexed predicate (constrained by node_type, active-only, on-commit, empty-exempt, per-database scope) backing both the create-time surface and the convergence scan.
  • NodeService::find_duplicate_for — read-only lookup; resolves the flags, returns the existing node; never mutates, never errors on a hit.
  • person.email declared unique + unique_case_insensitive (email is a claim, not identity — identity uniqueness stays uid-keyed in cloud auth_identities).

Security / correctness (adversarial-reviewed)

  • No SQL injection: node_type is normalized to [alnum_] (normalize_schema_id) and field is validated to [alnum_] (validate_schema_field_name) and only used when it exactly matches an existing schema field — so the interpolated json_extract path can't be broken out of (stricter than the existing QueryService pattern).
  • Suggest-don't-block invariant tested: creating_two_persons_with_the_same_email_succeeds proves two same-email persons both persist.
  • 13 tests (6 predicate: exact/case-fold/exclude-self/lifecycle/no-match/type-scope; 7 service). Full core pre-push gate green.

Remaining slices

  • S2 (desktop adopt-existing suggestion UX in person-schema-form.svelte) — needs the desktop app, defers to a machine with it.
  • S3 (sync-apply convergence "possible duplicate" marker) — headless, follows this + a core-pin bump.

…mail)

Slice 1 of the store-aware unique validation work (ADR-065). The node-behavior
validation system had no way to express a cross-node rule like "no duplicate
email" — NodeBehavior::validate is pure and storeless. Rather than making the
trait store-aware (which would infect every behavior and still miss schema-only
extension types), the unique rule is declared on the schema property and
evaluated at the service/store layer.

- SchemaField gains optional `unique` / `unique_case_insensitive` flags
  (generic across core and extension types)
- SqliteStore::find_conflicting_unique — one indexed predicate (constrained by
  node_type, active-only, on-commit) backing both the create-time surface and
  the convergence scan; empty values exempt; per-database scope
- NodeService::find_duplicate_for — read-only lookup that resolves the flags
  and returns the existing node; never mutates, never errors on a hit
- person.email declared unique + case-insensitive (email is a claim, not
  identity — identity uniqueness stays uid-keyed in the cloud)

Suggest-don't-block: no create/update path rejects on a collision (a duplicate
create still succeeds); the suggestion and the convergence indicator consume the
lookup. Desktop suggestion UX and the sync-apply convergence marker are the
remaining slices.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE — Independent + adversarial review CONFIRMED. SQL-injection vector proven closed (node_type via normalize_schema_id, field via validate_schema_field_name + exact-match-to-existing-field gate; single quote isn't Unicode-alphanumeric so no breakout — stricter than the existing QueryService interpolation). Predicate correct (case-fold, exclude-self empty-sentinel safe, active-only, NULL-safe). find_duplicate_for never errors on a hit. 56 constructor sites spot-checked clean, serde additive/wire-compatible, and the suggest-don't-block invariant is proven by test (two same-email persons both persist). Full pre-push gate green.

@mstomar125
mstomar125 merged commit 79740ea into main Jul 31, 2026
2 checks passed
@mstomar125
mstomar125 deleted the wt-1734-unique-validation branch July 31, 2026 07:43
mstomar125 added a commit that referenced this pull request Aug 4, 2026
…1734) (#1969)

The store-aware `unique` rule (#1850) added NodeService::find_duplicate_for, but
nothing could call it — it had no gRPC surface, so a client can't surface the
"a person with this email already exists — adopt existing?" suggestion.

Add a FindDuplicate RPC that wraps find_duplicate_for: it returns the existing
node on a uniqueness-flagged match, or an EMPTY NodeResponse (empty node_id, no
node_data) when there is no duplicate — never NotFound, never an error, matching
the suggest-don't-block contract (ADR-065). "No duplicate" is an ordinary answer.

The desktop suggestion UI (person-schema-form) is the consumer and lands
separately; this is the backend enabler.

Co-authored-by: Claude Opus 4.8 <[email protected]>
mstomar125 added a commit that referenced this pull request Aug 17, 2026
…#2115)

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

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

* Address adversarial review: self-collision false-negative, injection 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]>

---------

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.

1 participant