Skip to content

Add LoadOrStore and LoadAndDelete (atomic insert-if-absent and read-and-consume) - #26

Merged
matthewmcneely merged 13 commits into
matthewmcneely:mainfrom
mlwelles:feature/load-and-delete-load-or-store
Jul 1, 2026
Merged

matthewmcneely merged 13 commits into
matthewmcneely:mainfrom
mlwelles:feature/load-and-delete-load-or-store

Conversation

@mlwelles

@mlwelles mlwelles commented Jun 8, 2026 •

Copy link
Copy Markdown

What this adds

Two atomic, key-keyed operations on modusgraph.Client (and the typed Client[T]), named after their sync.Map counterparts. Both key off an upsert predicate — one you pass, or the first field tagged dgraph:"upsert".

  • LoadOrStore — insert-if-absent. Atomically stores a node keyed by the upsert predicate, or reports that one already exists and hydrates the passed object with it. The building block for claiming a one-time token.
  • LoadAndDelete — atomic read-and-consume. Reads a node and deletes it in one transaction, electing a single winner under concurrency: exactly one caller gets loaded=true with the record, the rest get loaded=false. For consuming a nonce, a pending job, or a single-use code.
// Reject a replayed token: first caller stores, every later caller is rejected.
loaded, err := client.LoadOrStore(ctx, &Token{JTI: jti}, "jti")

// Consume a one-shot value exactly once across concurrent callers.
var t Token
loaded, err = client.LoadAndDelete(ctx, &t, jti, "jti")

Scope

