Repository navigation
fix(platform): atomic hold-aware org deletion, immutable slug - #3162
Merged
Merged
Conversation
Deletion was client-orchestrated: the app's prepare-deletion endpoint committed the organization_deleted audit row, deleted the org's user_preferences and enqueued the config-tree removal in its own transaction, and only then did the client call Better Auth's organization.delete. A failed or missing second call left a live organization gutted with a false deletion audit, and the TODO'd legal-hold guard was never re-added once the governance domain landed. The app now owns the single deletion door, POST /api/app/organizations/:id/delete, as one serializable transaction: every guard first (membership, owner role, default-org protection, an org-wide OR any custodian legal hold refuses with 409 LEGAL_HOLD_ACTIVE and nothing written), then the audit row, the per-user cascade (user_preferences, memories, last-active and session pointers), Better Auth's rows leaf-first (teamMember, team, invitation, member, the org), and the org.cleanup_files job enqueued through the same transaction. Better Auth's own /organization/delete is disabled so no second door bypasses the gate, and the cleanup job re-checks that no live organization still owns the slug before removing a tree. The client makes one call and maps the hold refusal to a translated, actionable toast (en/de/fr); the legal-hold docs name the new block.
beforeUpdateOrganization validated and applied a slug change with no compensation, while the slug is the tenant key of everything outside the database: blob keys embed it (s3KeyBelongsToOrg), the config tree lives at $TALE_CONFIG_DIR/<slug>, the knowledge corpora are scoped by it. One rename silently orphaned every stored file, every config file and the corpus, with new writes landing under the new slug. The slug is immutable once set: a differing value is refused with an actionable 400, re-sending the current slug beside a name change still lands, and a slug-less organization may still receive its first. The settings form never sent the slug, so the only affected path was the raw API.
A dedicated user with two organizations proves, against real Postgres: a custodian hold and an org-wide hold each refuse deletion and leave the org intact; Better Auth's delete door answers 404; a non-owner is refused; a slug rename is refused while the unchanged slug still updates; an aborted teardown transaction leaves rows, audit and jobs untouched; a queued cleanup for a slug a live organization owns leaves its tree alone; the committed delete removes rows, writes the audit row, cascades preferences and pointers and drops the config tree; and the shared user keeps their account and their other organization.
…egrity # Conflicts: # docs/de/platform/admin/governance/legal-hold.md # docs/en/platform/admin/governance/legal-hold.md # docs/fr/platform/admin/governance/legal-hold.md # services/platform/backend/MIGRATION.md
larryro
marked this pull request as ready for review
September 3, 2026 06:34
This was referenced Sep 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The invariant
"Delete my organization" either fully completes or changes nothing visible; data under a legal hold cannot be deleted; renaming an organization never loses its files.
Before: deletion was client-orchestrated —
POST /organizations/:id/prepare-deletioncommitted theorganization_deletedaudit row, deleted the org'sapp.user_preferencesand enqueued the config-treerm -rfin its own transaction, and only then did the browser call Better Auth'sorganization.delete. A failed or missing second call left a live organization gutted with a false deletion audit; the raw Better Auth door itself deleted with no hold check, no audit and orphaned app state. The legal-hold guard was a staleTODO. AndbeforeUpdateOrganizationapplied slug renames with no compensation although the slug is the tenant key of every blob (s3KeyBelongsToOrg), the config tree ($TALE_CONFIG_DIR/<slug>) and the knowledge corpora.Per finding
1. prepare-deletion destroys org config and preferences before the org is actually deleted — fixed
POST /api/app/organizations/:id/delete, as one serializable transaction (deleteOrganization): every guard first — membership, owner role, default-org protection, legal holds — with nothing written until all pass; then the audit row (while the actor's membership still exists), the per-user cascade (user_preferences,memories,lastActiveOrganizationIdandsession.activeOrganizationIdpointers), Better Auth's rows leaf-first (teamMember,team,invitation,member,organization), and theorg.cleanup_filesjob enqueued through the same transaction (addJobInTx) — the job exists only if the deletion committed./organization/deleteis closed (disableOrganizationDeletion: true→ 404ORGANIZATION_DELETION_DISABLED), so no second door bypasses the gate. On base that door returned 200 and removed the org, members and teams while leavinguser_preferencesand the config tree behind; it also strandedteam/teamMemberrows — the app door removes them.errorToast: falseso the hook owns feedback (the previous flow double-toasted); the hold refusal maps to a translated, actionable line (settings.organization.deleteBlockedByLegalHold, en/de/fr).domains/organizations/service.test.ts(recording tx) — a refusal under either hold issues zero writes and no job; non-owner/stranger/default-org refused before any write; the happy path's order is guards → audit → cascade → Better Auth rows → org row → job, every write bound to the org id,"user"never deleted from; a lost delete race throws so the tx rolls back. Integration (checkOrganizationLifecycle): aborted teardown transaction leaves rows/audit/jobs untouched; the committed delete removes rows, writes the audit row (actor_role=owner, slug in metadata), cascades preferences/pointers/teams, drops the config tree; a queued cleanup for a live org's slug leaves its tree alone.organization_deletedaudit row. Old SPAs mid-rollout callingprepare-deletion/Better Auth delete get 404s and nothing is destroyed (fail-safe direction).2. Org deletion bypasses legal holds — fixed
describeOrganizationHoldBlock(loadActiveHolds(tx, orgId))at the door: an org-wide hold or any custodian (userMembership) hold refuses with 409LEGAL_HOLD_ACTIVEand an actionable message (the whole tenant is what a deletion would destroy, so both granularities the schema supports block). SameLegalHoldErrorthe other destructive paths throw; the route returns{ error, message }.legal-hold.md(en/de/fr) names the block.3. Org slug rename strands blobs, config tree, corpus — fixed (refuse with reason)
beforeUpdateOrganizationclassifies the update (classifyOrgSlugUpdate):rename→ 400The organization slug cannot be changed: files, configuration and knowledge are stored under it. Create a new organization instead.;unchanged(re-sent beside a name change) andinitial(a slug-less org receiving its first) still land; fail-closed when the org can't be identified.name+metadata(organization-settings.tsx), so the UI never exposed slug rename — the only path was the raw/api/auth/organization/updateAPI. Refusing is honest: rename-with-data was never supported (no blob re-keying, no config move, no corpus re-scope exists), and a full migration would need a compensating multi-store transaction the codebase has no primitive for.org-slug.test.ts), integration (rename → 400, slug and config tree unchanged — on base the rename was applied,slug=…-movedwith the tree still at the old slug; unchanged slug + new name → 200).Gates (observed)
main, same harness/tests, fresh stack)bunx tsc --noEmit(platform)bunx oxlint --type-aware(touched files)service.test.ts,org-slug.test.ts)lib/i18n)@tale/ui(incl. the 26 i18n checks)@tale/docsstructuralbackend:integration(throwaway tale-db + MinIO)Refuted / scoped
app.*rows (documents, threads, projects…), S3 blobs and the knowledge corpus in place — the 0.5 ledger's known gap; that is an erasure-job design (multi-store, out-of-transaction), not a change to this door..claude/hooks/format.shrunsoxfmtwith the main clone's config and an absolute worktree path, so the**/*.md/**/*.ymlignore patterns don't match in worktrees — it pads markdown tables and re-wraps yml folded scalars the repo formatter never touches. The pre-commit hook (relative paths) skips them correctly. The noise it produced here was removed; the hook itself is left for its own fix.