@happyvertical/smrt-core 0.44.0 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +8 -8
- package/agents/change-feed.md +3 -2
- package/agents/generators.md +34 -0
- package/agents/revision-guard.md +66 -0
- package/dist/browser.js +2 -1
- package/dist/cascade.d.ts +5 -9
- package/dist/cascade.d.ts.map +1 -1
- package/dist/cascade.js +65 -30
- package/dist/cascade.js.map +1 -1
- package/dist/change-feed.d.ts +60 -1
- package/dist/change-feed.d.ts.map +1 -1
- package/dist/change-feed.js +464 -27
- package/dist/change-feed.js.map +1 -1
- package/dist/change-signals.d.ts.map +1 -1
- package/dist/change-signals.js +13 -11
- package/dist/change-signals.js.map +1 -1
- package/dist/embedded-write-queue.d.ts +8 -0
- package/dist/embedded-write-queue.d.ts.map +1 -1
- package/dist/embedded-write-queue.js +12 -2
- package/dist/embedded-write-queue.js.map +1 -1
- package/dist/generators/cli.d.ts.map +1 -1
- package/dist/generators/cli.js +10 -18
- package/dist/generators/cli.js.map +1 -1
- package/dist/generators/custom-action.d.ts +216 -0
- package/dist/generators/custom-action.d.ts.map +1 -1
- package/dist/generators/custom-action.js +256 -1
- package/dist/generators/custom-action.js.map +1 -1
- package/dist/generators/index.d.ts +2 -1
- package/dist/generators/index.d.ts.map +1 -1
- package/dist/generators/index.js +3 -2
- package/dist/generators/mcp.d.ts.map +1 -1
- package/dist/generators/mcp.js +14 -39
- package/dist/generators/mcp.js.map +1 -1
- package/dist/generators/preflight-route.d.ts +151 -0
- package/dist/generators/preflight-route.d.ts.map +1 -0
- package/dist/generators/preflight-route.js +194 -0
- package/dist/generators/preflight-route.js.map +1 -0
- package/dist/generators/rest.d.ts +12 -0
- package/dist/generators/rest.d.ts.map +1 -1
- package/dist/generators/rest.js +14 -15
- package/dist/generators/rest.js.map +1 -1
- package/dist/generators/tool-schema.d.ts.map +1 -1
- package/dist/generators/tool-schema.js +2 -8
- package/dist/generators/tool-schema.js.map +1 -1
- package/dist/generators.js +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -4
- package/dist/knowledge.d.ts.map +1 -1
- package/dist/knowledge.js +283 -35
- package/dist/knowledge.js.map +1 -1
- package/dist/manifest/static-manifest.d.ts.map +1 -1
- package/dist/manifest/static-manifest.js +6 -2
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/store.js.map +1 -1
- package/dist/manifest.json +8 -2
- package/dist/object.d.ts +31 -1
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +57 -9
- package/dist/object.js.map +1 -1
- package/dist/registry/framework-base-classes.d.ts +10 -0
- package/dist/registry/framework-base-classes.d.ts.map +1 -0
- package/dist/registry/framework-base-classes.js +92 -0
- package/dist/registry/framework-base-classes.js.map +1 -0
- package/dist/registry/schema-builder.d.ts.map +1 -1
- package/dist/registry/schema-builder.js +2 -0
- package/dist/registry/schema-builder.js.map +1 -1
- package/dist/registry/types.d.ts +27 -6
- package/dist/registry/types.d.ts.map +1 -1
- package/dist/registry.d.ts +1 -0
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +2 -1
- package/dist/registry.js.map +1 -1
- package/dist/revision-guard.d.ts +84 -0
- package/dist/revision-guard.d.ts.map +1 -0
- package/dist/revision-guard.js +120 -0
- package/dist/revision-guard.js.map +1 -0
- package/dist/scanner/manifest-generator.d.ts +46 -16
- package/dist/scanner/manifest-generator.d.ts.map +1 -1
- package/dist/scanner/manifest-generator.js +198 -45
- package/dist/scanner/manifest-generator.js.map +1 -1
- package/dist/smrt-knowledge.json +18 -9
- package/dist/system/bootstrap.d.ts.map +1 -1
- package/dist/system/bootstrap.js +2 -1
- package/dist/system/bootstrap.js.map +1 -1
- package/dist/system/schema.d.ts +75 -2
- package/dist/system/schema.d.ts.map +1 -1
- package/dist/system/schema.js +326 -4
- package/dist/system/schema.js.map +1 -1
- package/dist/vite-plugin/index.d.ts.map +1 -1
- package/dist/vite-plugin/index.js +48 -23
- package/dist/vite-plugin/index.js.map +1 -1
- package/dist/vite-plugin/sveltekit-generator.d.ts +33 -7
- package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
- package/dist/vite-plugin/sveltekit-generator.js +88 -17
- package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
- package/dist/vite-plugin/sync-apply-route.d.ts.map +1 -1
- package/dist/vite-plugin/sync-apply-route.js +2 -0
- package/dist/vite-plugin/sync-apply-route.js.map +1 -1
- package/dist/vite-plugin/web-collections.d.ts.map +1 -1
- package/dist/vite-plugin/web-collections.js +28 -5
- package/dist/vite-plugin/web-collections.js.map +1 -1
- package/package.json +4 -4
package/AGENTS.md
CHANGED
|
@@ -27,14 +27,14 @@ subsystem you are editing. This file keeps what holds across all of them.
|
|
|
27
27
|
|
|
28
28
|
- `initialize()`: loads field initializers, applies option values (options override initializers), loads from DB if id/slug provided
|
|
29
29
|
- `save()`: upsert with STI validation, interceptor execution, auto-embeddings. Persisted objects (`isPersisted` — set by DB hydration and successful saves) upsert on `['id']` so natural-key edits (e.g. slug renames) update in place; new objects upsert on the natural-key conflict columns for ingestion-style dedup (#1472)
|
|
30
|
-
- Persisted `save()`
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
30
|
+
- Persisted `save()` uses loaded `updated_at` in its `UPDATE`; zero rows throws
|
|
31
|
+
`RUNTIME_REVISION_CONFLICT`. Explicit `expectedUpdatedAt` binds a save or
|
|
32
|
+
delete to an earlier snapshot. Remote guarded deletes bind the same predicate
|
|
33
|
+
into the final `DELETE`; embedded adapters compare inside the shared write queue
|
|
34
|
+
before cascading. That queue serializes same-process saves, deletes, and full
|
|
35
|
+
`SmrtObject.withTransaction()` callbacks. Custom writes must preserve this
|
|
36
|
+
public CAS ordering contract. PostgreSQL predicate:
|
|
37
|
+
[agents/revision-guard.md](agents/revision-guard.md).
|
|
38
38
|
- Native DuckDB UUID columns are hydrated as canonical strings before model
|
|
39
39
|
initialization, natural-key lookup, and embedded revision claims. Exact
|
|
40
40
|
natural-key probes retain the interceptor-authorized filter when
|
package/agents/change-feed.md
CHANGED
|
@@ -10,7 +10,8 @@ Adapter-agnostic change-observation spine (`src/change-feed.ts`) — the server
|
|
|
10
10
|
|
|
11
11
|
- `_smrt_changes` system table: one append per framework save/delete via a GlobalInterceptors writer registered at framework init. Deletes are tombstones (`operation: 'delete'`). `_smrt_*` tables are skipped. Feed-append failures log and never fail the user's write. On PostgreSQL, `_smrt_append_change` catches the INSERT in an exception subtransaction and returns SQLSTATE as data, so swallowing/retrying a best-effort failure cannot leave a caller-managed transaction aborted with `25P02` (#2026); the feed row still commits or rolls back with the caller transaction. Raw-handle/read initialization checks for both the table and helper before issuing any DDL; a cold schema/helper install acquires the same transaction-scoped `('smrt', 'system-tables')` advisory lock as bootstrap before its first DDL and rechecks inside one server-side statement, while schema migration/bootstrap remains the authoritative replace path. No dirty-check: a field-unchanged `.save()` appends a spurious `update` entry (diff-aware paths like `getOrUpsert`/sync-apply short-circuit before `save()` and append nothing); subscribers must tolerate spurious entries — they are convergent.
|
|
12
12
|
- Sequences: allocated as `MAX(seq)+1` inside the INSERT with conflict retry — committed rows stay contiguous, so commit order == seq order on SQLite/Postgres/DuckDB (deliberately NOT identity/serial: those allocate before commit and break the cursor guarantee under concurrent writers).
|
|
13
|
+
- Staged appends (PostgreSQL, #2649): `MAX+1` costs a *wait* — the loser of a primary-key race waits for the winner's whole transaction — so an append inside a caller transaction that already wrote rows would let a long write transaction and an ordinary concurrent request form a real lock cycle (`40P01`, found downstream in willgriffin/willgriffin.dev#457). `_smrt_append_change` therefore checks `pg_current_xact_id_if_assigned()` (PostgreSQL 13+): when the caller already has a transaction id it stages the entry in `_smrt_changes_pending` (identity key, conflicts with nothing, never waits, still rolled back with the caller) and `appendChange()` returns **`null`** instead of a sequence. `_smrt_drain_changes()` moves *committed* staged rows into `_smrt_changes` with contiguous `MAX(seq)+row_number()` sequences under a **try-only** advisory lock, so the drain never waits either. Draining is driven from JavaScript, never inside the append helper: an entry sequenced invisibly server-side would get no live `_events` signal while the append's own signal carried a higher sequence, and a subscriber resuming from that `Last-Event-ID` would skip it permanently. `drainChangeFeed(db)` is called best-effort by `getChangesSince()`, by `pruneChangeFeed()`, and by the append path itself (throttled to one drain per 250 ms per database, bypassed immediately after this process staged an append). The append path issues ONE drain statement (a single bounded pass) and nothing else — the caller may own the surrounding transaction, and a second statement there could fail and abort it behind the feed's own error-swallowing (#2026); the helper's whole body, preflight included, sits inside its exception boundary for the same reason. It still settles that drain's signals in order without spending a statement: a drain that allocated anything assigns a transaction id, so an append that then takes the DIRECT path proves the drain committed, and its signals publish ahead of the append's own; a deferred append proves nothing and queues them. Signals for drained entries publish only after a follow-up probe proves the drain committed, so an uncommitted drain can never advertise a sequence a rollback releases for reuse. `getChangesSince()` additionally holds back everything the handle's own drains allocated while a transaction id is still assigned at read time (a per-handle watermark, so later reads in the same transaction keep holding back), and `bootstrapSystemTables()` refreshes the helpers before its schema-version fast return so an already-stamped database does not keep the deadlocking function. Consequences: the cursor guarantee is unchanged (one `MAX+1` writer at a time, only over committed work), but a staged entry becomes visible one drain after its transaction commits, its log position is drain order rather than statement order, and it publishes its live `_events` signal at drain time (post-commit — the old pre-commit signal could describe a rolled-back write). SQLite/DuckDB keep the direct insert unchanged. Residual: an append issued as a transaction's *first* statement still allocates inline — it holds no row locks then, so it cannot close a cycle, but it can make other direct appenders wait for that commit; issue explicit `bumpChangeFeed()` calls after the write or outside the transaction. A deployment that writes only through transactions and reads the feed from a connection that cannot write must schedule `drainChangeFeed()` on a writable one.
|
|
13
14
|
- `getChangesSince(db, { since, tables?, tenantId?, limit? }) → { changes, cursor, resyncRequired?, resyncCursor? }`: strictly monotonic cursor; polling with returned cursors misses no committed change and never repeats one. A cursor that cannot be served incrementally — pruned below the retained `[floor..horizon]` run, or foreign/ahead of the horizon — gets `resyncRequired: true` with empty `changes`, an unadvanced `cursor`, and `resyncCursor` set to the current horizon so clients can full-refetch then resume incrementally; detection runs on the UNFILTERED log so `tables`/`tenantId` filters never trigger or mask it. `getTenantScopedChangesSince()` resolves tenant via the DispatchBus resolver hook (fail-closed: tenancy on + no context → global rows only; tenant `T` sees `T` + global rows, never another tenant).
|
|
14
|
-
- `getTableVersion(db, table) → number`: the per-table change version (`MAX(seq)` for the table, replica-stable
|
|
15
|
+
- `getTableVersion(db, table) → number`: the per-table change version (`MAX(seq)` for the table **plus that table's staged-but-undrained count**, so a staged write still moves the ETag and cannot false-304 a client; the sum is monotonic because draining `n` staged rows raises the table's `MAX(seq)` by at least `n`, and both terms are read in ONE statement — separate reads let a drain be counted twice, minting a version a later write re-mints; replica-stable, with no per-process divergence), the ETag source for zero-query conditional GETs (#1765). Advances on any framework write to the table (CRUD and sync-apply, which all `save()`/`delete()`). A table with no retained entry of its own falls back to the global horizon (never a resettable low value) so an all-pruned table cannot false-304 a stale client; only 0 when the feed is empty.
|
|
15
16
|
- Generated `_changes` routes: REST (`GET {basePath}/_changes`, requires `authMiddleware`, otherwise 401 — per-model `api.public` does NOT apply) and SvelteKit (`{routesDir}/_changes/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.changesRoute.enabled: false`). Query params: `since`, `tables` (comma-separated), `limit`. Responses stay HTTP 200 in the resync state — `resyncRequired` is protocol state, not an error, and `resyncCursor` is the resume cursor after the client completes a full refetch.
|
|
16
|
-
- Retention: `pruneChangeFeed(db, { maxAgeMs?, maxRows?, dryRun? })` — scheduled since #2375 by `runRetentionSweep()` (30-day default), so nothing needs to call it directly; `dryRun` counts the same predicate instead of deleting. Pruning deletes oldest-first and always retains the newest entry (a non-empty feed is never emptied), which is what makes pruned-cursor detection provable and keeps caught-up consumers polling normally. Raw-SQL writes are invisible to the feed (same documented gap as the #1499 cache); `bumpChangeFeed(db, { table, rowId? })` is the manual escape hatch.
|
|
17
|
+
- Retention: `pruneChangeFeed(db, { maxAgeMs?, maxRows?, dryRun? })` — scheduled since #2375 by `runRetentionSweep()` (30-day default), so nothing needs to call it directly; `dryRun` counts the same predicate instead of deleting. Pruning deletes oldest-first and always retains the newest entry (a non-empty feed is never emptied), which is what makes pruned-cursor detection provable. The age bound is a **prefix** bound — everything below the oldest entry still inside the window — because `created_at` and `seq` are not co-monotonic (writer clocks skew, and a staged entry carries its stage-time stamp into a later-assigned sequence); deleting by timestamp alone could punch a hole in the middle of the retained run, where `since < floor - 1` cannot see it and keeps caught-up consumers polling normally. Raw-SQL writes are invisible to the feed (same documented gap as the #1499 cache); `bumpChangeFeed(db, { table, rowId? })` is the manual escape hatch.
|
package/agents/generators.md
CHANGED
|
@@ -63,6 +63,40 @@ requested path rather than a hardcoded `index.js`.
|
|
|
63
63
|
Generated code also has to be valid in an ES module: `arguments` is not a legal
|
|
64
64
|
binding name there, however convenient it reads.
|
|
65
65
|
|
|
66
|
+
## Browser-plane playbook preflight route (#2590)
|
|
67
|
+
|
|
68
|
+
`GET {basePath}/_preflight?key=<playbook key>` (`src/generators/preflight-route.ts`)
|
|
69
|
+
is an advisory, read-effect, idempotent report of what a caller's playbook would
|
|
70
|
+
be allowed to do — capability *selection*, never authorization. Resolution and
|
|
71
|
+
verdict shaping live in `@happyvertical/smrt-playbooks`, which depends on this
|
|
72
|
+
package, so core takes the evaluator as the `APIConfig.playbookPreflight` seam and
|
|
73
|
+
the dependency stays one-way. Without a provider the route 404s.
|
|
74
|
+
|
|
75
|
+
**`authMiddleware` is never invoked by preflight**, and that is enforced
|
|
76
|
+
structurally rather than by discipline: `PlaybookPreflightRouteOptions` has no
|
|
77
|
+
auth member of any kind, and `rest.ts` passes the boolean `appAuthConfigured`
|
|
78
|
+
instead — so there is no handle in the module to invoke by mistake. A synthetic-
|
|
79
|
+
`Request` dry run is explicitly not an option: the middleware is request-bound,
|
|
80
|
+
returns a `Response` rather than a boolean, and may consult session stores,
|
|
81
|
+
rate-limit, or audit. The app-auth layer therefore reports `unknown`, which is the
|
|
82
|
+
honest answer, and a future `authPredicate` seam can fill it in without changing
|
|
83
|
+
the contract.
|
|
84
|
+
|
|
85
|
+
The static layers preflight predicts against are exported from the same module —
|
|
86
|
+
`isApiActionEnabledForObject`, `isRestActionRoutable`, `isRestRoutePublic`,
|
|
87
|
+
`restFieldReadPermissions`, `restMethodForApiAction`,
|
|
88
|
+
`resolveRegisteredObjectName` — and `APIGenerator`'s own
|
|
89
|
+
`isApiActionEnabled` / `isRoutePublic` now delegate to them, so the route and the
|
|
90
|
+
prediction of the route cannot drift. Exposure and existence are separate
|
|
91
|
+
questions: `include`/`exclude` gate a route, they do not conjure one, so
|
|
92
|
+
`isRestActionRoutable` additionally requires a custom action to be declared in
|
|
93
|
+
`api.routes` — the only map `dispatchCustomCollectionAction` iterates. A custom
|
|
94
|
+
action is predicted against the verb its own route config declares, so a
|
|
95
|
+
`public: 'read'` opt-out neither silently covers a `POST` action nor falsely
|
|
96
|
+
denies a declared `GET` one. Every unresolvable key returns the provider's single uniform
|
|
97
|
+
"unavailable" body with an unconditional 200: unknown and unauthorized keys are
|
|
98
|
+
indistinguishable at the HTTP layer too.
|
|
99
|
+
|
|
66
100
|
## Emitted agent surface (#2591)
|
|
67
101
|
|
|
68
102
|
Generated model tools have always been build-time artifacts — virtual module,
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Revision compare-and-swap guard (`src/revision-guard.ts`)
|
|
2
|
+
|
|
3
|
+
Every persisted `save()` pins its `UPDATE` to the revision the writer loaded;
|
|
4
|
+
`claimRevision()` does the same without running domain hooks, and
|
|
5
|
+
`delete({ expectedUpdatedAt })` binds the same predicate into its final
|
|
6
|
+
`DELETE`. Zero affected rows raises `RUNTIME_REVISION_CONFLICT` rather than
|
|
7
|
+
overwriting or removing a newer row.
|
|
8
|
+
|
|
9
|
+
## Why the predicate is not an equality (#2620)
|
|
10
|
+
|
|
11
|
+
The guard used to compare `updated_at` to `loadedRevision.toISOString()`. On
|
|
12
|
+
PostgreSQL a JavaScript `Date` is two lossy conversions away from the stored
|
|
13
|
+
value, so that predicate matched no row at all in two common situations — and
|
|
14
|
+
the object then conflicted on *every* later save, permanently, rather than
|
|
15
|
+
losing a race:
|
|
16
|
+
|
|
17
|
+
- **Precision.** `updated_at` is a microsecond column. Any row last written by
|
|
18
|
+
raw SQL — `updated_at = CURRENT_TIMESTAMP` / `now()`, including SMRT's own
|
|
19
|
+
migration backfills — carries a sub-millisecond tail a `Date` cannot hold.
|
|
20
|
+
- **Process timezone.** Schemas created before the `TIMESTAMPTZ` mapping still
|
|
21
|
+
hold `updated_at` as `timestamp WITHOUT time zone`, and `pg` hydrates that
|
|
22
|
+
type in the process zone, so on a non-UTC host `toISOString()` renders a wall
|
|
23
|
+
clock the row never held. The same columns are written under three different
|
|
24
|
+
conventions — `pg` serializes a bound `Date` in the process zone,
|
|
25
|
+
`claimRevision()` writes a UTC ISO string, and raw `CURRENT_TIMESTAMP` writes
|
|
26
|
+
in the *server* zone — so no single rendering can match every row.
|
|
27
|
+
|
|
28
|
+
## What the predicate does instead
|
|
29
|
+
|
|
30
|
+
`postgresRevisionCondition()` builds
|
|
31
|
+
`date_trunc('milliseconds', updated_at) IN (…)` over both wall-clock renderings
|
|
32
|
+
of the revision, the process-zone one and the UTC one, each tagged `+00` so a
|
|
33
|
+
`timestamptz` comparison honours it and a `timestamp` comparison discards it —
|
|
34
|
+
the predicate therefore does not depend on the *session* TimeZone either. On a
|
|
35
|
+
UTC process the two renderings coincide and the condition is single-valued.
|
|
36
|
+
|
|
37
|
+
Lost-race semantics are preserved: a concurrent writer advances `updated_at` to
|
|
38
|
+
roughly "now", so it must land on the loaded revision — or, on a non-UTC
|
|
39
|
+
process only, on that revision shifted by the whole UTC offset — to the
|
|
40
|
+
millisecond before it could slip past. Collapsing that second rendering so the
|
|
41
|
+
predicate is single-valued on every process is tracked as #2623.
|
|
42
|
+
|
|
43
|
+
## Rules
|
|
44
|
+
|
|
45
|
+
- Never rebuild this predicate by hand; call `postgresRevisionCondition()`.
|
|
46
|
+
Every guarded write — `save()`, `claimRevision()`, and the guarded `DELETE` —
|
|
47
|
+
goes through `SmrtObject.revisionPredicate()` so no path is left on the exact
|
|
48
|
+
equality.
|
|
49
|
+
- The condition is PostgreSQL-only. Embedded engines take the process-local
|
|
50
|
+
compare/upsert fallback (`usesEmbeddedRevisionFallback`), and remote LibSQL
|
|
51
|
+
stores ISO text whose exact equality round-trips losslessly.
|
|
52
|
+
- Custom write paths must go through `save()`, `save({ expectedUpdatedAt })`,
|
|
53
|
+
or `claimRevision()` rather than bypassing the CAS ordering contract.
|
|
54
|
+
- The driver-layer half — `pg` hydrating and serializing `timestamp` columns in
|
|
55
|
+
the process zone — is tracked as happyvertical/sdk#1223. The guard
|
|
56
|
+
deliberately assumes neither hydration convention, so a UTC-hydration fix
|
|
57
|
+
there cannot break it.
|
|
58
|
+
|
|
59
|
+
## Coverage
|
|
60
|
+
|
|
61
|
+
`src/__tests__/issue-2620-revision-guard-precision-postgres.optional.test.ts`
|
|
62
|
+
runs the whole battery — guarded save, `save({ expectedUpdatedAt })`,
|
|
63
|
+
`claimRevision()`, guarded delete, and their still-conflicts counterparts —
|
|
64
|
+
against both `updated_at` column shapes in the registered PostgreSQL suite (`pnpm --filter @happyvertical/smrt-core
|
|
65
|
+
test:postgres`). `src/__tests__/revision-guard.test.ts` covers the rendering
|
|
66
|
+
itself in the default suite.
|
package/dist/browser.js
CHANGED
|
@@ -15,6 +15,7 @@ import { convertTypeToJsonSchema, generateToolFromMethod, generateToolManifest,
|
|
|
15
15
|
import { executeToolCall, executeToolCalls, formatToolResults, validateToolCall } from "./tools/tool-executor.js";
|
|
16
16
|
import { SmrtObject } from "./object.js";
|
|
17
17
|
import { SMRT_COLLECTION_BASE_NAMES, isSmrtCollectionExtendsName } from "./registry/collection-resolution.js";
|
|
18
|
+
import { isFrameworkBaseClass } from "./registry/framework-base-classes.js";
|
|
18
19
|
import { ObjectRegistry, smrt } from "./registry.js";
|
|
19
20
|
import { DEFAULT_FACET_LIMIT, MAX_FACET_FIELDS, MAX_FACET_LIMIT, MAX_STI_READ_SCOPE_TYPES, SmrtCollection } from "./collection.js";
|
|
20
21
|
import { SmrtHierarchical } from "./hierarchical.js";
|
|
@@ -24,4 +25,4 @@ import "./signals/index.js";
|
|
|
24
25
|
import { DEFAULT_RETENTION_POLICY, clearRetentionTasks, getRetentionTasks, pruneAiUsage, pruneExpiredContexts, registerRetentionTask, runRetentionSweep, unregisterRetentionTask } from "./system/retention.js";
|
|
25
26
|
import "./system/index.js";
|
|
26
27
|
import "./tools/index.js";
|
|
27
|
-
export { AIError, AiUsageCollector, AiUsagePersistenceHandler, ConfigurationError, DEFAULT_AI_COST_RATES, DEFAULT_FACET_LIMIT, DEFAULT_RETENTION_POLICY, DatabaseError, ErrorUtils, FilesystemError, MAX_FACET_FIELDS, MAX_FACET_LIMIT, MAX_STI_READ_SCOPE_TYPES, MetricsAdapter, NetworkError, ObjectRegistry, PubSubAdapter, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, assertPostgresSystemTimestampsCurrent, classifyDatabaseError, classifyDialectMessage, clearRetentionTasks, config, convertTypeToJsonSchema, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, estimateAiUsageCost, executeToolCall, executeToolCalls, formatToolResults, generateToolFromMethod, generateToolManifest, getDatabaseEngine, getRetentionTasks, isAbortedTransactionError, isDeterministicDatabaseError, isNotNullViolationError, isSmrtCollectionExtendsName, isTransientDatabaseError, isUniqueViolationError, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, pruneAiUsage, pruneExpiredContexts, registerRetentionTask, runRetentionSweep, shouldIncludeMethod, smrt, smrt as smrtRegistry, tableExists, unregisterRetentionTask, validateToolCall };
|
|
28
|
+
export { AIError, AiUsageCollector, AiUsagePersistenceHandler, ConfigurationError, DEFAULT_AI_COST_RATES, DEFAULT_FACET_LIMIT, DEFAULT_RETENTION_POLICY, DatabaseError, ErrorUtils, FilesystemError, MAX_FACET_FIELDS, MAX_FACET_LIMIT, MAX_STI_READ_SCOPE_TYPES, MetricsAdapter, NetworkError, ObjectRegistry, PubSubAdapter, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, assertPostgresSystemTimestampsCurrent, classifyDatabaseError, classifyDialectMessage, clearRetentionTasks, config, convertTypeToJsonSchema, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, estimateAiUsageCost, executeToolCall, executeToolCalls, formatToolResults, generateToolFromMethod, generateToolManifest, getDatabaseEngine, getRetentionTasks, isAbortedTransactionError, isDeterministicDatabaseError, isFrameworkBaseClass, isNotNullViolationError, isSmrtCollectionExtendsName, isTransientDatabaseError, isUniqueViolationError, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, pruneAiUsage, pruneExpiredContexts, registerRetentionTask, runRetentionSweep, shouldIncludeMethod, smrt, smrt as smrtRegistry, tableExists, unregisterRetentionTask, validateToolCall };
|
package/dist/cascade.d.ts
CHANGED
|
@@ -96,15 +96,11 @@ export declare function cascadeReferencesTo(db: DatabaseInterface, registry: Cas
|
|
|
96
96
|
/**
|
|
97
97
|
* Run the cascade and the target row's own deletion atomically.
|
|
98
98
|
*
|
|
99
|
-
* When
|
|
100
|
-
*
|
|
101
|
-
* statement, so a failure part-way through cannot leave
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
* degradation, not a silent one.
|
|
105
|
-
*
|
|
106
|
-
* When nothing references the class there is nothing to keep consistent, and
|
|
107
|
-
* the transaction is skipped — see the comment on that branch.
|
|
99
|
+
* When the adapter exposes `transaction()`, the whole sequence runs inside one
|
|
100
|
+
* — including framework-owned row cleanup and the caller's `deleteSelf`
|
|
101
|
+
* statement, so a failure part-way through cannot leave either side orphaned.
|
|
102
|
+
* Adapters without transaction support run the same statements sequentially;
|
|
103
|
+
* this is the documented degradation, not a silent one.
|
|
108
104
|
*
|
|
109
105
|
* @param db - Database the object is bound to
|
|
110
106
|
* @param registry - Registry view used to build cascade plans
|
package/dist/cascade.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cascade.d.ts","sourceRoot":"","sources":["../src/cascade.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"cascade.d.ts","sourceRoot":"","sources":["../src/cascade.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAK5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAKpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAM1D;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,gBAAgB,CAAC;AAsB9C,gFAAgF;AAChF,MAAM,WAAW,gBAAgB;IAC/B,mEAAmE;IACnE,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,SAAS,EAAE,MAAM,CAAC;IAClB,iDAAiD;IAC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,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,EAAE,CAAA;CAAE,GAC9D,OAAO,CAAC,aAAa,CAAC,CAwBxB;AASD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,iBAAiB,EACrB,QAAQ,EAAE,mBAAmB,EAC7B,MAAM,EAAE;IACN,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,+DAA+D;IAC/D,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;CAC/B,EACD,UAAU,EAAE,CAAC,EAAE,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,GACnD,OAAO,CAAC,aAAa,CAAC,CAuDxB"}
|
package/dist/cascade.js
CHANGED
|
@@ -24,14 +24,11 @@ import { createLogger } from "@happyvertical/logger";
|
|
|
24
24
|
* `afterDelete` hooks and interceptors do **not** run, and no change-feed
|
|
25
25
|
* tombstone is written for them — exactly as `ON DELETE CASCADE` behaves.
|
|
26
26
|
* Only the object `delete()` was called on runs the full lifecycle.
|
|
27
|
-
* -
|
|
28
|
-
*
|
|
29
|
-
* survive a failure. A
|
|
30
|
-
* polymorphic association class anywhere in the process skips the
|
|
31
|
-
* transaction — see {@link runCascadeDelete}. A `metaType` column can point
|
|
27
|
+
* - Every delete runs inside a single transaction when the adapter exposes
|
|
28
|
+
* one, including cleanup of framework-owned context and embedding rows, so
|
|
29
|
+
* a partial cascade cannot survive a failure. A `metaType` column can point
|
|
32
30
|
* at any class at runtime, so a polymorphic association class is always
|
|
33
|
-
* plausibly relevant
|
|
34
|
-
* rare, not the common case.
|
|
31
|
+
* plausibly relevant.
|
|
35
32
|
*
|
|
36
33
|
* ## Which references are followed
|
|
37
34
|
*
|
|
@@ -240,6 +237,43 @@ async function tolerateMissingTable(operation, fallback, context) {
|
|
|
240
237
|
throw error;
|
|
241
238
|
}
|
|
242
239
|
}
|
|
240
|
+
/**
|
|
241
|
+
* System-table cleanup may ignore an absent table for databases created before
|
|
242
|
+
* that subsystem existed, but never a missing column in a table that does
|
|
243
|
+
* exist. The shared `undefined_object` classification intentionally combines
|
|
244
|
+
* both cases, so this security boundary must retain the narrower driver signal.
|
|
245
|
+
*/
|
|
246
|
+
function normalizeMissingTableName(value) {
|
|
247
|
+
const unquoted = value.replace(/["'`[\]]/g, "");
|
|
248
|
+
return (unquoted.split(".").at(-1) ?? unquoted).replace(/[^A-Za-z0-9_$-]/g, "").toLowerCase();
|
|
249
|
+
}
|
|
250
|
+
function missingTableNames(messages) {
|
|
251
|
+
const names = [];
|
|
252
|
+
const patterns = [
|
|
253
|
+
/no such table:\s*([^\s,;]+)/giu,
|
|
254
|
+
/(?:relation|table)\s+((?:"[^"]+"(?:\."[^"]+")*)|(?:[A-Za-z0-9_.$-]+))\s+does not exist/giu,
|
|
255
|
+
/table with name\s+((?:"[^"]+")|(?:[A-Za-z0-9_.$-]+))\s+does not exist/giu
|
|
256
|
+
];
|
|
257
|
+
for (const message of messages) for (const pattern of patterns) for (const match of message.matchAll(pattern)) if (match[1]) names.push(normalizeMissingTableName(match[1]));
|
|
258
|
+
return names;
|
|
259
|
+
}
|
|
260
|
+
function isMissingTableError(error, expectedTable) {
|
|
261
|
+
const classification = classifyDatabaseError(error);
|
|
262
|
+
if (classification.kind !== "undefined_object") return false;
|
|
263
|
+
if (classification.sqlstate === "42703" || classification.driverCode === "42703" || classification.driverCodes.includes("42703")) return false;
|
|
264
|
+
const names = missingTableNames(classification.driverMessages);
|
|
265
|
+
const expected = normalizeMissingTableName(expectedTable);
|
|
266
|
+
return names.length > 0 && names.every((missingTableName) => missingTableName === expected);
|
|
267
|
+
}
|
|
268
|
+
async function tolerateMissingSystemTable(operation, fallback, context) {
|
|
269
|
+
try {
|
|
270
|
+
return await operation();
|
|
271
|
+
} catch (error) {
|
|
272
|
+
if (!isMissingTableError(error, context.table)) throw error;
|
|
273
|
+
logger.warn(`Cascade delete skipped ${context.action} on '${context.table}': table not found in this database.`, { error: error instanceof Error ? error.message : String(error) });
|
|
274
|
+
return fallback;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
243
277
|
async function selectIds(db, tableName, column, ids) {
|
|
244
278
|
const found = [];
|
|
245
279
|
for (const batch of chunkArray(ids, 900)) {
|
|
@@ -275,7 +309,8 @@ async function deleteByIds(db, tableName, ids) {
|
|
|
275
309
|
* enough.
|
|
276
310
|
*
|
|
277
311
|
* A missing system table is not an error — an application database may predate
|
|
278
|
-
* the table
|
|
312
|
+
* the table. Every other cleanup failure propagates so the surrounding delete
|
|
313
|
+
* transaction rolls back rather than orphaning tenant-sensitive recall data.
|
|
279
314
|
*/
|
|
280
315
|
async function deleteSystemRows(db, ids, classNames) {
|
|
281
316
|
const ownerIds = ids.filter((id) => typeof id === "string" && id.length > 0 && id !== COLLECTION_OWNER_SENTINEL);
|
|
@@ -288,14 +323,13 @@ async function deleteSystemRows(db, ids, classNames) {
|
|
|
288
323
|
EMBEDDINGS_TABLE,
|
|
289
324
|
"object_id",
|
|
290
325
|
"object_class"
|
|
291
|
-
]]) for (const batch of chunkArray(ownerIds, 900))
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
}
|
|
326
|
+
]]) for (const batch of chunkArray(ownerIds, 900)) await tolerateMissingSystemTable(() => db.delete(table, {
|
|
327
|
+
...idPredicate(idColumn, batch),
|
|
328
|
+
...idPredicate(classColumn, classNames)
|
|
329
|
+
}), void 0, {
|
|
330
|
+
table,
|
|
331
|
+
action: "framework-owned row cleanup"
|
|
332
|
+
});
|
|
299
333
|
}
|
|
300
334
|
/**
|
|
301
335
|
* Resolve every reference pointing at `ids` of `className`, recursively.
|
|
@@ -383,15 +417,11 @@ async function cascadeReferencesTo(db, registry, target) {
|
|
|
383
417
|
/**
|
|
384
418
|
* Run the cascade and the target row's own deletion atomically.
|
|
385
419
|
*
|
|
386
|
-
* When
|
|
387
|
-
*
|
|
388
|
-
* statement, so a failure part-way through cannot leave
|
|
389
|
-
*
|
|
390
|
-
*
|
|
391
|
-
* degradation, not a silent one.
|
|
392
|
-
*
|
|
393
|
-
* When nothing references the class there is nothing to keep consistent, and
|
|
394
|
-
* the transaction is skipped — see the comment on that branch.
|
|
420
|
+
* When the adapter exposes `transaction()`, the whole sequence runs inside one
|
|
421
|
+
* — including framework-owned row cleanup and the caller's `deleteSelf`
|
|
422
|
+
* statement, so a failure part-way through cannot leave either side orphaned.
|
|
423
|
+
* Adapters without transaction support run the same statements sequentially;
|
|
424
|
+
* this is the documented degradation, not a silent one.
|
|
395
425
|
*
|
|
396
426
|
* @param db - Database the object is bound to
|
|
397
427
|
* @param registry - Registry view used to build cascade plans
|
|
@@ -402,12 +432,17 @@ async function cascadeReferencesTo(db, registry, target) {
|
|
|
402
432
|
async function runCascadeDelete(db, registry, target, deleteSelf) {
|
|
403
433
|
const ids = target.id ? [target.id] : [];
|
|
404
434
|
if (buildCascadePlan(registry, target.className).isEmpty) {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
435
|
+
const runWithoutReferences = async (bound) => {
|
|
436
|
+
await deleteSystemRows(bound, ids, ownerClassCandidates(registry, target.className));
|
|
437
|
+
await deleteSelf(bound);
|
|
438
|
+
return {
|
|
439
|
+
affectedTables: /* @__PURE__ */ new Set(),
|
|
440
|
+
affectedTableClasses: /* @__PURE__ */ new Map()
|
|
441
|
+
};
|
|
410
442
|
};
|
|
443
|
+
const transaction = db.transaction;
|
|
444
|
+
if (typeof transaction !== "function") return runWithoutReferences(db);
|
|
445
|
+
return transaction.call(db, runWithoutReferences);
|
|
411
446
|
}
|
|
412
447
|
const run = async (bound) => {
|
|
413
448
|
const result = await cascadeReferencesTo(bound, registry, {
|
package/dist/cascade.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cascade.js","names":[],"sources":["../src/cascade.ts"],"sourcesContent":["/**\n * App-side referential integrity for `SmrtObject.delete()` (#2371).\n *\n * Same-package `@foreignKey` fields now emit database constraints where the\n * engine can enforce the declared policy. Cross-package references and older\n * schemas still rely on this application-side path. Before this module,\n * `delete()` removed the object's own row and nothing else: junction rows,\n * polymorphic association rows, `_smrt_embeddings` and `_smrt_contexts` entries\n * were all left pointing at an id that no longer resolved, and\n * `@foreignKey(..., { onDelete })` was metadata nobody read.\n *\n * This module implements those semantics in the application layer. It mirrors\n * what a DB-level constraint would do, deliberately including the parts that\n * make it *unlike* a model-layer delete:\n *\n * - Cascaded rows are removed with set-based statements. Their `beforeDelete` /\n * `afterDelete` hooks and interceptors do **not** run, and no change-feed\n * tombstone is written for them — exactly as `ON DELETE CASCADE` behaves.\n * Only the object `delete()` was called on runs the full lifecycle.\n * - When anything needs cascading, everything runs inside a single\n * transaction when the adapter exposes one, so a partial cascade cannot\n * survive a failure. A class with no typed references AND no registered\n * polymorphic association class anywhere in the process skips the\n * transaction — see {@link runCascadeDelete}. A `metaType` column can point\n * at any class at runtime, so a polymorphic association class is always\n * plausibly relevant; in an app with even one registered, this fast path is\n * rare, not the common case.\n *\n * ## Which references are followed\n *\n * A reference is any `@foreignKey` / `@crossPackageRef` field on a registered\n * class whose target resolves to the deleted object's class (or one of its\n * registered STI ancestors), plus the polymorphic `(metaType, metaId)` pair on\n * {@link SmrtPolymorphicAssociation} subclasses.\n *\n * The action comes from the field's declared `onDelete`. When it is not\n * declared, the default is derived from the referencing class's natural key:\n *\n * | Reference | Default when `onDelete` is absent |\n * |---|---|\n * | Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n * | Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n * | Ordinary same-package reference | `NO ACTION` (deletion is refused while references remain) |\n * | Every `@tenantId()` field | Excluded: tenant scope is not an ownership edge |\n *\n * The natural-key rule is what makes junction rows work without any\n * per-package annotation: a junction declares\n * `@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so\n * `content_id` identifies the row and the row cannot outlive the content it\n * links. An ordinary child (`Order.customerId`) is keyed by `(slug, context)`,\n * so it defaults to immediate `NO ACTION` unless it opts in with\n * `@foreignKey(Customer, { onDelete: 'CASCADE' })`.\n *\n * `@tenantId()` fields are excluded from the natural-key rule even though\n * `@happyvertical/smrt-tenancy` leads a tenant-scoped class's *default*\n * `conflictColumns` with the tenant column (#2360): the tenant column scopes\n * ownership, it does not identify the row the way a junction's foreign key\n * does, and it targets a class (`Tenant`) that is virtually always\n * referenced. Without this exclusion, deleting one `Tenant` row would\n * recursively CASCADE through every tenant-scoped table that has not\n * declared its own `conflictColumns` — the overwhelming majority. The field\n * is detected via the `__tenancy.isTenantIdField` marker `@tenantId()`\n * attaches to its own registration (`FieldMeta.__tenancy`, read structurally\n * so `smrt-core` never depends on `smrt-tenancy`). `@tenantId()` exposes no\n * `onDelete` option today, so this cannot currently be overridden per field.\n *\n * @see https://github.com/happyvertical/smrt/issues/2371\n * @module\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { classifyDatabaseError } from './db-errors.js';\nimport { ConfigurationError, DatabaseError } from './errors.js';\n// Type-only: erased at runtime, so it cannot re-enter the\n// `registry → object → cascade` import cycle.\nimport type { ObjectRegistry } from './registry.js';\nimport {\n normalizeForeignKeyAction,\n resolveForeignKeyDeleteAction,\n} from './schema/foreign-key-policy.js';\nimport type { ForeignKeyAction } from './schema/types.js';\nimport { chunkArray, IN_LIST_CHUNK_SIZE } from './utils/chunk.js';\nimport { toSnakeCase } from './utils/naming.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Referential action applied to rows pointing at a deleted object.\n *\n * Same vocabulary as SQL's `ON DELETE`, enforced by the framework before the\n * engine. `NO ACTION` is preflighted like an immediate restrictive action so\n * application-side and database-side enforcement agree.\n */\nexport type OnDeleteAction = ForeignKeyAction;\n\n/** Table holding framework-managed per-object memory entries. */\nconst CONTEXTS_TABLE = '_smrt_contexts';\n\n/** Table holding framework-managed per-object embedding vectors. */\nconst EMBEDDINGS_TABLE = '_smrt_embeddings';\n\n/**\n * Reserved `_smrt_contexts.owner_id` used by `SmrtCollection.remember()` for\n * collection-scoped memory. A real object id is a UUID and can never equal it,\n * but the guard keeps a malformed id from wiping every sibling's defaults.\n */\nconst COLLECTION_OWNER_SENTINEL = '__collection__';\n\n/**\n * Maximum number of cascade levels followed from the object `delete()` was\n * called on. A cycle between two classes that both declare `onDelete: 'CASCADE'`\n * is broken by the visited set; this bound catches unbounded *chains*.\n */\nconst MAX_CASCADE_DEPTH = 10;\n\n/** One reference that must be resolved before the target row can be removed. */\nexport interface CascadeReference {\n /** Registered name of the class holding the referencing column. */\n className: string;\n /** Table holding the referencing rows. */\n tableName: string;\n /** Field name (camelCase) on the referencing class. */\n fieldName: string;\n /** Column (snake_case) holding the reference. */\n column: string;\n /** Resolved action. `NO ACTION` is preflighted like an immediate RESTRICT. */\n action: OnDeleteAction;\n /** `true` when the action was declared rather than derived from the key. */\n declared: boolean;\n}\n\n/** A polymorphic association table that can point at any class. */\nexport interface CascadePolymorphicReference {\n /** Registered name of the association class. */\n className: string;\n /** Table holding the association rows. */\n tableName: string;\n}\n\n/** Everything that must happen before rows of one class can be deleted. */\nexport interface CascadePlan {\n /** Typed `@foreignKey` / `@crossPackageRef` references, action-resolved. */\n references: CascadeReference[];\n /** Polymorphic association tables that may point at this class. */\n polymorphic: CascadePolymorphicReference[];\n /** `meta_type` values that identify this class in an association row. */\n metaTypes: string[];\n /** `true` when nothing references this class and nothing has to be visited. */\n isEmpty: boolean;\n}\n\n/**\n * Read-only slice of `ObjectRegistry` this module needs.\n *\n * Taking it as a parameter — rather than importing the registry as a value —\n * keeps `cascade.ts` out of the `registry → object → cascade` import cycle,\n * and lets tests drive the planner from a hand-built registry.\n */\nexport type CascadeRegistryView = Pick<\n typeof ObjectRegistry,\n | 'getRelationshipMap'\n | 'getFields'\n | 'getConflictColumns'\n | 'getTableName'\n | 'getSelfReferableNames'\n | 'getClass'\n | 'getSTIBase'\n | 'getDescendants'\n>;\n\n/**\n * Normalize a declared `onDelete` value.\n *\n * Accepts any casing and both `SET NULL` and `SET_NULL`, matching what the\n * schema generator has always carried in the manifest. Returns `undefined` for\n * an unset or unrecognized value so the caller can fall back to the default.\n */\nexport function normalizeOnDelete(value: unknown): OnDeleteAction | undefined {\n return normalizeForeignKeyAction(value);\n}\n\nfunction isPolymorphicAssociationClass(fields: Map<string, unknown>): boolean {\n // The three columns `SmrtPolymorphicAssociation` contributes. Requiring all\n // of them keeps an unrelated class that happens to carry a `metaType` from\n // being treated as an association table.\n return fields.has('metaType') && fields.has('metaId') && fields.has('role');\n}\n\n/**\n * Build the cascade plan for one class.\n *\n * The plan is derived entirely from registry metadata, so it is valid for any\n * database the class is used against. It is rebuilt per delete rather than\n * cached: registration is incremental (manifests load lazily, tests register\n * classes between cases) and a stale plan would silently skip a table.\n *\n * @param registry - Registry view (`ObjectRegistry` satisfies it)\n * @param className - Class whose incoming references should be resolved\n */\nexport function buildCascadePlan(\n registry: CascadeRegistryView,\n className: string,\n): CascadePlan {\n // `className` is normally already qualified (delete() passes\n // getResolvedQualifiedName()), but a common same-package `@foreignKey('X')`\n // still stores its target as the bare simple name `X`. That still matches:\n // getSelfReferableNames() walks the full ancestor chain (self included) and\n // adds each ancestor's *simple* name via `getClass(ancestor)?.name`, so the\n // simple form is already in the seed set below, not just the loop's\n // qualified-variant augmentation.\n const targetNames = new Set(registry.getSelfReferableNames(className));\n for (const name of [...targetNames]) {\n const qualified = registry.getClass(name)?.qualifiedName;\n if (qualified) targetNames.add(qualified);\n }\n\n const references: CascadeReference[] = [];\n const polymorphic: CascadePolymorphicReference[] = [];\n\n for (const [sourceClass, relationships] of registry.getRelationshipMap()) {\n const fields = registry.getFields(sourceClass);\n\n if (isPolymorphicAssociationClass(fields)) {\n const tableName = registry.getTableName(sourceClass);\n if (tableName) {\n polymorphic.push({ className: sourceClass, tableName });\n }\n }\n\n if (relationships.length === 0) continue;\n\n let conflictColumns: Set<string> | undefined;\n\n for (const relationship of relationships) {\n if (\n relationship.type !== 'foreignKey' &&\n relationship.type !== 'crossPackageRef'\n ) {\n continue;\n }\n if (!targetNames.has(relationship.targetClass)) continue;\n\n // An explicit app-side-only relationship is archival metadata, not a\n // referential-integrity rule. Its identifier is deliberately allowed to\n // outlive the parent, so delete planning must not block, null, or remove\n // the retained row (#2413).\n if (\n relationship.type === 'foreignKey' &&\n relationship.options?.constraint === false\n ) {\n continue;\n }\n\n const tableName = registry.getTableName(sourceClass);\n if (!tableName) continue;\n\n const column = toSnakeCase(relationship.fieldName);\n if (!conflictColumns) {\n conflictColumns = new Set(registry.getConflictColumns(sourceClass));\n }\n\n // A `@tenantId()` field is a structural scoping marker, not a\n // junction/ownership key — it lands in `conflictColumns` only because\n // #2360 leads every tenant-scoped class's *default* natural key with\n // the tenant column, not because the referencing row is *identified*\n // by its tenant the way a junction row is identified by its parent.\n // Without this guard, deleting a `Tenant` would silently CASCADE\n // through the tenant column of every tenant-scoped class in the\n // schema that has not declared its own `conflictColumns` — the\n // overwhelming majority. `@tenantId()` exposes no `onDelete` today, so\n // an explicit declaration can never widen this back to CASCADE; that\n // is deliberate until tenant-delete cascade is an explicit decision.\n const isTenantIdField =\n relationship.options?.__tenancy?.isTenantIdField === true;\n if (isTenantIdField) continue;\n\n const { action, declared } = resolveForeignKeyDeleteAction({\n declared: relationship.options?.onDelete,\n isConflictColumn: conflictColumns.has(column),\n isTenantIdField: false,\n });\n\n if (\n action === 'SET NULL' &&\n fields.get(relationship.fieldName)?.required\n ) {\n // Fail on the declaration, not later on a NOT NULL violation from the\n // engine — the message there names a column, not the decorator.\n throw ConfigurationError.invalidConfiguration(\n `${sourceClass}.${relationship.fieldName} onDelete: 'SET NULL'`,\n relationship.fieldName,\n \"a nullable field (mark it `nullable: true`, or use 'CASCADE' / 'RESTRICT')\",\n );\n }\n\n references.push({\n className: sourceClass,\n tableName,\n fieldName: relationship.fieldName,\n column,\n action,\n declared,\n });\n }\n }\n\n // Both forms are matched deliberately: an association row written before a\n // class was package-qualified still carries the simple `meta_type`. The\n // qualified form alone is unambiguous; the simple-name fallback can still\n // match a same-simple-name sibling class's row if it also shares a\n // `meta_id` — a real, not just theoretical, risk for a class declaring\n // `idType: 'text'` (non-UUID, not guaranteed globally unique), the same gap\n // `deleteSystemRows()` closed for `_smrt_contexts` / `_smrt_embeddings`\n // (review fix) by adding a class-name filter. Closing it here needs the\n // same STI-and-legacy-name-aware filter this module already builds for\n // `deleteSystemRows()` narrowed further to registry-unambiguous simple\n // names; tracked under #2419 alongside the other same-simple-name\n // collision gaps rather than reworked here.\n const metaTypes: string[] = [];\n const qualified = registry.getClass(className)?.qualifiedName;\n if (qualified) metaTypes.push(qualified);\n const simple = registry.getClass(className)?.name ?? className;\n if (!metaTypes.includes(simple)) metaTypes.push(simple);\n\n return {\n references,\n polymorphic,\n metaTypes,\n isEmpty: references.length === 0 && polymorphic.length === 0,\n };\n}\n\n/** Per-delete state shared by every level of the cascade. */\ninterface CascadeContext {\n db: DatabaseInterface;\n registry: CascadeRegistryView;\n /** `table:id` pairs already expanded, so a reference cycle terminates. */\n visited: Set<string>;\n /** Tables touched by the cascade, for read-cache invalidation. */\n affectedTables: Set<string>;\n /**\n * Qualified name of the class that owns each affected table, so the\n * caller can resolve *that* class's own `@smrt({ cache })` config —\n * cross-process cache invalidation is a per-class opt-in, and a table\n * cascaded into belongs to a different class than the one `delete()` was\n * called on.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/** Resolve a registry-recorded class name to its qualified form, when known. */\nfunction toQualifiedClassName(\n registry: CascadeRegistryView,\n className: string,\n): string {\n return registry.getClass(className)?.qualifiedName ?? className;\n}\n\n/**\n * Every value `_smrt_contexts.owner_class` / `_smrt_embeddings.object_class`\n * could plausibly hold for a row belonging to an id of `className` (review\n * fix): both name forms (qualified + simple — older rows predate package\n * qualification) of `className` itself, plus every other member of its STI\n * hierarchy sharing its table. A CASCADE-collected id can belong to any\n * concrete STI subclass of the declaring reference, which stamps its own\n * (more specific) runtime class name at write time, not the reference's.\n *\n * Narrowing by this set — instead of matching by id alone — closes a\n * cross-class collision: two unrelated classes using `idType: 'text'`\n * (non-UUID, not guaranteed globally unique) could otherwise share an id\n * value and have one's `remember()`/embeddings rows deleted by the other's\n * cascade.\n */\nfunction ownerClassCandidates(\n registry: CascadeRegistryView,\n className: string,\n): string[] {\n const stiBase = registry.getSTIBase(className) ?? className;\n const members = new Set<string>([\n className,\n stiBase,\n ...registry.getDescendants(stiBase),\n ]);\n\n const names = new Set<string>();\n for (const member of members) {\n names.add(member);\n const registered = registry.getClass(member);\n if (registered?.qualifiedName) names.add(registered.qualifiedName);\n if (registered?.name) names.add(registered.name);\n }\n return [...names];\n}\n\n/**\n * Build the `where` clause matching `column` against one or more ids.\n *\n * A single id uses equality so the planner can use a plain index; multiple ids\n * use the adapter's `in` operator.\n */\nfunction idPredicate(column: string, ids: string[]): Record<string, unknown> {\n return ids.length === 1 ? { [column]: ids[0] } : { [`${column} in`]: ids };\n}\n\n/**\n * Run a cascade statement against a *referencing* table, tolerating the\n * table (or an expected column) not existing in this database.\n *\n * The cascade plan is built from the in-process registry, which can carry a\n * class from any imported package — including one whose table this specific\n * database was never migrated to include (a partially adopted feature, a\n * package pulled in for its types, or, in a test process, a fixture some\n * other test file registered). A missing referencing table trivially has no\n * rows to act on, so the correct behaviour is identical to the table\n * existing and being empty — this must never abort an otherwise valid\n * delete. Any other failure (a real constraint violation, a lock timeout, a\n * genuine SQL error unrelated to the table's existence) still propagates.\n */\nasync function tolerateMissingTable<T>(\n operation: () => Promise<T>,\n fallback: T,\n context: { table: string; action: string },\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (classifyDatabaseError(error).kind === 'undefined_object') {\n logger.warn(\n `Cascade delete skipped ${context.action} on '${context.table}': ` +\n 'table or column not found in this database.',\n { error: error instanceof Error ? error.message : String(error) },\n );\n return fallback;\n }\n throw error;\n }\n}\n\nasync function selectIds(\n db: DatabaseInterface,\n tableName: string,\n column: string,\n ids: string[],\n): Promise<string[]> {\n const found: string[] = [];\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n const rows = await tolerateMissingTable(\n () => db.list(tableName, idPredicate(column, batch)),\n [] as Record<string, unknown>[],\n { table: tableName, action: 'CASCADE select' },\n );\n for (const row of rows) {\n const id = row?.id;\n if (typeof id === 'string' && id.length > 0) found.push(id);\n }\n }\n return found;\n}\n\nasync function deleteByIds(\n db: DatabaseInterface,\n tableName: string,\n ids: string[],\n): Promise<void> {\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () => db.delete(tableName, idPredicate('id', batch)),\n undefined,\n { table: tableName, action: 'CASCADE delete' },\n );\n }\n}\n\n/**\n * Remove the framework-managed side rows owned by the given object ids.\n *\n * `_smrt_contexts` and `_smrt_embeddings` are keyed by `(owner_class, owner_id)`\n * and `(object_class, object_id)` respectively. Matched by id *and* class\n * (review fix): id alone would let two unrelated classes using\n * `idType: 'text'` (non-UUID, not guaranteed globally unique) collide on a\n * shared id value and delete each other's memory/embeddings rows. `classNames`\n * is the STI-hierarchy-expanded candidate set from\n * {@link ownerClassCandidates} — the class column stores the *runtime*\n * constructor name, which for an STI hierarchy is a concrete subclass rather\n * than the class the cascade was planned from, so a single exact name is not\n * enough.\n *\n * A missing system table is not an error — an application database may predate\n * the table, and losing derived rows must never fail an otherwise valid delete.\n */\nasync function deleteSystemRows(\n db: DatabaseInterface,\n ids: string[],\n classNames: string[],\n): Promise<void> {\n const ownerIds = ids.filter(\n (id) =>\n typeof id === 'string' &&\n id.length > 0 &&\n id !== COLLECTION_OWNER_SENTINEL,\n );\n if (ownerIds.length === 0 || classNames.length === 0) return;\n\n for (const [table, idColumn, classColumn] of [\n [CONTEXTS_TABLE, 'owner_id', 'owner_class'],\n [EMBEDDINGS_TABLE, 'object_id', 'object_class'],\n ] as const) {\n for (const batch of chunkArray(ownerIds, IN_LIST_CHUNK_SIZE)) {\n try {\n await db.delete(table, {\n ...idPredicate(idColumn, batch),\n ...idPredicate(classColumn, classNames),\n });\n } catch (error) {\n logger.warn(\n `Failed to clean ${table} rows during cascade delete: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n }\n}\n\n/**\n * Resolve every reference pointing at `ids` of `className`, recursively.\n *\n * Does **not** delete the rows identified by `ids` — the caller owns that, so\n * `SmrtObject.delete()` keeps issuing its own final statement and its own\n * lifecycle hooks.\n */\nasync function resolveReferences(\n ctx: CascadeContext,\n className: string,\n tableName: string,\n ids: string[],\n depth: number,\n): Promise<void> {\n const pending = ids.filter((id) => {\n const key = `${tableName}:${id}`;\n if (ctx.visited.has(key)) return false;\n ctx.visited.add(key);\n return true;\n });\n if (pending.length === 0) return;\n\n if (depth > MAX_CASCADE_DEPTH) {\n throw DatabaseError.constraintViolation(\n `cascade delete from ${className} exceeded the maximum depth of ` +\n `${MAX_CASCADE_DEPTH}; check for a chain of onDelete: 'CASCADE' ` +\n 'references that never terminates',\n className,\n );\n }\n\n const plan = buildCascadePlan(ctx.registry, className);\n\n // SQL NO ACTION is immediate on every supported SMRT migration path, so the\n // app-side belt preflights it exactly like RESTRICT before any mutation.\n for (const reference of plan.references) {\n if (reference.action !== 'RESTRICT' && reference.action !== 'NO ACTION') {\n continue;\n }\n let remaining = 0;\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n remaining += await tolerateMissingTable(\n () =>\n ctx.db.count(\n reference.tableName,\n idPredicate(reference.column, batch),\n ),\n 0,\n { table: reference.tableName, action: `${reference.action} check` },\n );\n if (remaining > 0) break;\n }\n if (remaining > 0) {\n throw DatabaseError.constraintViolation(\n `${reference.className}.${reference.fieldName} ` +\n `${reference.declared ? 'declares' : 'resolves to'} onDelete: ` +\n `'${reference.action}' and ${remaining} row(s) still reference this ` +\n `${className}`,\n reference.column,\n );\n }\n }\n\n for (const reference of plan.references) {\n if (reference.action === 'SET NULL') {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () =>\n ctx.db.update(\n reference.tableName,\n idPredicate(reference.column, batch),\n { [reference.column]: null },\n ),\n undefined,\n { table: reference.tableName, action: 'SET NULL' },\n );\n }\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n continue;\n }\n\n if (reference.action !== 'CASCADE') continue;\n\n const childIds = await selectIds(\n ctx.db,\n reference.tableName,\n reference.column,\n pending,\n );\n if (childIds.length === 0) continue;\n\n await resolveReferences(\n ctx,\n reference.className,\n reference.tableName,\n childIds,\n depth + 1,\n );\n await deleteSystemRows(\n ctx.db,\n childIds,\n ownerClassCandidates(ctx.registry, reference.className),\n );\n await deleteByIds(ctx.db, reference.tableName, childIds);\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n }\n\n for (const association of plan.polymorphic) {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n const where: Record<string, unknown> = {\n ...idPredicate('meta_id', batch),\n };\n if (plan.metaTypes.length === 1) {\n where.meta_type = plan.metaTypes[0];\n } else {\n where['meta_type in'] = plan.metaTypes;\n }\n const result = await tolerateMissingTable(\n () => ctx.db.delete(association.tableName, where),\n undefined,\n {\n table: association.tableName,\n action: 'polymorphic association cleanup',\n },\n );\n if ((result?.affected ?? 0) > 0) {\n ctx.affectedTables.add(association.tableName);\n ctx.affectedTableClasses.set(\n association.tableName,\n toQualifiedClassName(ctx.registry, association.className),\n );\n }\n }\n }\n}\n\n/** Outcome of a cascade run, returned so the caller can invalidate caches. */\nexport interface CascadeResult {\n /** Tables whose rows were removed or nulled, excluding the target's own. */\n affectedTables: Set<string>;\n /**\n * Qualified class name that owns each entry in {@link affectedTables},\n * where resolvable — lets the caller check *that* class's own\n * cross-process cache config rather than only its own.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/**\n * Resolve every reference to `ids` of `className` and clean their framework\n * side rows, then hand control back so the caller can delete the rows.\n *\n * Callers are expected to run this on a transaction-bound `db` — see\n * {@link runCascadeDelete}, which owns that decision.\n */\nexport async function cascadeReferencesTo(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: { className: string; tableName: string; ids: string[] },\n): Promise<CascadeResult> {\n const ctx: CascadeContext = {\n db,\n registry,\n visited: new Set(),\n affectedTables: new Set(),\n affectedTableClasses: new Map(),\n };\n await resolveReferences(\n ctx,\n target.className,\n target.tableName,\n target.ids,\n 0,\n );\n await deleteSystemRows(\n db,\n target.ids,\n ownerClassCandidates(registry, target.className),\n );\n return {\n affectedTables: ctx.affectedTables,\n affectedTableClasses: ctx.affectedTableClasses,\n };\n}\n\ntype TransactionCapable = DatabaseInterface & {\n transaction?: <T>(\n this: DatabaseInterface,\n callback: (tx: DatabaseInterface) => Promise<T>,\n ) => Promise<T>;\n};\n\n/**\n * Run the cascade and the target row's own deletion atomically.\n *\n * When anything references the class and the adapter exposes `transaction()`,\n * the whole sequence runs inside one — including the caller's `deleteSelf`\n * statement, so a failure part-way through cannot leave the object deleted with\n * its junction rows intact (or vice versa). Adapters without transaction\n * support run the same statements sequentially; this is the documented\n * degradation, not a silent one.\n *\n * When nothing references the class there is nothing to keep consistent, and\n * the transaction is skipped — see the comment on that branch.\n *\n * @param db - Database the object is bound to\n * @param registry - Registry view used to build cascade plans\n * @param target - Class, table and id of the object being deleted\n * @param deleteSelf - Issues the target row's own `DELETE`, on the tx-bound db\n * @returns Tables affected by the cascade, for read-cache invalidation\n */\nexport async function runCascadeDelete(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: {\n className: string;\n tableName: string;\n /** An unsaved object has none; the cascade is then a no-op. */\n id: string | null | undefined;\n },\n deleteSelf: (db: DatabaseInterface) => Promise<void>,\n): Promise<CascadeResult> {\n const ids = target.id ? [target.id] : [];\n\n // Nothing references this class AND no polymorphic association class is\n // registered anywhere in the process. `plan.polymorphic` is unconditionally\n // every registered `SmrtPolymorphicAssociation` subclass — a `metaType`\n // column can point at any class at runtime, so there is no static metadata\n // to scope it by, unlike a typed `@foreignKey`/`@crossPackageRef`. This\n // branch is therefore common for a class with no incoming references in an\n // app with no polymorphic associations at all, but rare — not \"the\n // overwhelmingly common case\" — once even one polymorphic class exists\n // anywhere in the process, since every delete's plan then carries it.\n // Opening a transaction to wrap statements that cannot disagree with each\n // other would cost two extra round trips, and on single-connection adapters\n // it would serialize concurrent deletes behind the transaction queue. Order\n // the two statements instead: the row goes first, so a failure leaves\n // everything as it was, and the derived side rows follow under the\n // best-effort contract they already carry.\n if (buildCascadePlan(registry, target.className).isEmpty) {\n await deleteSelf(db);\n await deleteSystemRows(\n db,\n ids,\n ownerClassCandidates(registry, target.className),\n );\n return { affectedTables: new Set(), affectedTableClasses: new Map() };\n }\n\n const run = async (bound: DatabaseInterface): Promise<CascadeResult> => {\n const result = await cascadeReferencesTo(bound, registry, {\n className: target.className,\n tableName: target.tableName,\n ids,\n });\n await deleteSelf(bound);\n return result;\n };\n\n const transaction = (db as TransactionCapable).transaction;\n if (typeof transaction !== 'function') {\n return run(db);\n }\n\n return transaction.call<\n DatabaseInterface,\n [(tx: DatabaseInterface) => Promise<CascadeResult>],\n Promise<CascadeResult>\n >(db, run);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;AAY7C,IAAM,iBAAiB;;AAGvB,IAAM,mBAAmB;;;;;;AAOzB,IAAM,4BAA4B;;;;;;AAOlC,IAAM,oBAAoB;;;;;;;;AAgE1B,SAAgB,kBAAkB,OAA4C;CAC5E,OAAO,0BAA0B,KAAK;AACxC;AAEA,SAAS,8BAA8B,QAAuC;CAI5E,OAAO,OAAO,IAAI,UAAU,KAAK,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gCAAgB,IAAI,IAAI;EACxB,sCAAsB,IAAI,IAAI;CAChC;CACA,MAAM,kBACJ,KACA,OAAO,WACP,OAAO,WACP,OAAO,KACP,CACF;CACA,MAAM,iBACJ,IACA,OAAO,KACP,qBAAqB,UAAU,OAAO,SAAS,CACjD;CACA,OAAO;EACL,gBAAgB,IAAI;EACpB,sBAAsB,IAAI;CAC5B;AACF;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,iBACpB,IACA,UACA,QAMA,YACwB;CACxB,MAAM,MAAM,OAAO,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC;CAiBvC,IAAI,iBAAiB,UAAU,OAAO,SAAS,CAAC,CAAC,SAAS;EACxD,MAAM,WAAW,EAAE;EACnB,MAAM,iBACJ,IACA,KACA,qBAAqB,UAAU,OAAO,SAAS,CACjD;EACA,OAAO;GAAE,gCAAgB,IAAI,IAAI;GAAG,sCAAsB,IAAI,IAAI;EAAE;CACtE;CAEA,MAAM,MAAM,OAAO,UAAqD;EACtE,MAAM,SAAS,MAAM,oBAAoB,OAAO,UAAU;GACxD,WAAW,OAAO;GAClB,WAAW,OAAO;GAClB;EACF,CAAC;EACD,MAAM,WAAW,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAe,GAA0B;CAC/C,IAAI,OAAO,gBAAgB,YACzB,OAAO,IAAI,EAAE;CAGf,OAAO,YAAY,KAIjB,IAAI,GAAG;AACX"}
|
|
1
|
+
{"version":3,"file":"cascade.js","names":[],"sources":["../src/cascade.ts"],"sourcesContent":["/**\n * App-side referential integrity for `SmrtObject.delete()` (#2371).\n *\n * Same-package `@foreignKey` fields now emit database constraints where the\n * engine can enforce the declared policy. Cross-package references and older\n * schemas still rely on this application-side path. Before this module,\n * `delete()` removed the object's own row and nothing else: junction rows,\n * polymorphic association rows, `_smrt_embeddings` and `_smrt_contexts` entries\n * were all left pointing at an id that no longer resolved, and\n * `@foreignKey(..., { onDelete })` was metadata nobody read.\n *\n * This module implements those semantics in the application layer. It mirrors\n * what a DB-level constraint would do, deliberately including the parts that\n * make it *unlike* a model-layer delete:\n *\n * - Cascaded rows are removed with set-based statements. Their `beforeDelete` /\n * `afterDelete` hooks and interceptors do **not** run, and no change-feed\n * tombstone is written for them — exactly as `ON DELETE CASCADE` behaves.\n * Only the object `delete()` was called on runs the full lifecycle.\n * - Every delete runs inside a single transaction when the adapter exposes\n * one, including cleanup of framework-owned context and embedding rows, so\n * a partial cascade cannot survive a failure. A `metaType` column can point\n * at any class at runtime, so a polymorphic association class is always\n * plausibly relevant.\n *\n * ## Which references are followed\n *\n * A reference is any `@foreignKey` / `@crossPackageRef` field on a registered\n * class whose target resolves to the deleted object's class (or one of its\n * registered STI ancestors), plus the polymorphic `(metaType, metaId)` pair on\n * {@link SmrtPolymorphicAssociation} subclasses.\n *\n * The action comes from the field's declared `onDelete`. When it is not\n * declared, the default is derived from the referencing class's natural key:\n *\n * | Reference | Default when `onDelete` is absent |\n * |---|---|\n * | Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n * | Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n * | Ordinary same-package reference | `NO ACTION` (deletion is refused while references remain) |\n * | Every `@tenantId()` field | Excluded: tenant scope is not an ownership edge |\n *\n * The natural-key rule is what makes junction rows work without any\n * per-package annotation: a junction declares\n * `@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so\n * `content_id` identifies the row and the row cannot outlive the content it\n * links. An ordinary child (`Order.customerId`) is keyed by `(slug, context)`,\n * so it defaults to immediate `NO ACTION` unless it opts in with\n * `@foreignKey(Customer, { onDelete: 'CASCADE' })`.\n *\n * `@tenantId()` fields are excluded from the natural-key rule even though\n * `@happyvertical/smrt-tenancy` leads a tenant-scoped class's *default*\n * `conflictColumns` with the tenant column (#2360): the tenant column scopes\n * ownership, it does not identify the row the way a junction's foreign key\n * does, and it targets a class (`Tenant`) that is virtually always\n * referenced. Without this exclusion, deleting one `Tenant` row would\n * recursively CASCADE through every tenant-scoped table that has not\n * declared its own `conflictColumns` — the overwhelming majority. The field\n * is detected via the `__tenancy.isTenantIdField` marker `@tenantId()`\n * attaches to its own registration (`FieldMeta.__tenancy`, read structurally\n * so `smrt-core` never depends on `smrt-tenancy`). `@tenantId()` exposes no\n * `onDelete` option today, so this cannot currently be overridden per field.\n *\n * @see https://github.com/happyvertical/smrt/issues/2371\n * @module\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { classifyDatabaseError } from './db-errors.js';\nimport { ConfigurationError, DatabaseError } from './errors.js';\n// Type-only: erased at runtime, so it cannot re-enter the\n// `registry → object → cascade` import cycle.\nimport type { ObjectRegistry } from './registry.js';\nimport {\n normalizeForeignKeyAction,\n resolveForeignKeyDeleteAction,\n} from './schema/foreign-key-policy.js';\nimport type { ForeignKeyAction } from './schema/types.js';\nimport { chunkArray, IN_LIST_CHUNK_SIZE } from './utils/chunk.js';\nimport { toSnakeCase } from './utils/naming.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Referential action applied to rows pointing at a deleted object.\n *\n * Same vocabulary as SQL's `ON DELETE`, enforced by the framework before the\n * engine. `NO ACTION` is preflighted like an immediate restrictive action so\n * application-side and database-side enforcement agree.\n */\nexport type OnDeleteAction = ForeignKeyAction;\n\n/** Table holding framework-managed per-object memory entries. */\nconst CONTEXTS_TABLE = '_smrt_contexts';\n\n/** Table holding framework-managed per-object embedding vectors. */\nconst EMBEDDINGS_TABLE = '_smrt_embeddings';\n\n/**\n * Reserved `_smrt_contexts.owner_id` used by `SmrtCollection.remember()` for\n * collection-scoped memory. A real object id is a UUID and can never equal it,\n * but the guard keeps a malformed id from wiping every sibling's defaults.\n */\nconst COLLECTION_OWNER_SENTINEL = '__collection__';\n\n/**\n * Maximum number of cascade levels followed from the object `delete()` was\n * called on. A cycle between two classes that both declare `onDelete: 'CASCADE'`\n * is broken by the visited set; this bound catches unbounded *chains*.\n */\nconst MAX_CASCADE_DEPTH = 10;\n\n/** One reference that must be resolved before the target row can be removed. */\nexport interface CascadeReference {\n /** Registered name of the class holding the referencing column. */\n className: string;\n /** Table holding the referencing rows. */\n tableName: string;\n /** Field name (camelCase) on the referencing class. */\n fieldName: string;\n /** Column (snake_case) holding the reference. */\n column: string;\n /** Resolved action. `NO ACTION` is preflighted like an immediate RESTRICT. */\n action: OnDeleteAction;\n /** `true` when the action was declared rather than derived from the key. */\n declared: boolean;\n}\n\n/** A polymorphic association table that can point at any class. */\nexport interface CascadePolymorphicReference {\n /** Registered name of the association class. */\n className: string;\n /** Table holding the association rows. */\n tableName: string;\n}\n\n/** Everything that must happen before rows of one class can be deleted. */\nexport interface CascadePlan {\n /** Typed `@foreignKey` / `@crossPackageRef` references, action-resolved. */\n references: CascadeReference[];\n /** Polymorphic association tables that may point at this class. */\n polymorphic: CascadePolymorphicReference[];\n /** `meta_type` values that identify this class in an association row. */\n metaTypes: string[];\n /** `true` when nothing references this class and nothing has to be visited. */\n isEmpty: boolean;\n}\n\n/**\n * Read-only slice of `ObjectRegistry` this module needs.\n *\n * Taking it as a parameter — rather than importing the registry as a value —\n * keeps `cascade.ts` out of the `registry → object → cascade` import cycle,\n * and lets tests drive the planner from a hand-built registry.\n */\nexport type CascadeRegistryView = Pick<\n typeof ObjectRegistry,\n | 'getRelationshipMap'\n | 'getFields'\n | 'getConflictColumns'\n | 'getTableName'\n | 'getSelfReferableNames'\n | 'getClass'\n | 'getSTIBase'\n | 'getDescendants'\n>;\n\n/**\n * Normalize a declared `onDelete` value.\n *\n * Accepts any casing and both `SET NULL` and `SET_NULL`, matching what the\n * schema generator has always carried in the manifest. Returns `undefined` for\n * an unset or unrecognized value so the caller can fall back to the default.\n */\nexport function normalizeOnDelete(value: unknown): OnDeleteAction | undefined {\n return normalizeForeignKeyAction(value);\n}\n\nfunction isPolymorphicAssociationClass(fields: Map<string, unknown>): boolean {\n // The three columns `SmrtPolymorphicAssociation` contributes. Requiring all\n // of them keeps an unrelated class that happens to carry a `metaType` from\n // being treated as an association table.\n return fields.has('metaType') && fields.has('metaId') && fields.has('role');\n}\n\n/**\n * Build the cascade plan for one class.\n *\n * The plan is derived entirely from registry metadata, so it is valid for any\n * database the class is used against. It is rebuilt per delete rather than\n * cached: registration is incremental (manifests load lazily, tests register\n * classes between cases) and a stale plan would silently skip a table.\n *\n * @param registry - Registry view (`ObjectRegistry` satisfies it)\n * @param className - Class whose incoming references should be resolved\n */\nexport function buildCascadePlan(\n registry: CascadeRegistryView,\n className: string,\n): CascadePlan {\n // `className` is normally already qualified (delete() passes\n // getResolvedQualifiedName()), but a common same-package `@foreignKey('X')`\n // still stores its target as the bare simple name `X`. That still matches:\n // getSelfReferableNames() walks the full ancestor chain (self included) and\n // adds each ancestor's *simple* name via `getClass(ancestor)?.name`, so the\n // simple form is already in the seed set below, not just the loop's\n // qualified-variant augmentation.\n const targetNames = new Set(registry.getSelfReferableNames(className));\n for (const name of [...targetNames]) {\n const qualified = registry.getClass(name)?.qualifiedName;\n if (qualified) targetNames.add(qualified);\n }\n\n const references: CascadeReference[] = [];\n const polymorphic: CascadePolymorphicReference[] = [];\n\n for (const [sourceClass, relationships] of registry.getRelationshipMap()) {\n const fields = registry.getFields(sourceClass);\n\n if (isPolymorphicAssociationClass(fields)) {\n const tableName = registry.getTableName(sourceClass);\n if (tableName) {\n polymorphic.push({ className: sourceClass, tableName });\n }\n }\n\n if (relationships.length === 0) continue;\n\n let conflictColumns: Set<string> | undefined;\n\n for (const relationship of relationships) {\n if (\n relationship.type !== 'foreignKey' &&\n relationship.type !== 'crossPackageRef'\n ) {\n continue;\n }\n if (!targetNames.has(relationship.targetClass)) continue;\n\n // An explicit app-side-only relationship is archival metadata, not a\n // referential-integrity rule. Its identifier is deliberately allowed to\n // outlive the parent, so delete planning must not block, null, or remove\n // the retained row (#2413).\n if (\n relationship.type === 'foreignKey' &&\n relationship.options?.constraint === false\n ) {\n continue;\n }\n\n const tableName = registry.getTableName(sourceClass);\n if (!tableName) continue;\n\n const column = toSnakeCase(relationship.fieldName);\n if (!conflictColumns) {\n conflictColumns = new Set(registry.getConflictColumns(sourceClass));\n }\n\n // A `@tenantId()` field is a structural scoping marker, not a\n // junction/ownership key — it lands in `conflictColumns` only because\n // #2360 leads every tenant-scoped class's *default* natural key with\n // the tenant column, not because the referencing row is *identified*\n // by its tenant the way a junction row is identified by its parent.\n // Without this guard, deleting a `Tenant` would silently CASCADE\n // through the tenant column of every tenant-scoped class in the\n // schema that has not declared its own `conflictColumns` — the\n // overwhelming majority. `@tenantId()` exposes no `onDelete` today, so\n // an explicit declaration can never widen this back to CASCADE; that\n // is deliberate until tenant-delete cascade is an explicit decision.\n const isTenantIdField =\n relationship.options?.__tenancy?.isTenantIdField === true;\n if (isTenantIdField) continue;\n\n const { action, declared } = resolveForeignKeyDeleteAction({\n declared: relationship.options?.onDelete,\n isConflictColumn: conflictColumns.has(column),\n isTenantIdField: false,\n });\n\n if (\n action === 'SET NULL' &&\n fields.get(relationship.fieldName)?.required\n ) {\n // Fail on the declaration, not later on a NOT NULL violation from the\n // engine — the message there names a column, not the decorator.\n throw ConfigurationError.invalidConfiguration(\n `${sourceClass}.${relationship.fieldName} onDelete: 'SET NULL'`,\n relationship.fieldName,\n \"a nullable field (mark it `nullable: true`, or use 'CASCADE' / 'RESTRICT')\",\n );\n }\n\n references.push({\n className: sourceClass,\n tableName,\n fieldName: relationship.fieldName,\n column,\n action,\n declared,\n });\n }\n }\n\n // Both forms are matched deliberately: an association row written before a\n // class was package-qualified still carries the simple `meta_type`. The\n // qualified form alone is unambiguous; the simple-name fallback can still\n // match a same-simple-name sibling class's row if it also shares a\n // `meta_id` — a real, not just theoretical, risk for a class declaring\n // `idType: 'text'` (non-UUID, not guaranteed globally unique), the same gap\n // `deleteSystemRows()` closed for `_smrt_contexts` / `_smrt_embeddings`\n // (review fix) by adding a class-name filter. Closing it here needs the\n // same STI-and-legacy-name-aware filter this module already builds for\n // `deleteSystemRows()` narrowed further to registry-unambiguous simple\n // names; tracked under #2419 alongside the other same-simple-name\n // collision gaps rather than reworked here.\n const metaTypes: string[] = [];\n const qualified = registry.getClass(className)?.qualifiedName;\n if (qualified) metaTypes.push(qualified);\n const simple = registry.getClass(className)?.name ?? className;\n if (!metaTypes.includes(simple)) metaTypes.push(simple);\n\n return {\n references,\n polymorphic,\n metaTypes,\n isEmpty: references.length === 0 && polymorphic.length === 0,\n };\n}\n\n/** Per-delete state shared by every level of the cascade. */\ninterface CascadeContext {\n db: DatabaseInterface;\n registry: CascadeRegistryView;\n /** `table:id` pairs already expanded, so a reference cycle terminates. */\n visited: Set<string>;\n /** Tables touched by the cascade, for read-cache invalidation. */\n affectedTables: Set<string>;\n /**\n * Qualified name of the class that owns each affected table, so the\n * caller can resolve *that* class's own `@smrt({ cache })` config —\n * cross-process cache invalidation is a per-class opt-in, and a table\n * cascaded into belongs to a different class than the one `delete()` was\n * called on.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/** Resolve a registry-recorded class name to its qualified form, when known. */\nfunction toQualifiedClassName(\n registry: CascadeRegistryView,\n className: string,\n): string {\n return registry.getClass(className)?.qualifiedName ?? className;\n}\n\n/**\n * Every value `_smrt_contexts.owner_class` / `_smrt_embeddings.object_class`\n * could plausibly hold for a row belonging to an id of `className` (review\n * fix): both name forms (qualified + simple — older rows predate package\n * qualification) of `className` itself, plus every other member of its STI\n * hierarchy sharing its table. A CASCADE-collected id can belong to any\n * concrete STI subclass of the declaring reference, which stamps its own\n * (more specific) runtime class name at write time, not the reference's.\n *\n * Narrowing by this set — instead of matching by id alone — closes a\n * cross-class collision: two unrelated classes using `idType: 'text'`\n * (non-UUID, not guaranteed globally unique) could otherwise share an id\n * value and have one's `remember()`/embeddings rows deleted by the other's\n * cascade.\n */\nfunction ownerClassCandidates(\n registry: CascadeRegistryView,\n className: string,\n): string[] {\n const stiBase = registry.getSTIBase(className) ?? className;\n const members = new Set<string>([\n className,\n stiBase,\n ...registry.getDescendants(stiBase),\n ]);\n\n const names = new Set<string>();\n for (const member of members) {\n names.add(member);\n const registered = registry.getClass(member);\n if (registered?.qualifiedName) names.add(registered.qualifiedName);\n if (registered?.name) names.add(registered.name);\n }\n return [...names];\n}\n\n/**\n * Build the `where` clause matching `column` against one or more ids.\n *\n * A single id uses equality so the planner can use a plain index; multiple ids\n * use the adapter's `in` operator.\n */\nfunction idPredicate(column: string, ids: string[]): Record<string, unknown> {\n return ids.length === 1 ? { [column]: ids[0] } : { [`${column} in`]: ids };\n}\n\n/**\n * Run a cascade statement against a *referencing* table, tolerating the\n * table (or an expected column) not existing in this database.\n *\n * The cascade plan is built from the in-process registry, which can carry a\n * class from any imported package — including one whose table this specific\n * database was never migrated to include (a partially adopted feature, a\n * package pulled in for its types, or, in a test process, a fixture some\n * other test file registered). A missing referencing table trivially has no\n * rows to act on, so the correct behaviour is identical to the table\n * existing and being empty — this must never abort an otherwise valid\n * delete. Any other failure (a real constraint violation, a lock timeout, a\n * genuine SQL error unrelated to the table's existence) still propagates.\n */\nasync function tolerateMissingTable<T>(\n operation: () => Promise<T>,\n fallback: T,\n context: { table: string; action: string },\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (classifyDatabaseError(error).kind === 'undefined_object') {\n logger.warn(\n `Cascade delete skipped ${context.action} on '${context.table}': ` +\n 'table or column not found in this database.',\n { error: error instanceof Error ? error.message : String(error) },\n );\n return fallback;\n }\n throw error;\n }\n}\n\n/**\n * System-table cleanup may ignore an absent table for databases created before\n * that subsystem existed, but never a missing column in a table that does\n * exist. The shared `undefined_object` classification intentionally combines\n * both cases, so this security boundary must retain the narrower driver signal.\n */\nfunction normalizeMissingTableName(value: string): string {\n const unquoted = value.replace(/[\"'`[\\]]/g, '');\n return (unquoted.split('.').at(-1) ?? unquoted)\n .replace(/[^A-Za-z0-9_$-]/g, '')\n .toLowerCase();\n}\n\nfunction missingTableNames(messages: readonly string[]): string[] {\n const names: string[] = [];\n const patterns = [\n /no such table:\\s*([^\\s,;]+)/giu,\n /(?:relation|table)\\s+((?:\"[^\"]+\"(?:\\.\"[^\"]+\")*)|(?:[A-Za-z0-9_.$-]+))\\s+does not exist/giu,\n /table with name\\s+((?:\"[^\"]+\")|(?:[A-Za-z0-9_.$-]+))\\s+does not exist/giu,\n ];\n for (const message of messages) {\n for (const pattern of patterns) {\n for (const match of message.matchAll(pattern)) {\n if (match[1]) names.push(normalizeMissingTableName(match[1]));\n }\n }\n }\n return names;\n}\n\nfunction isMissingTableError(error: unknown, expectedTable: string): boolean {\n const classification = classifyDatabaseError(error);\n if (classification.kind !== 'undefined_object') return false;\n if (\n classification.sqlstate === '42703' ||\n classification.driverCode === '42703' ||\n classification.driverCodes.includes('42703')\n ) {\n return false;\n }\n const names = missingTableNames(classification.driverMessages);\n const expected = normalizeMissingTableName(expectedTable);\n return (\n names.length > 0 &&\n names.every((missingTableName) => missingTableName === expected)\n );\n}\n\nasync function tolerateMissingSystemTable<T>(\n operation: () => Promise<T>,\n fallback: T,\n context: { table: string; action: string },\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (!isMissingTableError(error, context.table)) throw error;\n logger.warn(\n `Cascade delete skipped ${context.action} on '${context.table}': ` +\n 'table not found in this database.',\n { error: error instanceof Error ? error.message : String(error) },\n );\n return fallback;\n }\n}\n\nasync function selectIds(\n db: DatabaseInterface,\n tableName: string,\n column: string,\n ids: string[],\n): Promise<string[]> {\n const found: string[] = [];\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n const rows = await tolerateMissingTable(\n () => db.list(tableName, idPredicate(column, batch)),\n [] as Record<string, unknown>[],\n { table: tableName, action: 'CASCADE select' },\n );\n for (const row of rows) {\n const id = row?.id;\n if (typeof id === 'string' && id.length > 0) found.push(id);\n }\n }\n return found;\n}\n\nasync function deleteByIds(\n db: DatabaseInterface,\n tableName: string,\n ids: string[],\n): Promise<void> {\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () => db.delete(tableName, idPredicate('id', batch)),\n undefined,\n { table: tableName, action: 'CASCADE delete' },\n );\n }\n}\n\n/**\n * Remove the framework-managed side rows owned by the given object ids.\n *\n * `_smrt_contexts` and `_smrt_embeddings` are keyed by `(owner_class, owner_id)`\n * and `(object_class, object_id)` respectively. Matched by id *and* class\n * (review fix): id alone would let two unrelated classes using\n * `idType: 'text'` (non-UUID, not guaranteed globally unique) collide on a\n * shared id value and delete each other's memory/embeddings rows. `classNames`\n * is the STI-hierarchy-expanded candidate set from\n * {@link ownerClassCandidates} — the class column stores the *runtime*\n * constructor name, which for an STI hierarchy is a concrete subclass rather\n * than the class the cascade was planned from, so a single exact name is not\n * enough.\n *\n * A missing system table is not an error — an application database may predate\n * the table. Every other cleanup failure propagates so the surrounding delete\n * transaction rolls back rather than orphaning tenant-sensitive recall data.\n */\nasync function deleteSystemRows(\n db: DatabaseInterface,\n ids: string[],\n classNames: string[],\n): Promise<void> {\n const ownerIds = ids.filter(\n (id) =>\n typeof id === 'string' &&\n id.length > 0 &&\n id !== COLLECTION_OWNER_SENTINEL,\n );\n if (ownerIds.length === 0 || classNames.length === 0) return;\n\n for (const [table, idColumn, classColumn] of [\n [CONTEXTS_TABLE, 'owner_id', 'owner_class'],\n [EMBEDDINGS_TABLE, 'object_id', 'object_class'],\n ] as const) {\n for (const batch of chunkArray(ownerIds, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingSystemTable(\n () =>\n db.delete(table, {\n ...idPredicate(idColumn, batch),\n ...idPredicate(classColumn, classNames),\n }),\n undefined,\n { table, action: 'framework-owned row cleanup' },\n );\n }\n }\n}\n\n/**\n * Resolve every reference pointing at `ids` of `className`, recursively.\n *\n * Does **not** delete the rows identified by `ids` — the caller owns that, so\n * `SmrtObject.delete()` keeps issuing its own final statement and its own\n * lifecycle hooks.\n */\nasync function resolveReferences(\n ctx: CascadeContext,\n className: string,\n tableName: string,\n ids: string[],\n depth: number,\n): Promise<void> {\n const pending = ids.filter((id) => {\n const key = `${tableName}:${id}`;\n if (ctx.visited.has(key)) return false;\n ctx.visited.add(key);\n return true;\n });\n if (pending.length === 0) return;\n\n if (depth > MAX_CASCADE_DEPTH) {\n throw DatabaseError.constraintViolation(\n `cascade delete from ${className} exceeded the maximum depth of ` +\n `${MAX_CASCADE_DEPTH}; check for a chain of onDelete: 'CASCADE' ` +\n 'references that never terminates',\n className,\n );\n }\n\n const plan = buildCascadePlan(ctx.registry, className);\n\n // SQL NO ACTION is immediate on every supported SMRT migration path, so the\n // app-side belt preflights it exactly like RESTRICT before any mutation.\n for (const reference of plan.references) {\n if (reference.action !== 'RESTRICT' && reference.action !== 'NO ACTION') {\n continue;\n }\n let remaining = 0;\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n remaining += await tolerateMissingTable(\n () =>\n ctx.db.count(\n reference.tableName,\n idPredicate(reference.column, batch),\n ),\n 0,\n { table: reference.tableName, action: `${reference.action} check` },\n );\n if (remaining > 0) break;\n }\n if (remaining > 0) {\n throw DatabaseError.constraintViolation(\n `${reference.className}.${reference.fieldName} ` +\n `${reference.declared ? 'declares' : 'resolves to'} onDelete: ` +\n `'${reference.action}' and ${remaining} row(s) still reference this ` +\n `${className}`,\n reference.column,\n );\n }\n }\n\n for (const reference of plan.references) {\n if (reference.action === 'SET NULL') {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () =>\n ctx.db.update(\n reference.tableName,\n idPredicate(reference.column, batch),\n { [reference.column]: null },\n ),\n undefined,\n { table: reference.tableName, action: 'SET NULL' },\n );\n }\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n continue;\n }\n\n if (reference.action !== 'CASCADE') continue;\n\n const childIds = await selectIds(\n ctx.db,\n reference.tableName,\n reference.column,\n pending,\n );\n if (childIds.length === 0) continue;\n\n await resolveReferences(\n ctx,\n reference.className,\n reference.tableName,\n childIds,\n depth + 1,\n );\n await deleteSystemRows(\n ctx.db,\n childIds,\n ownerClassCandidates(ctx.registry, reference.className),\n );\n await deleteByIds(ctx.db, reference.tableName, childIds);\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n }\n\n for (const association of plan.polymorphic) {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n const where: Record<string, unknown> = {\n ...idPredicate('meta_id', batch),\n };\n if (plan.metaTypes.length === 1) {\n where.meta_type = plan.metaTypes[0];\n } else {\n where['meta_type in'] = plan.metaTypes;\n }\n const result = await tolerateMissingTable(\n () => ctx.db.delete(association.tableName, where),\n undefined,\n {\n table: association.tableName,\n action: 'polymorphic association cleanup',\n },\n );\n if ((result?.affected ?? 0) > 0) {\n ctx.affectedTables.add(association.tableName);\n ctx.affectedTableClasses.set(\n association.tableName,\n toQualifiedClassName(ctx.registry, association.className),\n );\n }\n }\n }\n}\n\n/** Outcome of a cascade run, returned so the caller can invalidate caches. */\nexport interface CascadeResult {\n /** Tables whose rows were removed or nulled, excluding the target's own. */\n affectedTables: Set<string>;\n /**\n * Qualified class name that owns each entry in {@link affectedTables},\n * where resolvable — lets the caller check *that* class's own\n * cross-process cache config rather than only its own.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/**\n * Resolve every reference to `ids` of `className` and clean their framework\n * side rows, then hand control back so the caller can delete the rows.\n *\n * Callers are expected to run this on a transaction-bound `db` — see\n * {@link runCascadeDelete}, which owns that decision.\n */\nexport async function cascadeReferencesTo(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: { className: string; tableName: string; ids: string[] },\n): Promise<CascadeResult> {\n const ctx: CascadeContext = {\n db,\n registry,\n visited: new Set(),\n affectedTables: new Set(),\n affectedTableClasses: new Map(),\n };\n await resolveReferences(\n ctx,\n target.className,\n target.tableName,\n target.ids,\n 0,\n );\n await deleteSystemRows(\n db,\n target.ids,\n ownerClassCandidates(registry, target.className),\n );\n return {\n affectedTables: ctx.affectedTables,\n affectedTableClasses: ctx.affectedTableClasses,\n };\n}\n\ntype TransactionCapable = DatabaseInterface & {\n transaction?: <T>(\n this: DatabaseInterface,\n callback: (tx: DatabaseInterface) => Promise<T>,\n ) => Promise<T>;\n};\n\n/**\n * Run the cascade and the target row's own deletion atomically.\n *\n * When the adapter exposes `transaction()`, the whole sequence runs inside one\n * — including framework-owned row cleanup and the caller's `deleteSelf`\n * statement, so a failure part-way through cannot leave either side orphaned.\n * Adapters without transaction support run the same statements sequentially;\n * this is the documented degradation, not a silent one.\n *\n * @param db - Database the object is bound to\n * @param registry - Registry view used to build cascade plans\n * @param target - Class, table and id of the object being deleted\n * @param deleteSelf - Issues the target row's own `DELETE`, on the tx-bound db\n * @returns Tables affected by the cascade, for read-cache invalidation\n */\nexport async function runCascadeDelete(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: {\n className: string;\n tableName: string;\n /** An unsaved object has none; the cascade is then a no-op. */\n id: string | null | undefined;\n },\n deleteSelf: (db: DatabaseInterface) => Promise<void>,\n): Promise<CascadeResult> {\n const ids = target.id ? [target.id] : [];\n\n // Nothing references this class AND no polymorphic association class is\n // registered anywhere in the process. `plan.polymorphic` is unconditionally\n // every registered `SmrtPolymorphicAssociation` subclass — a `metaType`\n // column can point at any class at runtime, so there is no static metadata\n // to scope it by, unlike a typed `@foreignKey`/`@crossPackageRef`. This\n // branch is therefore common for a class with no incoming references in an\n // app with no polymorphic associations at all, but rare — not \"the\n // overwhelmingly common case\" — once even one polymorphic class exists\n // anywhere in the process, since every delete's plan then carries it.\n // Framework-owned context and embedding rows still need atomic cleanup even\n // when the registry has no typed or polymorphic references for this class.\n if (buildCascadePlan(registry, target.className).isEmpty) {\n const runWithoutReferences = async (\n bound: DatabaseInterface,\n ): Promise<CascadeResult> => {\n await deleteSystemRows(\n bound,\n ids,\n ownerClassCandidates(registry, target.className),\n );\n await deleteSelf(bound);\n return { affectedTables: new Set(), affectedTableClasses: new Map() };\n };\n const transaction = (db as TransactionCapable).transaction;\n if (typeof transaction !== 'function') return runWithoutReferences(db);\n return transaction.call<\n DatabaseInterface,\n [(tx: DatabaseInterface) => Promise<CascadeResult>],\n Promise<CascadeResult>\n >(db, runWithoutReferences);\n }\n\n const run = async (bound: DatabaseInterface): Promise<CascadeResult> => {\n const result = await cascadeReferencesTo(bound, registry, {\n className: target.className,\n tableName: target.tableName,\n ids,\n });\n await deleteSelf(bound);\n return result;\n };\n\n const transaction = (db as TransactionCapable).transaction;\n if (typeof transaction !== 'function') {\n return run(db);\n }\n\n return transaction.call<\n DatabaseInterface,\n [(tx: DatabaseInterface) => Promise<CascadeResult>],\n Promise<CascadeResult>\n >(db, run);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;AAY7C,IAAM,iBAAiB;;AAGvB,IAAM,mBAAmB;;;;;;AAOzB,IAAM,4BAA4B;;;;;;AAOlC,IAAM,oBAAoB;;;;;;;;AAgE1B,SAAgB,kBAAkB,OAA4C;CAC5E,OAAO,0BAA0B,KAAK;AACxC;AAEA,SAAS,8BAA8B,QAAuC;CAI5E,OAAO,OAAO,IAAI,UAAU,KAAK,OAAO,IAAI,QAAQ,KAAK,OAAO,IAAI,MAAM;AAC5E;;;;;;;;;;;;AAaA,SAAgB,iBACd,UACA,WACa;CAQb,MAAM,cAAc,IAAI,IAAI,SAAS,sBAAsB,SAAS,CAAC;CACrE,KAAK,MAAM,QAAQ,CAAC,GAAG,WAAW,GAAG;EACnC,MAAM,YAAY,SAAS,SAAS,IAAI,CAAC,EAAE;EAC3C,IAAI,WAAW,YAAY,IAAI,SAAS;CAC1C;CAEA,MAAM,aAAiC,CAAC;CACxC,MAAM,cAA6C,CAAC;CAEpD,KAAK,MAAM,CAAC,aAAa,kBAAkB,SAAS,mBAAmB,GAAG;EACxE,MAAM,SAAS,SAAS,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