SIGN IN SIGN UP

perf(sync): remove duplicate peer lookup and the scope-listing N+1 (#1580)

## Description

Follow-up to #1564 and #1565, which fixed `rows_read`. This one targets request volume, which is what `rows_written` is made of: every authenticated coordinator request writes two rows to `request_nonces` — one INSERT on the way in, one DELETE when it expires 600s later — so a redundant request costs writes no matter how little it reads.

Both changes are worth making on their own terms; neither is only a quota play.

**1. Duplicate `/v1/peers` per daemon tick.** `refreshCoordinatorPresenceForDaemon` called `refreshAuthorizedCoordinatorPeerTrust`, which fetches peers and stores their addresses — then discarded the peers it returned. Ten lines later `fetchCoordinatorStalePeers` re-read the config file, fetched the same `/v1/peers`, and repeated the same `refreshStoredCoordinatorPeerAddresses` write. Two identical round trips seconds apart, with the same side effect applied twice.

`refreshCoordinatorForDaemon` now returns the snapshot and the tick passes it through, so one tick makes one lookup. `fetchCoordinatorStalePeers` keeps its fetching path for callers without a snapshot — including the tick itself when the coordinator refresh threw, so a failed refresh still degrades to the old behaviour rather than silently skipping the preflight. The stale-set derivation moved into the exported `coordinatorStalePeerKeys` so both paths share one implementation. `refreshCoordinatorPresenceForDaemon` remains as a boolean-returning wrapper.

The snapshot is now taken before the `onAfterCoordinatorRefresh` callback rather than after it. For a best-effort offline preflight a few-seconds-old view is well inside tolerance.

**2. `GET /v1/scopes` N+1.** `requesterAuthorizedForScope` ran `listScopeMemberships(scope_id)` once per scope — reading every member of every scope to answer a question about one device. The endpoint now makes a single `listDeviceScopeMemberships` call, served by the already-present `idx_coordinator_scope_memberships_device_status` index, and matches scopes against that map. `(scope_id, device_id)` is the primary key so the mapping is 1:1, and the `membership_epoch >= scope.membership_epoch` check is unchanged. The helper had no other caller — `/v1/scopes/:scope_id/members` does its own check over memberships it already needs — so it is removed rather than left dead.

`listDeviceScopeMemberships` is added to the store contract and implemented in both the D1 and better-sqlite stores.

## Type of Change

- [ ] 🚀 Feature (new functionality)
- [x] 🐛 Bug fix (fixes an issue)
- [ ] 📚 Documentation (docs-only change)
- [ ] 🔧 Maintenance (refactor, chore, CI, etc.)
- [ ] 🧪 Testing (test-only changes)

## Testing

- [x] Relevant checks pass locally (`pnpm run tsc`, `pnpm run lint`, `pnpm run test`)
- [x] Added/updated tests for changes
- [ ] Manually verified changes work as expected

`pnpm run tsc` and `pnpm run lint` clean. `pnpm run test` reports 5,736 passed — five more than before this change — with one unrelated environmental failure (`packages/mcp-server/src/http.test.ts` cannot bind `::1` in this container; it passes in CI). `pnpm --filter @codemem/cloudflare-coordinator-worker test:worker` passes, 6 tests.

New coverage:
- Shared store harness: one device's memberships across several scopes, isolation from other devices' grants, `includeRevoked` behaviour, and the empty-`deviceId` guard. Confirmed running against **both** store implementations.
- `fetchCoordinatorStalePeers` derives the same stale set from a supplied snapshot, with `globalThis.fetch` stubbed to throw so a second lookup would fail the test.
- `refreshCoordinatorForDaemon` returns the peer snapshot with exactly one `refreshAuthorizedCoordinatorPeerTrust` call, and reports `peers: null` when the coordinator is unconfigured.

## Checklist

- [x] Code follows project style (`pnpm run lint` passes for touched files)
- [x] Self-review completed
- [x] Documentation updated (if needed)
- [x] No new warnings introduced

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Lq71RnJbURWvF9fmkKuDRc

---
_Generated by [Claude Code](https://claude.ai/code/session_01Lq71RnJbURWvF9fmkKuDRc)_
A
Adam Kunicki committed
d8e7f4fb68239b8eddef78a19963a7045f4a28c2
Parent: 87932ca
Committed by GitHub <noreply@github.com> on 9/2/2026, 6:48:30 PM