Skip to content

fix(coordinator): snapshot AttestationResult on store (fix -race data race) - #336

Merged
Gajesh2007 merged 3 commits into
masterfrom
fix/provider-attestation-result-race
Jun 14, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
fix/provider-attestation-result-race

Conversation

@anupsv

@anupsv anupsv commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes a data race (caught intermittently by the -race detector in coordinator/api, e.g. TestProviderRegistrationRejectsInvalidConfiguredBinaryHash) between registry.persistProviderNow's async marshal and the provider-registration path.

Root cause

persistProviderNow spawns a detached goroutine that json.Marshals p.AttestationResult under p.mu. The registration path (coordinator/api/provider.go) builds a single local result (*attestation.VerificationResult), mutates its fields across several validation checks (result.Valid, result.Error, …), and hands the pointer to the registry via SetAttestationResult(&result). Storing the caller's pointer made p.AttestationResult alias that still-mutable struct, so the unsynchronized field writes raced the async marshal.

It's nondeterministic because the persist goroutine outlives the test that spawned it and only collides with another test's registration under the wrong interleaving — so the test passes in isolation but trips occasionally on a full-package -race run.

This is pre-existing on master (both persistProviderNow and the pointer-storing SetAttestationResult are unchanged there); it is not specific to any feature branch.

Fix

SetAttestationResult now stores a shallow copy under p.mu:

snapshot := *result
p.AttestationResult = &snapshot

attestation.VerificationResult is all value-typed fields (bools / strings / time.Time), so the copy is a complete, immutable, Provider-owned snapshot — the caller can keep mutating its local result without ever touching what the registry marshals. nil is preserved.

Test plan

go test -race ./coordinator/registry/ and ./coordinator/api/ — pass. New regression tests in coordinator/registry/attestation_result_race_test.go:

  • TestSetAttestationResultSnapshotsCallerStruct — deterministic: mutating the caller's struct after SetAttestationResult must not change the stored value.
  • TestSetAttestationResultNoRaceWithConcurrentMarshal — a marshal loop concurrent with caller mutate-then-restore, clean under -race.
  • TestSetAttestationResultNilClears — nil clears the stored result.

Verified the tests fail without the fix: reverting SetAttestationResult to the pointer-store makes the snapshot test fail deterministically (stored result was not snapshotted: Valid=false Error="mutated") and the concurrency test report DATA RACE. The originally-flaky TestProviderRegistrationRejectsInvalidConfiguredBinaryHash ran 15× clean under -race with the fix.

Context

