Skip to content

refactor: collapse dedup-drift risks (constantTimeEqual, error catalog, concurrency loops, umbrella exports, Studio shard-key hook) - #273

Merged
prisis merged 7 commits into
alphafrom
advisor/230-tech-debt-dedup
Aug 1, 2026
Merged

prisis merged 7 commits into
alphafrom
advisor/230-tech-debt-dedup

Conversation

@prisis

@prisis prisis commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Five independent dedup/tech-debt fixes, one commit each.

A — runtime constantTimeEqual → the canonical shared/ copy

The runtime carried a private reimplementation (using codePointAt where the canonical uses charCodeAt) with a stale "keep in sync with shard-do.ts" comment — but shard-do already imports from shared/. A security primitive with two definitions is exactly what drifts. Now imports shared/constant-time-equal; the local copy + stale comment are gone. Added a dedup-guard test that greps packages/*/src + shared/ for a redeclared constantTimeEqual (with a documented allowlist for the one remaining out-of-scope payment copy → follow-up).

B — catalog every minted error code (close the fail-open leak)

isInternalCode fails open for any code not in ERROR_CATALOG, so an uncatalogued 500-class code echoes its message to the client with nothing failing. A two-pattern, multi-line-aware grep found 81 uncatalogued codes (the plan's "27" was an example list) — all now registered with correct statuses. 6 flagged internal: true, each audited individually: AUTH_AUDIT_READ_FAILED, CRON_JOB_FAILED, MISCONFIGURED (the named live-leak on the public RPC path), NESTED_TRANSACTION, SQL_UNAVAILABLE, INTERNAL_ERROR — all carry backend detail. The *_NOT_CONFIGURED family, codegen build-time diagnostics, and client-SDK/WS codes stayed non-internal (static, actionable messages — not over-flagged). Added a repo-level registration test that fails on any future uncatalogued code.

C — one bounded-concurrency helper

Five hand-rolled bounded-fan-out loops in query-coordinator.ts (with already-divergent guards) collapsed into runBoundedJobs<T,R>(jobs, concurrency, run); runBoundedFanOut and the cdcSync/import/applyCdc/rankPage orchestrators call it, unified on the early-return-when-empty guard. The query-coordinator.*.test.ts suite pins the semantics.

D — complete + data-drive the umbrella exports

lunorash was missing server/otel and client/upload, so a one-install app couldn't reach two shipped features. Added both re-exports + export-map entries, and rewrote the parity test to read each upstream package's own exports map and assert a lunorash/* mapping for every subpath — with an explicit opt-out list (@lunora/platform's ./conformance*) and an alias table (flags/providers/*→flags/*). It now fails on the next upstream subpath drift instead of needing a hand-maintained array.

E — useShardKey hook (12 duplicated preambles → 1)

The shard-key + 400ms-debounce preamble was copy-pasted in 12 panels. Extracted useShardKey(initial, delayMs) → { shardKey, setShardKey, queryShardKey } with the debounce + synchronous reset semantics. It uses its own setTimeout debounce rather than composing the shared useDebounced — composing let a stale pending debounce clobber a synchronous reset (caught by a regression test), and keeping the diff out of use-debounced.ts means zero overlap with #264's edit to that file.

Verification

runtime 791, errors 528, lunorash 117, studio 967 (hook: 7 tests incl. synchronous-reset + stale-timer). All lint:types/lint:eslint/lint:package-json green; full build:packages (53 projects) passes.

Merge-order notes (all individually mergeable vs alpha)

Plan: plans/230-*.md.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added broader, clearer error coverage with appropriate status and diagnostic handling.
    • Exposed server telemetry and client upload capabilities through the main package.
    • Added consistent shard-key selection and settling across Studio data, logs, reports, migrations, schema, traces, and issue views.
  • Improvements

    • Improved reliability and consistency when running concurrent data operations.
    • Standardized shard-scoped queries and actions to reduce inconsistent results while users edit shard keys.

prisis added 5 commits August 1, 2026 04:31
The runtime carried a private constantTimeEqual reimplementation whose
"keep in sync with shard-do.ts" comment was already stale (shard-do
imports the canonical shared/constant-time-equal.ts). A security
primitive like this must have exactly one definition, so drop the
local copy (which also diverged on codePointAt vs. the canonical
charCodeAt) and import the shared helper instead.

Add a dedup-guard test that greps packages/*/src and shared/ for a
redeclared constantTimeEqual, with a documented allowlist for the
pre-existing payment/src/webhook.ts copy (tracked separately).
isInternalCode fails OPEN for any code not in ERROR_CATALOG, so a code
minted outside the catalog echoes its message to the client
unredacted with no test failing. An audit found 81 codes thrown
across the repo (via `code: "X"` or `new LunoraError("X"`) that were
never registered.