This branch was re-cut onto current main so it carries only the consume operations. It previously bundled the other fork features (#17, #18, #20, #23, #24, #25), but those merge on their own tracks; keeping them here duplicated already-merged work and would have reverted main's Dgraph/Go upgrade and docs. Net change is now the two operations, their tests, and a README section.

Implementation notes

  • LoadOrStore builds on dgman MutateOrGet, which returns created UIDs only — an empty result means an existing node matched.
  • LoadAndDelete shares one no-CommitNow transaction across the read and delete, so concurrent callers conflict on commit; a bounded retry reads the winner's deletion as not-found. A real cluster aborts the loser, so the in-process serialization lock is taken only for the embedded engine (remote consumers on unrelated keys are not serialized).
  • firstUpsertPredicate guards nil/non-struct input and returns "" rather than panicking.

Tests

TestLoadOrStore, TestLoadAndDelete, TestLoadAndDeleteSingleWinner (contention → single winner), and the typed equivalents. Root and typed -short suites pass locally.

Documentation

An Atomic Operations section in the README, plus runnable ExampleClient_LoadOrStore / ExampleClient_LoadAndDelete.

@mlwelles
mlwelles requested a review from matthewmcneely as a code owner June 8, 2026 05:28

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

10 issues found across 31 files

Tip: cubic can generate docs of your entire codebase and keep them up to date. Try it here.

Re-trigger cubic

Comment thread client.go Resolved
Comment thread self_validator_test.go Resolved
Comment thread dial_options_test.go Resolved
Comment thread retry.go Resolved
Comment thread client.go Resolved
Comment thread client.go Resolved
Comment thread typed/query.go Resolved
Comment thread record.go Resolved
Comment thread consume_test.go Resolved
Comment thread retry_test.go Resolved
mlwelles and others added 7 commits June 30, 2026 21:44
Add TestLoadAndDeleteSingleWinner and serialize LoadAndDelete's
read-then-delete critical section with a per-client mutex so exactly one
in-process caller consumes a node. The embedded engine's commit path does no
optimistic-concurrency conflict check, so the shared read-write transaction
alone cannot abort losers; the lock guarantees single-winner semantics
regardless of backend.
…eflection

Addresses review feedback specific to LoadOrStore/LoadAndDelete:

- LoadAndDelete took a process-wide mutex unconditionally, serializing
  consumers across all keys and backends. The mutex is only needed for the
  embedded engine (no commit-time conflict check); a remote Dgraph cluster
  aborts the loser of a commit conflict and the bounded retry already elects
  a single winner. The lock is now taken only for embedded clients
  (c.engine != nil), removing head-of-line blocking for remote consumers.
- firstUpsertPredicate dereferenced reflect.Value without guarding a nil
  pointer or non-struct input, panicking on Type()/NumField(). It now returns
  "" for an invalid or non-struct value.

Tests:
- TestLoadOrStore / TestTypedLoadOrStore now assert the passed object is
  hydrated with the existing record (its UID) on the loaded=true path, so a
  regression returning loaded=true without populating fields is caught.

Docs: add runnable ExampleClient_loadOrStore and ExampleClient_loadAndDelete.

This branch also merges the updated feature branches, bringing in the review
fixes for the typed query builder, retry policy, schema routing, gRPC dial
options, and self-validation.
…casing

Re-cut of the consume operations onto current main. Three adjustments
needed after main moved on from the branch's base:

- Use currentTracer().StartSpan in the typed LoadOrStore/LoadAndDelete
  methods, matching the atomic-holder tracing API main adopted; the bare
  tracer symbol no longer exists.
- Rename ExampleClient_loadOrStore/loadAndDelete to the exported-method
  casing so godoc associates them with Client.LoadOrStore/LoadAndDelete.
- Document both operations in the README (the project's only docs) with
  an Atomic Operations section.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@matthewmcneely
matthewmcneely force-pushed the feature/load-and-delete-load-or-store branch from 5bb1729 to 24ba426 Compare July 1, 2026 01:48
@mlwelles

mlwelles commented Jul 1, 2026

Copy link
Copy Markdown
Author

@cubic-dev-ai review this PR.

Since the last review (run 23bdedcc, against a 31-file integration branch), the diff has been rescoped to just the LoadOrStore/LoadAndDelete feature — 6 files, head 24ba426. The earlier findings from the other feature branches merged upstream separately, so please review the current scoped diff fresh.

@cubic-dev-ai

cubic-dev-ai Bot commented Jul 1, 2026

Copy link
Copy Markdown

@cubic-dev-ai review this PR.

Since the last review (run 23bdedcc, against a 31-file integration branch), the diff has been rescoped to just the LoadOrStore/LoadAndDelete feature — 6 files, head 24ba426. The earlier findings from the other feature branches merged upstream separately, so please review the current scoped diff fresh.

@mlwelles I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread client.go Resolved
LoadAndDelete builds its read filter as "eq("+pred+", $1)". The key value is
parameterized via $1, but the predicate name is concatenated straight into the
DQL, so a name carrying DQL metacharacters (parentheses, commas, whitespace,
quotes, angle brackets) could corrupt or inject the query.

Reject any predicate that is not a plain Dgraph identifier ([A-Za-z0-9_.-])
before it reaches the filter, returning a clear error. Valid predicate names
produce a byte-identical query, so behavior is unchanged for every legitimate
caller. Add TestLoadAndDeleteRejectsInvalidPredicate covering five injection
attempts plus the valid path.

Identified by cubic (review-run 9bee68bc).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@mlwelles

mlwelles commented Jul 1, 2026

Copy link
Copy Markdown
Author

@cubic-dev-ai review this PR.

Latest commit 4dddd8a addresses the predicate-interpolation finding from run 9bee68bc: LoadAndDelete now validates the predicate name against a plain-identifier allowlist before building the eq() filter. Requesting a fresh review of the current head.

@cubic-dev-ai

cubic-dev-ai Bot commented Jul 1, 2026

Copy link
Copy Markdown

@cubic-dev-ai review this PR.

Latest commit 4dddd8a addresses the predicate-interpolation finding from run 9bee68bc: LoadAndDelete now validates the predicate name against a plain-identifier allowlist before building the eq() filter. Requesting a fresh review of the current head.

@mlwelles I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread client.go Resolved
checkPointer used reflect.TypeOf(obj).Kind(), which panics on a nil any because
reflect.TypeOf(nil) is a nil Type. Switch to the nil-safe reflect.ValueOf and
also reject typed nil pointers ((*T)(nil)), which previously passed the
pointer-kind check and then panicked downstream in uidOf's FieldByName. This
closes the same latent panic for Get, checkPointer's other caller.

uidOf now guards an invalid or non-struct Value before FieldByName, matching
firstUpsertPredicate -- defense-in-depth for any future caller.

Add TestLoadAndDeleteRejectsNilObject covering the nil-interface and typed-nil
pointer paths.

Identified by cubic (review-run ad6b15a5).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@mlwelles

mlwelles commented Jul 1, 2026

Copy link
Copy Markdown
Author

@cubic-dev-ai review this PR.

Latest commit 9d0f9c8 addresses the nil-input panic finding from run ad6b15a5 (checkPointer + uidOf now return errors instead of panicking on nil/typed-nil input). Requesting a fresh review of the current head.

@cubic-dev-ai

cubic-dev-ai Bot commented Jul 1, 2026

Copy link
Copy Markdown

@cubic-dev-ai review this PR.

Latest commit 9d0f9c8 addresses the nil-input panic finding from run ad6b15a5 (checkPointer + uidOf now return errors instead of panicking on nil/typed-nil input). Requesting a fresh review of the current head.

@mlwelles I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 6 files

Re-trigger cubic

govet (via Trunk) flags the deprecated reflect.Ptr alias on changed lines.
checkPointer and uidOf were rewritten in this branch, so their reflect.Ptr
uses now sit on changed lines and trip the hold-the-line lint. Switch both to
reflect.Pointer (an identical constant since Go 1.18). No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@mlwelles

mlwelles commented Jul 1, 2026

Copy link
Copy Markdown
Author

@cubic-dev-ai review this PR.

Latest commit d56c53d is a lint-only follow-up to the clean review of 9d0f9c8: it swaps the deprecated reflect.Ptr constant for reflect.Pointer (identical value) to satisfy govet hold-the-line. Requesting a final review of the current head.

@cubic-dev-ai

cubic-dev-ai Bot commented Jul 1, 2026

Copy link
Copy Markdown

@cubic-dev-ai review this PR.

Latest commit d56c53d is a lint-only follow-up to the clean review of 9d0f9c8: it swaps the deprecated reflect.Ptr constant for reflect.Pointer (identical value) to satisfy govet hold-the-line. Requesting a final review of the current head.

@mlwelles I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread client.go Resolved
…nter migration

LoadOrStore validated only via validateStruct, which is a no-op when no
validator is configured, so a nil interface or typed nil pointer could reach
dgman's MutateOrGet and panic or silently fail to hydrate on the loaded=true
path. Call checkPointer first, matching LoadAndDelete and Get. Add
TestLoadOrStoreRejectsNilObject covering both nil forms.

Also replace the remaining deprecated reflect.Ptr uses in client.go
(validateStruct, unwrapSchemaSlice, firstUpsertPredicate) with reflect.Pointer,
so no changed line trips govet's hold-the-line deprecation check. reflect.Ptr
is an identical alias, so there is no behavior change.

Identified by cubic (review-run 4990f7ed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@mlwelles

mlwelles commented Jul 1, 2026

Copy link
Copy Markdown
Author

@cubic-dev-ai review this PR.

Latest commit d05461a adds the checkPointer guard to LoadOrStore (finding from run 4990f7ed) so it rejects nil/typed-nil like LoadAndDelete and Get, and completes the reflect.Ptr -> reflect.Pointer migration in client.go so govet hold-the-line stays green. Requesting a review of the current head.

@cubic-dev-ai

cubic-dev-ai Bot commented Jul 1, 2026

Copy link
Copy Markdown

@cubic-dev-ai review this PR.

Latest commit d05461a adds the checkPointer guard to LoadOrStore (finding from run 4990f7ed) so it rejects nil/typed-nil like LoadAndDelete and Get, and completes the reflect.Ptr -> reflect.Pointer migration in client.go so govet hold-the-line stays green. Requesting a review of the current head.

@mlwelles I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread client.go Resolved
…d contract

LoadAndDelete documents that obj is left zero when it returns loaded=false, but
the retry loop reuses obj across attempts. When the first Get hydrates obj and
the commit then aborts on a race, the retry reads not-found and returned
loaded=false while obj still held stale data from the aborted attempt; a caller
passing a pre-populated struct that matched nothing saw the same. Reset obj via
a new zeroValue helper before both not-found returns that follow a Get.

Add TestLoadAndDeleteZeroesObjectWhenNotFound.

Identified by cubic (review-run 63c40390).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@mlwelles

mlwelles commented Jul 1, 2026

Copy link
Copy Markdown
Author

@cubic-dev-ai review this PR.

Latest commit 5241afe fixes the loaded=false obj-zero contract in LoadAndDelete (finding from run 63c40390). Requesting a review of the current head.

@cubic-dev-ai

cubic-dev-ai Bot commented Jul 1, 2026

Copy link
Copy Markdown

@cubic-dev-ai review this PR.

Latest commit 5241afe fixes the loaded=false obj-zero contract in LoadAndDelete (finding from run 63c40390). Requesting a review of the current head.

@mlwelles I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread client.go Resolved
… its UID

A genuine miss returns via dgman's ErrNodeNotFound, so reaching the uid=="" check
means Get matched and hydrated a node but uidOf found no readable string UID
field (a model contract violation). Returning loaded=false there silently skipped
a matched node -- a consumed token or job would look un-consumed. Return an error
instead. Add TestLoadAndDeleteErrorsWhenUIDUnreadable using a model whose uid
field is named Uid, which dgman hydrates but uidOf's FieldByName("UID") cannot
read.

Identified by cubic (review-run a3227e6d).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@mlwelles

mlwelles commented Jul 1, 2026

Copy link
Copy Markdown
Author

@cubic-dev-ai review this PR.

Latest commit 6f58bb6 fixes the silent-skip finding from run a3227e6d: LoadAndDelete now errors when a matched node has no readable UID. Requesting a review of the current head.

@cubic-dev-ai

cubic-dev-ai Bot commented Jul 1, 2026

Copy link
Copy Markdown

@cubic-dev-ai review this PR.

Latest commit 6f58bb6 fixes the silent-skip finding from run a3227e6d: LoadAndDelete now errors when a matched node has no readable UID. Requesting a review of the current head.

@mlwelles I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 6 files

Re-trigger cubic

@matthewmcneely
matthewmcneely merged commit 05c3246 into matthewmcneely:main Jul 1, 2026
5 checks passed
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.

2 participants