Surfaced as a flaky CI failure on an unrelated PR (#335). Fixed here on master so all branches inherit it.

Follow-up (not in this PR)

Review flagged a separate, pre-existing low-severity item, untouched by this change: cmd/coordinator/main.go:352,360 reads p.AttestationResult without p.mu in the SetOnMDA callback (the sibling SetOnLateSecurityInfo callback locks correctly). This snapshot fix reduces its danger — the stored struct is now immutable — but the pointer read should go through GetAttestationResult(). Worth a small standalone fix.


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

…ta race

persistProviderNow asynchronously json.Marshal(p.AttestationResult) under p.mu,
while the provider-registration path mutates a single local result struct
(Valid/Error/...) across several validation checks and hands its pointer to the
registry via SetAttestationResult. Storing the caller's pointer aliased that
mutable struct, so the unsynchronized field writes raced the async marshal —
caught intermittently by the -race detector in coordinator/api
(TestProviderRegistrationRejectsInvalidConfiguredBinaryHash and others; the
async persist goroutine outlives the test that spawned it).

SetAttestationResult now stores a shallow copy. VerificationResult is all
value-typed fields, so the copy is a complete, immutable, Provider-owned
snapshot; the caller can keep mutating its local result without touching it.

Regression: a deterministic snapshot test (mutation after store doesn't leak)
plus a -race test (concurrent marshal vs caller mutate+restore).
@vercel

vercel Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 14, 2026 6:45pm
d-inference-console-ui-dev Ready Ready Preview Jun 14, 2026 6:45pm
d-inference-landing Ready Ready Preview Jun 14, 2026 6:45pm

Request Review

ethenotethan

This comment was marked as outdated.

@github-actions

github-actions Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

This PR fixes a data race in SetAttestationResult that, under concurrent registration and persistence, could have allowed unsynchronised writes to an attestation.VerificationResult struct that is also read during marshal — a correctness fix with a minor positive security posture effect on T-034.


Trust boundaries touched

  • TB-002 — Coordinator ↔ Provider WebSocket (attestation result lifecycle)
  • TB-009 — Apple attestation chain (cross-cutting; AttestationResult feeds trust-level decisions)

Threat analysis

T-034 — Provider runs modified code while advertising a trusted identity ✅ Strengthens mitigation (marginally)

The race being fixed is between:

  1. The registration path in coordinator/api/provider.go, which mutates the same *attestation.VerificationResult local across multiple validation steps (Valid, Error, field writes), and
  2. persistProviderNow asynchronously json.Marshal-ing p.AttestationResult under p.mu.

Before this change, p.AttestationResult = result stored the caller's live pointer. Any field written to result after SetAttestationResult returned (but before the caller finished its validation pipeline) would race the background marshal. Under -race this is a detectable data race; in production it is a silent torn read. A torn VerificationResult during serialisation could produce a persisted attestation snapshot that doesn't accurately reflect the validated state — e.g. Valid=true persisted while error fields are mid-write.

The fix — snapshot := *result before storing — makes p.AttestationResult an immutable, fully-owned copy. All of VerificationResult's fields are value-typed (per the comment), so the shallow copy is complete. The defer p.mu.Unlock() is a welcome cleanup that prevents a missed unlock if a future code path adds an early return.

This does not change the logic of attestation verification or the CodeAttested gate, so it doesn't directly affect whether a modified binary passes. It does ensure the stored attestation snapshot faithfully represents what was verified, removing a window where a race could produce an inconsistent persisted state that might be audited or re-evaluated later.


New attack surface introduced

None. This change narrows behaviour (removes aliasing); it introduces no new API surface, no new goroutines, and no new trust decisions.


Open findings resolved

None explicitly. The PR doesn't reference any SEC-* finding, and no existing finding directly describes this race. The related test file coordinator/registry/attestation_result_race_test.go (not shown in diff) presumably exercises this path under -race; its presence is positive signal that this fix is regression-tested.


Minor notes for the reviewer

  • VerificationResult all-value-typed assumption (registry.go comment line +18): this invariant should be enforced structurally. If a future field adds a pointer, slice, or map to attestation.VerificationResult, the shallow copy becomes incomplete and the race silently returns. Consider adding a compile-time size/reflect check, or a comment in attestation/verification_result.go marking the type as "must remain value-typed for copy safety."
  • The nil guard at line +13 is correct and necessary; previously a nil pointer could have been stored and later dereferenced under p.mu by a reader expecting a non-nil result.

🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@Gajesh2007

Copy link
Copy Markdown
Member

@codex review this

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 51dc62311a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 1 finding(s) (1 blocking)

  • 🟡 [MEDIUM] coordinator/registry/attestation_result_race_test.go:60-65 — Redundant json.Marshal calls in tight loop without using result
    • Suggestion: Consider reducing iteration count or adding minimal work between marshals to better simulate real usage patterns

Type_diligence — ✅ No issues found

Additive_complexity — ✅ No issues found

1 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +60 to +65
defer wg.Done()
for i := 0; i < 5000; i++ {
if got := p.GetAttestationResult(); got != nil {
_, _ = json.Marshal(got)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Redundant json.Marshal calls in tight loop without using result

💡 Suggestion: Consider reducing iteration count or adding minimal work between marshals to better simulate real usage patterns

📊 Score: 2×4 = 8 · Category: Repeated work

@Gajesh2007
Gajesh2007 merged commit fc43cd4 into master Jun 14, 2026
14 of 16 checks passed

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 1 finding(s) (1 blocking)

  • 🟡 [MEDIUM] coordinator/registry/attestation_result_race_test.go:60-65 — Redundant json.Marshal calls in tight loop without using result
    • Suggestion: Consider reducing iteration count or adding small delay between marshals to avoid unnecessary CPU usage in test

Type_diligence — ✅ No issues found

Additive_complexity — 1 finding(s)

  • 🔵 [INFO] coordinator/registry/attestation_result_race_test.go:51-75 — Race test uses arbitrary high iteration count (5000) without justification
    • Suggestion: Use a smaller iteration count (100-500) or make it configurable via build tags for CI vs local testing

2 finding(s) total, 1 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +60 to +65
defer wg.Done()
for i := 0; i < 5000; i++ {
if got := p.GetAttestationResult(); got != nil {
_, _ = json.Marshal(got)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Redundant json.Marshal calls in tight loop without using result

💡 Suggestion: Consider reducing iteration count or adding small delay between marshals to avoid unnecessary CPU usage in test

📊 Score: 2×4 = 8 · Category: Repeated work

Comment on lines +51 to +75
// races on the shared struct's fields without it.
func TestSetAttestationResultNoRaceWithConcurrentMarshal(t *testing.T) {
p := &Provider{}
r := &attestation.VerificationResult{Valid: true, Error: "orig"}
p.SetAttestationResult(r)

var wg sync.WaitGroup
wg.Add(2)
go func() { // reader: persistProviderNow-style marshal of the stored snapshot
defer wg.Done()
for i := 0; i < 5000; i++ {
if got := p.GetAttestationResult(); got != nil {
_, _ = json.Marshal(got)
}
}
}()
go func() { // writer: registration-style mutate-then-restore of the local result
defer wg.Done()
for i := 0; i < 5000; i++ {
r.Valid = !r.Valid
r.Error = "x"
p.SetAttestationResult(r)
}
}()
wg.Wait()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Race test uses arbitrary high iteration count (5000) without justification

💡 Suggestion: Use a smaller iteration count (100-500) or make it configurable via build tags for CI vs local testing

📊 Score: 2×3 = 6 · Category: over-configuration

jonathan308 added a commit that referenced this pull request Oct 22, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 pushed a commit that referenced this pull request Oct 22, 2026
…ed width (#1555)

* perf(flint): pin SDK speedups, chain constrained decode, serve at paged width

Pins mlx-swift-lm claude/flint-perf (0349802): larger decode command
buffers, fewer paged decode dispatches and host uploads, a fused MoE FP32
expert combine, batched sliding-window prefill attention, final-layer
KV-only evaluation chunks, and constrained decode chaining with cached
device masks. Every SDK change is byte-identical to the previous path.

FlintNativeProtocolConstraint and FlintAnswerStopConstraint opt into
chained decode and key their cached masks by constraint state, since the
allowed set depends only on the state while output budget remains.
RecursiveSI/flint-int4 joins the automatic paged list, so it serves at
the legacy paged width (8) on M5 Pro, Max and Ultra.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(flint): pin mlx-swift-lm 758c25bc (fork.yaml and formatting only)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(flint): pin mlx-swift-lm cbaf4cc9 (zero-filled decode merge scratch)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(flint): pin merged mlx-swift-lm main 993f7060 (#336)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007 pushed a commit that referenced this pull request Oct 22, 2026
* perf(flint): pin SDK speedups, chain constrained decode, serve at paged width

Pins mlx-swift-lm claude/flint-perf (0349802): larger decode command
buffers, fewer paged decode dispatches and host uploads, a fused MoE FP32
expert combine, batched sliding-window prefill attention, final-layer
KV-only evaluation chunks, and constrained decode chaining with cached
device masks. Every SDK change is byte-identical to the previous path.

FlintNativeProtocolConstraint and FlintAnswerStopConstraint opt into
chained decode and key their cached masks by constraint state, since the
allowed set depends only on the state while output budget remains.
RecursiveSI/flint-int4 joins the automatic paged list, so it serves at
the legacy paged width (8) on M5 Pro, Max and Ultra.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(flint): pin mlx-swift-lm 758c25bc (fork.yaml and formatting only)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(flint): pin mlx-swift-lm cbaf4cc9 (zero-filled decode merge scratch)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(flint): pin exact decode fusions (mlx-swift-lm 3676bff1)

Fused q/k/v and gate/up projections, fused routed gate/up banks, one MoE
combine-and-residual kernel and compiled router steps: the batch-1 decode
graph drops from 2,042 to 1,233 GPU primitives per token with
byte-identical logits, K/V and tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(flint): describe the decode fusions; pin mlx-swift-lm 9b7f5b07

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(flint): pin merged mlx-swift-lm main 993f7060 (#336)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — a40bb364 Deployed Jun 14, 2026 by vercel[bot]
Preview – d-inference — a40bb364 Deployed Jun 14, 2026 by vercel[bot]
Preview – d-inference-landing — a40bb364 Deployed Jun 14, 2026 by vercel[bot]
benchmarks — a40bb364 Deployed Jun 14, 2026 by Gajesh2007 via E2E Benchmarks #864
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.

3 participants