Register all of them with a status/title, and flag `internal: true`
on the handful whose message can carry backend/deployment detail
(MISCONFIGURED, CRON_JOB_FAILED, AUTH_AUDIT_READ_FAILED, the
SQLite-in-DO "should never happen" invariants, and the two generic
500 catch-alls) — audited individually so a merely-actionable
"you forgot to configure X" message stays client-visible rather than
getting redacted by default.

Add a repo-level test that greps packages/*/src for both minting
shapes and fails if a future code ships without a catalog entry.
query-coordinator.ts hand-rolled the same shared-cursor worker-pool
loop five times (runBoundedFanOut plus four orchestrators), with
slightly divergent empty-input guards between them.

Extract runBoundedJobs<T, R>(jobs, concurrency, run), unify on the
early-return-when-empty guard, and express runBoundedFanOut and the
cdcSync/import/applyCdc/rankPage orchestrators as calls into it.
… test

The umbrella's exports map is hand-listed and had drifted: @lunora/server's
./otel and @lunora/client's ./upload had no lunorash/* counterpart, and
the old re-exports.test.ts was a hand-maintained array that couldn't
catch the next drift the same way.

Add the two missing one-line re-export subpaths, and rewrite the test
to read each upstream package's own exports map and assert every
subpath (bar an explicit, reasoned opt-out list — @lunora/platform's
./conformance TCK, the flags/providers/* flattening) has a lunorash/*
mapping.
The shard-key input + 400ms-debounce preamble
(useState + useDebounced(shardKey.trim(), 400)) was copy-pasted across
12 Studio panels.

Extract useShardKey(initial, delayMs) returning
{ shardKey, setShardKey, queryShardKey } into packages/studio/src/hooks/,
and migrate all 12 call sites. Beyond dedup, the hook makes a shard
reset driven by the caller's `initial` value (a table/tab switch)
resolve synchronously — queryShardKey snaps to the new shard
immediately instead of leaving a query/subscription pointed at the
previous shard for up to 400ms while the debounce catches up. Comes
with its own debounce implementation (not composing the shared
useDebounced) so the reset can't race a stale pending timer from
before it.
@netlify

netlify Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

Name Link
🔨 Latest commit 0011cc2
🔍 Latest deploy log https://app.netlify.com/projects/lunorash/deploys/6a6dcb27086b8300084a8a4e
😎 Deploy Preview https://deploy-preview-273--lunorash.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@prisis, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 3 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a06d27c4-6b2f-48d1-8c71-e1ac225df75e

📥 Commits

Reviewing files that changed from the base of the PR and between 5f91717 and 0011cc2.

⛔ Files ignored due to path filters (1)
  • packages/studio/__tests__/hooks/use-shard-key.test.tsx is excluded by !**/__tests__/** and included by packages/**
📒 Files selected for processing (1)
  • packages/studio/src/features/schema/hooks/use-schema-explorer.tsx

Walkthrough

The PR expands the error catalog and Lunora package exports, centralizes runtime helpers and bounded concurrency, and replaces duplicated Studio shard-key debouncing with the shared useShardKey hook.

Changes

Error and package API surface

Layer / File(s) Summary
Expanded error catalog
packages/errors/src/catalog.ts
Adds error codes for admin, audit, cron, runtime, Durable Object, relay, worker, Nuxt, replica, client, and offline-outbox operations.
Package subpath exports
packages/lunora/package.json, packages/lunora/src/client/upload.ts, packages/lunora/src/server/otel.ts
Exports the ./client/upload and ./server/otel modules with ESM and declaration targets.

Runtime execution changes

Layer / File(s) Summary
Shared comparison helper
packages/runtime/src/create-worker.ts
Uses the shared constantTimeEqual helper for token and signature comparisons.
Bounded job orchestration
packages/runtime/src/query-coordinator.ts
Adds a reusable bounded worker pool for fan-out, CDC synchronization, imports, CDC replay, and ranked-page requests.

Studio shard-key state

Layer / File(s) Summary
Reusable shard-key hook
packages/studio/src/hooks/use-shard-key.ts
Adds useShardKey, which exposes live and settled shard keys, trims query values, debounces updates, resets on initial-key changes, and clears timers.
Data browser shard routing
packages/studio/src/features/data/hooks/use-data-browser.tsx
Uses the settled query shard key for reads, facets, view mirroring, history, writes, and deletes.
Studio panel adoption
packages/studio/src/features/advisors/insights-panel.tsx, packages/studio/src/features/database/migrations.tsx, packages/studio/src/features/functions/function-stats.tsx, packages/studio/src/features/issues/issues-panel.tsx, packages/studio/src/features/logs/*, packages/studio/src/features/reports/*, packages/studio/src/features/schema/hooks/use-schema-explorer.tsx, packages/studio/src/features/traces/traces-panel.tsx
Updates shard-scoped queries and effects to use queryShardKey from the shared hook.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • anolilab/lunora#44: Both changes refactor shard-key and query handling across shared Studio panels.
  • anolilab/lunora#118: Both changes modify the shared error catalog and its redaction metadata.
  • anolilab/lunora#90: Both changes modify runtime worker authorization and security behavior in create-worker.ts.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the five refactoring areas covered by the pull request.
Description check ✅ Passed The description provides a detailed summary, test results, merge-order notes, and implementation rationale, but omits several template sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch advisor/230-tech-debt-dedup

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Thank you for confirming the Contributor License Agreement! 🙏

@github-actions

github-actions Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@github-actions

github-actions Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

React Doctor found no new issues. 🎉

Reviewed by React Doctor for commit 0011cc2.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/studio/src/features/schema/hooks/use-schema-explorer.tsx`:
- Line 72: Use queryShardKey consistently for schema reads and cache keys in the
schema explorer: update toggle, the graph probe, diagram cache lookups, and the
table-list loading flow around useShardKey to use the settled key. Keep shardKey
exclusively as the live input value so all displayed schema data corresponds to
the same debounced shard.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3fef37a2-a67e-4af2-9135-297d564f794e

📥 Commits

Reviewing files that changed from the base of the PR and between 36421ad and 5f91717.

⛔ Files ignored due to path filters (4)
  • packages/errors/__tests__/catalog-registration.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/lunora/__tests__/re-exports.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/runtime/__tests__/constant-time-equal-dedup.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/studio/__tests__/hooks/use-shard-key.test.tsx is excluded by !**/__tests__/** and included by packages/**
📒 Files selected for processing (19)
  • packages/errors/src/catalog.ts
  • packages/lunora/package.json
  • packages/lunora/src/client/upload.ts
  • packages/lunora/src/server/otel.ts
  • packages/runtime/src/create-worker.ts
  • packages/runtime/src/query-coordinator.ts
  • packages/studio/src/features/advisors/insights-panel.tsx
  • packages/studio/src/features/data/hooks/use-data-browser.tsx
  • packages/studio/src/features/database/migrations.tsx
  • packages/studio/src/features/functions/function-stats.tsx
  • packages/studio/src/features/issues/issues-panel.tsx
  • packages/studio/src/features/logs/audit-panel.tsx
  • packages/studio/src/features/logs/logs-panel.tsx
  • packages/studio/src/features/logs/subscriptions-panel.tsx
  • packages/studio/src/features/reports/fanout-panel.tsx
  • packages/studio/src/features/reports/metrics-panel.tsx
  • packages/studio/src/features/schema/hooks/use-schema-explorer.tsx
  • packages/studio/src/features/traces/traces-panel.tsx
  • packages/studio/src/hooks/use-shard-key.ts

@codspeed

codspeed Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 0.06%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
❌ 1 regressed benchmark
✅ 232 untouched benchmarks
⏩ 27 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ flat 3 primitives (the notify.send attribute shape) 55.7 µs 62 µs -10.2%
⚡ count, no attributes 64.2 µs 57.7 µs +11.23%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing advisor/230-tech-debt-dedup (0011cc2) with alpha (a540991)2

Open in CodSpeed

Footnotes

  1. 27 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on alpha (d9791ea) during the generation of this report, so a540991 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

prisis added 2 commits August 1, 2026 12:31
Move the onReady(setShardKey) call in the useShardKey test harness out
of render and into an effect. Render must stay pure — React can replay
or discard it — so a prop callback invoked during render can fire more
than once or for a commit that never lands.
toggle, the graph column probe, and the diagram's cached columns read
the live (per-keystroke) shardKey while the table list already loads
on the debounced queryShardKey. During the debounce window this let an
operator expand a table, or open the graph, against the shard they're
still typing rather than the one the displayed tables came from. Key
all of them on queryShardKey; shardKey stays only the input's live
value.
@prisis
prisis merged commit 3e7f64a into alpha Aug 1, 2026
43 of 46 checks passed
@prisis
prisis deleted the advisor/230-tech-debt-dedup branch August 1, 2026 10:56
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using our GitHub Discussions tab for questions.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Sep 8, 2026

This branch was previously deployed

1 inactive deployment
benchmarks — 0011cc29 Deployed Aug 1, 2026 by prisis via Benchmarks #1329
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant