Skip to content

fix(platform): classify dead-org errors and recover stale clients - #3052

Merged
larryro merged 4 commits into
mainfrom
fix/org-context-errors
Aug 24, 2026
Merged

larryro merged 4 commits into
mainfrom
fix/org-context-errors

Conversation

@larryro

@larryro larryro commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

Closes the stale/empty-org error class behind the demo project's active GlitchTip cluster (~250 events across ~45 issue groups): a client whose persisted active organization was deleted — or whose org context is an empty string in a stale tab — failed org-scoped queries forever and spammed a new issue group per action failure.

  • TALE-PROJECT-OU — Not a member of organization (empty id), 63 events, still firing the day of this fix; latest event culprit is getOrganizationMember.
  • TALE-PROJECT-VB / VA / VC / VD — one user polling a deleted org (jh7csd7…) weekly for a month, never recovering.
  • ~40 single-event [CONVEX A(…)] [Request ID: xxxx] Server Error groups — the request id defeats message grouping.

Server

  • lib/rls/errors.ts: RLS errors now extend ConvexError<{code, message}> (the ongoing "throw ConvexError codes" migration; lib/auth/require_org_membership.ts is the reference). Class identity and the human message are preserved, so every instanceof UnauthorizedError degrade-gracefully catch site and the server log/title shapes are unchanged; only the wire gains structured data.
  • lib/rls/organization/get_organization_member.ts: rejects an empty organizationId at the boundary (ORG_NOT_FOUND) before any lookup, and classifies membership misses with one failure-path adapter read — dead/malformed org id → ORG_NOT_FOUND, live org without membership → ORG_FORBIDDEN (disabled member too). The looksLikeConvexDocumentId pre-check keeps non-id strings out of the adapter's db.get decode throw.
  • lib/helpers/org_slug.ts: OrgSlugUnresolvableError becomes a structured ConvexError (ORG_NOT_FOUND); isOrgSlugUnresolvable and all catch sites unchanged.
  • members/queries.ts: getCurrentMemberContext maps the gate's code to not_found/not_member instead of re-looking up the organization in its catch.

Client

  • New app/lib/org-error-recovery.ts, wired as the query cache's global onError: on a code: 'ORG_NOT_FOUND' failure it clears the member-context hint, leaves the dead org's dashboard routes for /dashboard/ (the index re-resolves a valid membership), clears the session's active org (setActive({organizationId: null}), best-effort), and refreshes the session cache — once per burst. ORG_FORBIDDEN deliberately does NOT redirect: the dashboard layout's "you've been removed" AccessDenied screen is an intentional design (routes/dashboard/$id.tsx), and structured errors are no longer retried, so forbidden states cannot loop.
  • Query default retry now skips structured ConvexErrors (same rationale useActionQuery documents) — deterministic failures reach the UI and the recovery hook once instead of 4 server executions each.
  • New app/lib/sentry-normalize.ts + beforeSend: strips [Request ID: …] from message/logentry/exception values so failures group one-issue-per-root-cause (covers captureConsoleIntegration-promoted convex console lines too).

Tests

New boundary regression convex/governance/get_policy_org_boundary.test.ts reproduces the GlitchTip evidence end-to-end in a convex-test world (empty id and deleted org id both reject as structured ORG_NOT_FOUND across the function boundary; getCurrentMemberContext folds both into not_found). Rewritten/extended unit suites for the gate, the status mapping, the recovery hook, and the normalizer. The {provider,connector}_credentials non-member refusal tests now seed a real betterAuth organization row so they assert the live-org refusal they were written for.

Verification

On a91763c + this branch: tsc --noEmit clean; oxlint --type-aware clean on all changed files; lint:sast clean; platform suites — server 672 files/8,440 tests pass, client 3,312 tests pass, pii 67,214 tests pass. The single server-suite failure (lib/mocks/contract/openai-compat.test.ts, embedding dim 16384≠1536) fails identically on the pristine base with this change stashed — pre-existing, unrelated.

