Skip to content

fix(codegen): keep shorthand table columns - #350

Closed
prisis wants to merge 4 commits into
alphafrom
fix/shard-error-identity
Closed

prisis wants to merge 4 commits into
alphafrom
fix/shard-error-identity

Conversation

@prisis

@prisis prisis commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Behavior-preserving pass over all 55 packages: dead private code removed,
copy-paste factored into shared helpers, single-use wrappers inlined, and
hand-rolled utilities replaced with stdlib equivalents. Net −6,088 source
lines with no test-file changes and the public API surface unchanged
(api:check green; the one snapshot diff is a cosmetic type-name rendering).

Also removes a stray duplicate loop in @lunora/config's wrangler→Alchemy
conversion that emitted every var binding twice into the generated program.

Co-Authored-By: Claude Opus 5 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_019WfuWNN3cWJE6beZjng347<!--
Thank you for contributing to Lunora!

Please fill out the sections below so reviewers can land your change quickly.
Keep the title in conventional-commit form (e.g. feat(cli): add migrate flag).
-->

Summary

Linked issues

Test plan

Checklist

  • Commit messages follow the Conventional Commits style (feat(scope): subject)
  • Added or updated tests covering the change
  • Updated relevant docs in apps/docs (or README.md for package-local docs)
  • No package.json files in packages/* modified outside the touched package
  • If a new package was added: project.json has type:package and a category:* tag
  • If migration impact: noted upgrade steps in the PR description and changelog entry

Notes for reviewers

Contributor License Agreement

By submitting this pull request, I confirm that my contribution is made under the terms of the project's license and that you can use, modify, copy, and redistribute this contribution under those terms.
defineTable({ status }) — a shorthand property whose value is a validator
held in a const — was dropped from the table shape entirely. parseObjectShape
skipped anything that was not a PropertyAssignment, and a shorthand property
is its own initializer, so the column vanished from Doc_* with no error
anywhere.

The failure is silent and arrives late: an index over the missing column
surfaces only as a confusing index_references_unknown_field advisory pointing
at a column the author can plainly see in the schema, and a column with no index
produces no diagnostic at all — just a runtime insert that writes a field the
generated types say does not exist. object-shorthand autofixes
status: status into this form, so the loss can arrive from a lint run on a
schema that was previously correct.

Every caller of the parser was affected: table shapes, .input() args, http
routes and mutators all read their shape through it.

Co-Authored-By: Claude Opus 5 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_01CYvgKochPxnrCCtKB1tXGf

Summary by CodeRabbit

  • Bug Fixes

    • Preserved the original errors thrown during serialized operations and transactions, including custom error properties.
    • Ensured the host remains usable after an operation fails.
    • Improved handling of platform failures when multiple errors occur.
    • Added support for shorthand object properties in validator parsing.
    • Improved detection of locally declared types during API generation.
  • Documentation

    • Clarified error-handling behavior for serialized operations and transactions.

prisis and others added 4 commits August 2, 2026 18:55
`defineTable({ status })` — a shorthand property whose value is a validator
held in a const — was dropped from the table shape entirely. `parseObjectShape`
skipped anything that was not a `PropertyAssignment`, and a shorthand property
is its own initializer, so the column vanished from `Doc_*` with no error
anywhere.

The failure is silent and arrives late: an index over the missing column
surfaces only as a confusing `index_references_unknown_field` advisory pointing
at a column the author can plainly see in the schema, and a column with no index
produces no diagnostic at all — just a runtime insert that writes a field the
generated types say does not exist. `object-shorthand` autofixes
`status: status` into this form, so the loss can arrive from a lint run on a
schema that was previously correct.

Every caller of the parser was affected: table shapes, `.input()` args, http
routes and mutators all read their shape through it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CYvgKochPxnrCCtKB1tXGf
A handler annotated with a type it exports from its own module emitted that
bare name into `_generated/api.ts`, which never imports the handler's module —
so the generated file did not compile (TS2304) while `lunora codegen` exited 0.

`symbolDeclaredUnreachable` treated an exported declaration as reachable, on the
assumption that an exported name can be imported. Nothing emits that import: the
emitter only rewrites qualifiers the type checker itself rendered as
`import("…")`, and the checker prints an exported local type by bare name
precisely because it is nameable from the handler.

A non-exported declaration was already expanded structurally. Exported ones now
take the same path, so the emitted type is identical in shape and resolves from
anywhere. The existing test asserted the old behaviour on the stated grounds
that "the name is valid"; it encoded the defect, and is rewritten.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CYvgKochPxnrCCtKB1tXGf
Every `LunoraError` a mutation handler threw reached the client as a generic
500 `INTERNAL` / "Internal error". A `NOT_FOUND`, a `CONFLICT` on a unique
index, an `UNAUTHENTICATED` guard — all indistinguishable, all logged as
internal faults, and all unbranchable by the client. Queries were unaffected
because they never enter a transaction, which made the behaviour look arbitrary.

Two boundaries in the mutation path lose the error:

1. `blockConcurrencyWhile` (the single-writer gate) treats a rejecting closure
   as unrecoverable and ABORTS the Durable Object. That is the right default for
   the initialization work the API was designed for, and the wrong one for a
   gate wrapping every mutation: an ordinary application error tore down the
   shard, discarding its in-memory state and every hibernating WebSocket
   subscription on it, for every other client connected to that shard.
2. `storage.transaction` rolls back correctly but propagates a flattened copy —
   a plain `Error` carrying `name: message` and none of the original's own
   properties. `isLunoraError` is structural (`type`/`code`/`status`), so the
   copy fails that check and is redacted.

Both now settle the closure's outcome inside the boundary and re-raise the
original instance outside it. Semantics are otherwise unchanged: the gate is
still held for the whole closure, and the transaction closure still throws into
the platform so the rollback happens exactly as before. A failure raised by the
platform itself, with no handler error to restore, is surfaced untouched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CYvgKochPxnrCCtKB1tXGf
Review follow-ups on the shard-boundary fix.

The property the previous commit restored was pinned only by unit doubles that
implement the very workerd behaviour being claimed — they cannot fail if the
platform differs, and they asserted nothing for any other host. `ShardHost` also
said nothing about what happens to a thrown error, so a new
`platform-<target>` could regress it and stay green.

The contract now states it on both `runSerialized` and `transaction`, and the
conformance suite asserts it: a sentinel carrying `code`/`status` must come back
by identity, and the host must still serve the next caller afterwards. Verified
under real workerd via `@lunora/do`'s `runInDurableObject` project — the case
fails against the unfixed adapter and passes against the fixed one, which is the
assurance the doubles could not give. The in-memory reference host and the node
host both already satisfy it.

Also from review:

- Drop the explicit type argument on `blockConcurrencyWhile`, which was
  discarding the closure's return type and forcing an `as never` to recover it.
  `as const` on the discriminant lets it infer.
- Attach a failed commit/rollback as `cause` when the handler's error takes
  precedence, so a broken storage layer cannot vanish behind an application
  error.
- Rename `symbolDeclaredUnreachable` to `declaredInHandlerModule`. After the
  previous commit the predicate returns true for exported declarations, which
  are reachable — the name had become wrong and its docblock existed mostly to
  say so.
- Cut the duplicated incident narrative from the comments, keeping the
  platform behaviour that cannot be derived from the code and dropping the
  past-tense bug story.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CYvgKochPxnrCCtKB1tXGf
@netlify

netlify Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

Name Link
🔨 Latest commit f8bd461
🔍 Latest deploy log https://app.netlify.com/projects/lunorash/deploys/6a72db3721682000081d5130
😎 Deploy Preview https://deploy-preview-350--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.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

Walkthrough

The PR updates codegen handling for local types and shorthand validators. It also changes Cloudflare host error propagation, adds conformance coverage for exact error identity, and documents the updated ShardHost contract.

Changes

Codegen resolution

Layer / File(s) Summary
Handler-local type expansion
packages/codegen/src/discover-functions.ts
Type discovery now structurally expands exported and non-exported interfaces and type aliases declared in the handler source file.
Shorthand validator parsing
packages/codegen/src/parse-validator.ts
parseObjectShape now resolves shorthand properties from their property names and regular assignments from their initializers.

Platform error identity

Layer / File(s) Summary
Cloudflare error preservation
packages/platform-cloudflare/src/cloudflare-host.ts
runSerialized and transaction preserve closure errors, expose platform failures, and attach a platform failure as cause when both failures occur.
Error identity contract and conformance
packages/platform/src/shard-host.ts, packages/platform/src/conformance/suite.ts
The ShardHost contract documents exact thrown-value preservation. Conformance tests verify error identity and host reuse after rejection.

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

Sequence Diagram(s)

sequenceDiagram
  participant Closure
  participant CloudflareHost
  participant CloudflareRuntime
  Closure->>CloudflareHost: throw closure error
  CloudflareHost->>CloudflareRuntime: settle blockConcurrencyWhile or transaction
  CloudflareRuntime-->>CloudflareHost: return platform result
  CloudflareHost-->>Closure: rethrow original error
Loading

Possibly related PRs

  • anolilab/lunora#332: Covers the same codegen fixes and Cloudflare error-preservation changes.
  • anolilab/lunora#334: Overlaps in Cloudflare error identity handling, conformance coverage, documentation, and type discovery.
  • anolilab/lunora#240: Overlaps in codegen function discovery and validator parsing.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes relevant context but leaves required template sections empty and begins with stale, conflicting cleanup details. Replace the stale opening text and complete the Summary, Linked issues, Test plan, Checklist, and Notes sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the codegen fix for preserving shorthand table columns.
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 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch fix/shard-error-identity
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/shard-error-identity

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 5, 2026

Copy link
Copy Markdown
Contributor

Thank you for confirming the Contributor License Agreement! 🙏

@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/platform-cloudflare/src/cloudflare-host.ts`:
- Around line 198-200: Update the cause-assignment logic around the existing
closure error handling in the Cloudflare adapter so writing thrown.value.cause
is best-effort and any assignment failure cannot replace the original closure
error; retain the existing guards, then always rethrow thrown.value. Add a
Cloudflare adapter regression covering a differing platform error and a closure
throw of Object.freeze(new Error("closure failed")).
🪄 Autofix

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: b39f0866-8755-497a-b0a5-3964f4e8ee88

📥 Commits

Reviewing files that changed from the base of the PR and between 7b94254 and f8bd461.

⛔ Files ignored due to path filters (3)
  • packages/codegen/__tests__/discover-functions.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/codegen/__tests__/discover-schema.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/platform-cloudflare/__tests__/cloudflare-host.transaction.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
📒 Files selected for processing (5)
  • packages/codegen/src/discover-functions.ts
  • packages/codegen/src/parse-validator.ts
  • packages/platform-cloudflare/src/cloudflare-host.ts
  • packages/platform/src/conformance/suite.ts
  • packages/platform/src/shard-host.ts

Comment on lines +198 to +200
if (thrown.value instanceof Error && thrown.value.cause === undefined && error !== thrown.value) {
thrown.value.cause = error;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Locate file =="
git ls-files | grep -F 'packages/platform-cloudflare/src/cloudflare-host.ts' || true

echo "== Relevant source =="
wc -l packages/platform-cloudflare/src/cloudflare-host.ts
sed -n '150,230p' packages/platform-cloudflare/src/cloudflare-host.ts

echo "== Search for related tests/usages =="
rg -n "cause === undefined|cause =" packages/platform-cloudflare packages -g '*.ts' -g '*.tsx' || true

Repository: anolilab/lunora

Length of output: 4951


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Tests around Cloudflare transaction =="
rg -n "transaction\\(|transactional|cloudflare-host|flattened|closure failed|Object\\.freeze" packages/platform-cloudflare packages -g '*.test.ts' -g '*.spec.ts' -g '*.ts' || true

echo "== Files containing cloudflare tests =="
git ls-files 'packages/platform-cloudflare/**' | grep -E '(__tests__|spec|test|doubles|stores)' | sort

echo "== Read test files mentioning transaction =="
for f in $(git ls-files 'packages/platform-cloudflare/**' | grep -E '(__tests__|spec|test|doubles|stores)'); do
  if rg -q "transaction|closure" "$f"; then
    echo "--- $f"
    wc -l "$f"... 2>/dev/null || true
    rg -n -C 4 "transaction|closure|Object\\.freeze|throw" "$f" || true
  fi
done

Repository: anolilab/lunora

Length of output: 28824


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Runtime behavior of cause assignment edge cases =="
node - <<'JS'
function probe(label, error) {
  const target = { value: error, changed: false };
  try {
    if (target.value instanceof Error && target.value.cause === undefined) {
      target.value.cause = new Error("platform");
      target.changed = true;
    }
    return { label, ok: true, type: Object.prototype.toString.call(target.value), changed: target.changed, thrown: false };
  } catch (e) {
    return { label, ok: false, thrownName: Object.getPrototypeOf(e).name, thrownMessage: e.message, thrownType: Object.prototype.toString.call(e), causeAssignmentFailed: e.message.includes("cause") || e.message.includes("cannot") };
  }
}

const cases = [
  ["plain error with undefined cause", new Error("closure failed")],
  ["frozen generic error", Object.freeze(new Error("closure failed"))],
  ["frozen plain-like causing read/write descriptor same", (() => {
    const base = new Error("closure failed");
    const cause = new Error("platform");
    Object.setPrototypeOf(base, Object.freeze(Object.getPrototypeOf(base)));
    Object.defineProperty(base, "cause", Object.getOwnPropertyDescriptor(base, "cause"));
    return Object.freeze(base);
  })()],
  ["non-enumerable own cause property throwing setter", (() => {
    const base = new Error("closure failed");
    Object.defineProperty(base, "cause", {
      configurable: true,
      get() { return undefined },
      set() { throw new Error("no mutations") }
    });
    return Object.seal(base);
  })()]
];

console.log(JSON.stringify(cases.map(probe), null, 2));
JS

echo "== Existing frozen error test in repo =="
rg -n -C 4 "Object\\.freeze\\(.*Error|frozen = Object\\.freeze|frozenError" packages/platform-cloudflare packages vts -g '*.ts' -g '*.ts' || true

Repository: anolilab/lunora

Length of output: 847


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Runtime behavior of cause assignment edge cases =="
node - <<'JS'
function probe(label, error) {
  const target = { value: error, changed: false };
  try {
    if (target.value instanceof Error && target.value.cause === undefined) {
      target.value.cause = new Error("platform");
      target.changed = true;
    }
    return { label, ok: true, type: Object.prototype.toString.call(target.value), changed: target.changed, thrown: false };
  } catch (e) {
    return { label, ok: false, thrownName: Object.getPrototypeOf(e).name, thrownMessage: e.message, thrownType: Object.prototype.toString.call(e), causeAssignmentFailed: e.message.includes("cause") || e.message.includes("cannot") };
  }
}

function freezeWithOwnCauseDescriptor(base) {
  const cause = new Error("platform");
  const proto = Object.getPrototypeOf(base);
  Object.setPrototypeOf(proto, Object.freeze(Object.getPrototypeOf(proto)));
  base.cause = cause;
  Object.defineProperty(base, "cause", Object.getOwnPropertyDescriptor(base, "cause"));
  return Object.freeze(base);
}

const cases = [
  ["plain error with undefined cause", new Error("closure failed")],
  ["frozen generic error", Object.freeze(new Error("closure failed"))],
  ["frozen plain-like error with own cause descriptor", freezeWithOwnCauseDescriptor(new Error("closure failed"))],
  ["sealed error with throwing cause setter", (() => {
    const base = new Error("closure failed");
    Object.defineProperty(base, "cause", {
      configurable: true,
      get() { return undefined; },
      set() { throw new Error("no mutations"); }
    });
    return Object.seal(base);
  })()]
];

console.log(JSON.stringify(cases.map(probe), null, 2));
JS

echo "== Existing frozen Error regression tests =="
rg -n -C 4 "Object\\.freeze\\(.*new Error|Object\\.freeze\\(.*Error|frozen.*Error|frozenError|throwsFrozen" packages -g '*.ts' -g '*.tsx' || true

Repository: anolilab/lunora

Length of output: 2034


🏁 Script executed:

#!/bin/bash
set -u

echo "== Inspect Node module eval JSON log path =="
cat /tmp/coderabbit-shell-logs/shell-output-cBuqJ9PQ6v.log | tail -80

echo "== Check Node availability/version =="
node --version 2>&1 || true

Repository: anolilab/lunora

Length of output: 332


🏁 Script executed:

#!/bin/bash
set -euo pipefail
unset NODE_OPTIONS

echo "== Simple frozen Error cause assignment probe =="
node --input-type=module - <<'JS'
const errors = [
  ["plain Error", new Error("closure failed")],
  ["frozen generic Error", Object.freeze(new Error("closure failed"))],
  ["Error frozen before own cause assignment", (() => {
    const e = new Error("closure failed");
    return Object.freeze(e);
  })()],
  ["sealed Error with throwing setter", (() => {
    const e = new Error("closure failed");
    Object.defineProperty(e, "cause", {
      get() { return undefined; },
      set() { throw new TypeError("no mutations"); }
    });
    return Object.seal(e);
  })()],
];

for (const [label, source] of errors) {
  let error;
  try {
    source.cause = new Error("platform");
    error = null;
  } catch (e) {
    error = {
      name: e.constructor.name,
      message: e.message,
      thrownForCauseAssignment: true
    };
  }
  console.log(label, error ? JSON.stringify(error) : "assignment ok");
}
JS

echo "== Read existing transaction spec for regression gap =="
sed -n '68,120p' packages/platform-cloudflare/__tests__/cloudflare-host.transaction.test.ts

Repository: anolilab/lunora

Length of output: 3158


Preserve the closure error when cause is immutable.

The assignment at line 199 writes to an arbitrary closure-thrown Error; for a frozen error, a read-only cause, or a throwing cause setter, this throws a TypeError and replaces the original closure throw with that mutation error. Make the cause read/write best-effort inside the existing catch, then still rethrow thrown.value. Add a Cloudflare adapter regression where the platform error differs and the closure throws Object.freeze(new Error("closure failed")).

🤖 Prompt for 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.

In `@packages/platform-cloudflare/src/cloudflare-host.ts` around lines 198 - 200,
Update the cause-assignment logic around the existing closure error handling in
the Cloudflare adapter so writing thrown.value.cause is best-effort and any
assignment failure cannot replace the original closure error; retain the
existing guards, then always rethrow thrown.value. Add a Cloudflare adapter
regression covering a differing platform error and a closure throw of
Object.freeze(new Error("closure failed")).

@prisis prisis closed this Aug 5, 2026
@prisis
prisis deleted the fix/shard-error-identity branch August 11, 2026 22:30
@github-actions

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 10, 2026
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