Related: #3019 · complements 72bc189-style endpoint softening (readBranding default-branding fallback) by closing the class centrally.

A stale or empty persisted organization context (a deleted org id, or
"" from a stale tab) failed org-scoped queries forever: the RLS
membership gate threw a raw UnauthorizedError (an opaque redacted
"Server Error" to clients, uncaught-RLSError spam server-side), nothing
client-side ever cleared the dead org, and the per-call request id in
Convex failure text split every action failure into its own Sentry
issue (~250 events across ~45 groups on demo — TALE-PROJECT-OU/VA/VB/
VC/VD).

Server: the RLS errors and OrgSlugUnresolvableError now extend
ConvexError with {code, message} — class identity and the human message
are preserved, so every instanceof catch site and the log/title shapes
are unchanged. getOrganizationMember rejects an empty organizationId at
the boundary and classifies misses: dead or malformed org id is
ORG_NOT_FOUND, a live org the caller is not in is ORG_FORBIDDEN.
getCurrentMemberContext maps that code instead of re-looking up the
organization in its catch.

Client: a query-cache-wide onError clears the persisted active org and
re-resolves through /dashboard/ when a query fails with ORG_NOT_FOUND
(throttled; ORG_FORBIDDEN intentionally keeps the AccessDenied screen),
the default retry policy skips deterministic ConvexErrors, and a Sentry
beforeSend strips "[Request ID: …]" so failures group by root cause.
Manually testing the stale-org fix on a running stack (real browser, org
deleted under an open tab) caught two gaps the suites had not:

1. The dead-org classification ran AFTER the email fallback, so the
   failure path cost 4-5 sequential cross-component reads. An org
   deletion re-executes every subscribed org-scoped query at once, and
   under that herd the function budget expired mid-chain — clients saw
   unstructured timeouts instead of ORG_NOT_FOUND, and nothing could
   recover. Classify the org right after the member miss: a dead org
   short-circuits in two reads (cheaper than pre-fix) and skips the
   fallback that cannot succeed; a live org reuses the same read for
   the ORG_FORBIDDEN classification. A new unit test pins the exact
   adapter call sequence.

2. The client recovery was wired as QueryCache onError, which only
   fires for queryFn rejections — but @convex-dev/react-query delivers
   a LIVE subscription failure by writing the error state directly
   (query.setState), which is precisely what an open tab receives when
   its org dies mid-session. installOrgErrorRecovery(queryClient) now
   subscribes to the query cache and observes error states from both
   delivery paths; new tests drive a real QueryClient through each.

With both changes the incident scenario recovers hands-off: the parked
tab leaves the deleted org's routes, lands on a surviving org's
dashboard, and the session's persisted active org is re-pointed.
@larryro

larryro commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

Manual test done (reviewer request) — and it earned its keep: the first live run did not recover, which surfaced two gaps the suites missed. Both are fixed in 1fa9210; the scenario now passes hands-off.

Setup: the repo's mode-A manual stack (tests/manual/SETUP.md): local anonymous Convex backend + prod-build serve (TALE_E2E_SERVE_BUILD=1), hermetic fixtures, mock gateway; driven with a real Chromium (real sign-up, real create-org wizard, real dashboards).

Scenario (the incident): a signed-in tab parked on /dashboard/<O2>/chat while O2 is deleted server-side.

  • Before 1fa9210: the deletion re-executes every subscribed org-scoped query at once; the failure path (member miss → 2-read email fallback → classify) blew the function budget under that herd, clients got unstructured timeouts, and the structured ORG_NOT_FOUNDs that did complete arrived via the WS subscription (query.setState) — which QueryCache.onError never sees. The tab sat on the dead org indefinitely.
  • After: dead org classifies in two reads (member miss → org row gone → throw; cheaper than the pre-fix path since the fallback is skipped), and installOrgErrorRecovery observes the query cache so both error-delivery paths dispatch recovery. The tab left the dead org and landed on the surviving org's dashboard in a few seconds, zero interaction; session.activeOrganizationId re-pointed.

Also verified live: wire-level getPolicy as an authenticated user — "" → errorData {code: ORG_NOT_FOUND, message: "Organization id is required."}, deleted org id → ORG_NOT_FOUND, member org → success, another user's live org → ORG_FORBIDDEN "Not a member…". And with the SDK live (dummy DSN, envelopes intercepted): the captured event's grouping text is [CONVEX A(agents/actions:listAgents)] Server Error … with no [Request ID: …] (the raw console args in extra intentionally keep the id for per-event correlation).

Full evidence (screenshots, console/backends logs, raw wire responses, captured envelope) is attached to the TAL-2 task. Post-amendment gates: targeted suites green, full server project 672 files pass with only the pre-existing openai-compat Prism failure (fails identically on pristine main), oxlint --type-aware clean.

The E2E project specs exposed a false-positive recovery: components can
transiently send organizationId "" while their data resolves (the task
modal's `task?.organizationId ?? ''` cluster — the same in-app races
that have been feeding the empty-org GlitchTip group all along, not
only stale tabs). The boundary guard classified "" as ORG_NOT_FOUND,
so the client's dead-org recovery treated a WORKING session as one
whose persisted org was gone and navigated the tab to the picker
mid-flow — dialogs vanished under the driver and both project specs
timed out, deterministically, on every CI run of this branch.

Split the codes: an empty id now rejects as ORG_ID_REQUIRED (a
caller-side gap; structured, terminal, still an UnauthorizedError so
every server catch keeps working), while ORG_NOT_FOUND remains
strictly "this org id no longer resolves" — the only signal the
recovery may act on. getCurrentMemberContext folds both into
status not_found (the dashboard layout's semantics for a garbage
route id are unchanged), and the org-residency error mapper treats
ORG_ID_REQUIRED like its siblings.

Verified: the two previously-failing specs (projects, projects-depth)
pass locally against the hermetic stack with this change; the
recovery, boundary, and gate suites pin the new code.
@larryro

larryro commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

Why shard 10 was red (deterministically) — and the fix in d80f3d1: the two project specs open the task modal, whose hooks can transiently send organizationId: "" while the task doc resolves (task?.organizationId ?? ''). The boundary guard classified "" as ORG_NOT_FOUND, so the new dead-org recovery treated a working session as stale and navigated the tab to the org picker mid-spec — dialogs vanished under the driver and both specs timed out on every run of this branch. (Bonus finding: these in-app "" races are a live source of the TALE-PROJECT-OU event stream — it was never only stale tabs.)

d80f3d1 splits the codes: empty id → ORG_ID_REQUIRED (caller-side gap; structured + terminal, still catchable as UnauthorizedError server-side; never triggers recovery), ORG_NOT_FOUND → strictly "this org id no longer resolves" (the only recovery trigger). getCurrentMemberContext folds both into not_found, so the dashboard layout's behavior for garbage route ids is unchanged.

Verified before pushing: both previously-failing specs (projects.spec.ts, projects-depth.spec.ts) pass locally against the hermetic stack with this change (4/4, incl. the two exact failures), plus the gate/boundary/recovery unit suites (146 tests) and type-aware lint. A repo-wide sweep of the ?? '' org-arg pattern (task modal, kanban, chat) is worth a follow-up — with the code split they are harmless one-shot structured errors, but gating them would silence the remaining TALE-PROJECT-OU trickle from current bundles.

Sweep for the empty-org-id code split: the requireOrgMembershipById
guard test still pinned ORG_NOT_FOUND (caught by CI's Unit job), and
the REST error->status map needed the new code — an empty id is a bad
argument (400), deliberately distinct from ORG_NOT_FOUND's 404.
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.

1 participant