Skip to content

Commit 76684a7

Browse files
fix(driver-sql): the orphan arm keeps a hash-shadow carrier whose key it could not read, never an orphan drop (#32430)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgHNGYL5R2Qt6GA5ZKKhvoKT)_ Fixes #32399 domain:server#2 · os-bill · session_01Utp6CaP1iy4RSEQbW6177G Clause-②: no - The orphan arm of `diffManagedIndexes`, on a #11627 hash-shadow carrier under an ObjectStack generated name whose generation expression could not be read: FROM `unmapped_index` / `drop_index`, categorized `destructive` (performed by `os migrate apply --allow-destructive`) TO kept, nothing offered. No authored key, wire shape, or non-destructive answer moves; the one thing withdrawn is an opt-in drop of a constraint whose key the planner could not read, which `isHashShadowCarrier`'s own contract already ruled out. A RESOLVED orphan carrier is still offered as the drop. Metadata-protocol: none Skills-docs: none. `git grep -i -E 'hash.?shadow|__hash|shadow carrier|orphan(ed)? index|drop_index' -- skills content/docs` (releases excluded) has 1 hit, `content/docs/deployment/cli.mdx` line 1182, the `drop_index` row of the index-drift table ("An index carrying ObjectStack's generated naming that metadata no longer declares"). It says what the op means, not that every such index gets it (runtime-managed partial and expression indexes were already excluded without a sentence there), so this change makes it no less true. ## 维护者速读 1. 改了什么:driver-sql 的 schema 差异比对里,"孤儿索引"这条规则遇到 MySQL/MariaDB 上读不出所哈希键的影子列唯一索引时,不再提议删除(destructive),改为保留、什么都不提议;读得出键的孤儿影子索引照旧提议删除。 2. 为什么改:读不出键就不知道删掉的是哪条唯一约束;`os migrate apply --allow-destructive` 会把它删掉,数据从此静默失去这条约束。加宽分支和重定义分支早已这样处理,只差孤儿分支。 3. 风险与回滚:只会把一条"提议删除"变成"保留",不新增任何操作;代价是这种读不出键、声明又确实已删掉的影子索引不再出现在计划里(与另两条分支相同的取舍:少一条发现,绝不丢一条约束)。回滚即还原本 PR。 4. 先看:`packages/drivers/driver-sql/src/schema-drift.ts` 里 `diffManagedIndexes` 第 3 段(孤儿分支)新加的一行守卫与注释。 5. 两分钟验证:`pnpm --filter @objectstack/driver-sql exec vitest run src/sql-driver-13015-shadow-carried-index-drift.test.ts`,预期 11 个过、2 个实库单元无 MySQL 时具名跳过(设 `OS_TEST_MYSQL_URL` 则 16 个全跑);读不出键的影子索引不出现在结果里,读得出键的那个仍是 `drop_index`。 6. 需要你做的:无,席位落地。 ## What changes `packages/drivers/driver-sql/src/schema-drift.ts`, section 3 of `diffManagedIndexes` (the orphan arm): one guard, `if (isHashShadowCarrier(p) && !p.shadowKey) continue;`, placed after the runtime-managed skip and before the orphan entry is built. It is the redefinition arm's guard, byte for byte, with the same load-bearing `!p.shadowKey` half: a carrier whose key was resolved is not exempted and is still offered as the orphan drop, described by the key it enforced. The widening arm (PR #32356) is untouched. This is the answer the other two arms already give an unresolved carrier, and the one `SqlDriver.resolveHashShadowKeys`' docblock promises ("`diffManagedIndexes` then reports NOTHING for it ... The degraded outcome is a missing finding, never a dropped constraint"). Before this change the orphan arm broke that promise. ## Why `isHashShadowCarrier` recognises a carrier by name alone, so it holds even when the generation expression cannot be read, and its jsdoc rules that a carrier "is never a thing this differ may propose destroying on a guess". PR #32356 applied that to the widening arm; the redefinition arm already had it. The orphan arm had no such exemption, so an unresolved carrier under any other generated name (a retired declaration, or a tenant-arm legacy name, which claims no carrier) was offered as `drop_index`, `destructive`. An operator running `os migrate apply --allow-destructive` would drop a unique constraint whose key nobody had read. ## Tests All in `packages/drivers/driver-sql/src/sql-driver-13015-shadow-carried-index-drift.test.ts`, the shared harness for shadow-carried index drift, as one new top-level `describe` plus one live cell (no new file): - An unresolved carrier no declaration names: no entry of any kind. In the same call, two colocated CONTROLs: a RESOLVED orphan carrier is still `unmapped_index` / `drop_index` / `destructive`, described as `UNIQUE (organization_id, gone)`, and the ordinary drifted unique is still `recreate_index`. - Outside the widening arm: an unresolved carrier under a tenant-arm legacy name (no `widenedBy`) is kept; the whole diff is empty. - CONTROL: the same carrier with its key read is still the orphan `drop_index`. - The widening arm's unresolved-carrier answer from PR #32356 is unchanged (kept, nothing offered). - Live MySQL cell: two retired shadow-carried UNIQUEs built by `initObjects`; one shadow is rebuilt with a generation expression that names no column (`UNHEX(SHA2('unreadable', 256))`), which `resolveHashShadowKeys` resolves to nothing. A fresh driver with neither declared: the resolved one is offered as `drop_index`, the unreadable one is not; after `applyMigrationEntries(drift, { allowDestructive: true })` the catalog still holds the unreadable index and no longer holds the resolved one. ## Acceptance notes - **"Kept and reported".** The card's expected text says the carrier is "kept and reported", and also that this is "the widening arm's answer after PR #32356". The widening arm's answer is kept with nothing in the plan, and so is the redefinition arm's; no report-only finding exists for an unresolved carrier on any arm (`DriftOp` has none, and `resolveHashShadowKeys` documents "reports NOTHING"). This PR gives the orphan arm exactly the widening arm's answer and adds no new finding kind. A report-only entry would be a new `DriftOp` member, an exported shape the CLI renders; it is named in the seat report as an open question, not built here. - **The trade.** A carrier whose declaration really is gone and whose key cannot be read is no longer listed at all, so its STORED generated column stays until the key is readable again. That is the same missing-finding trade the redefinition arm makes, chosen over a guessed drop. - **Overlap.** Open PR #32306 also edits `schema-drift.ts`, in the widening arm (section 1); this hunk is in section 3 only. Whichever merges second merges `origin/main` first. ## Verification Measured on `origin/main` `7d82b2dab` + this branch (head `1ead60236`), with a live MySQL 8.0.46 (`mysql:8.0`, the image CI's live job uses) in this container. <details><summary>Red first, on unfixed main (live MySQL 8.0.46)</summary> The card's first step: an unreadable carrier does reach the orphan arm on a live server. On `7d82b2dab` with only the new tests added, `OS_TEST_MYSQL_URL=… vitest run src/sql-driver-13015-shadow-carried-index-drift.test.ts`: `Tests 3 failed | 13 passed (16)`, live mysql RAN. The live cell's subject assertion received: ``` "kind": "unmapped_index", "category": "destructive", "actual": "UNIQUE (uniq_os32399_orphan_unreadable__hash)", "op": { "type": "drop_index", "indexName": "uniq_os32399_orphan_unreadable", ... } ``` The two pure-function subject pins failed the same way; every CONTROL and every pre-existing test passed. (A MariaDB 11.8 run was tried first: MariaDB keys a long TEXT unique natively and takes no shadow route, so the shadow cells, the pre-existing #13015 ones included, do not apply there.) </details> <details><summary>Green</summary> - The new file plus `sql-driver-widened-grant-key.test.ts` (the PR #32356 pins) and `sql-driver-13056-orphan-shadow-column-cleanup.test.ts`, live MySQL: `Test Files 3 passed (3)`, `Tests 49 passed (49)`, VERDICT `command-exit 0`. - `pnpm --filter @objectstack/driver-sql test` (no live URL): `Test Files 250 passed | 13 skipped (263)`, `Tests 4229 passed | 228 skipped (4457)`, VERDICT `command-exit 0`. - `pnpm --filter @objectstack/driver-sql run typecheck`: exit 0 (`tsc --listFiles` includes the test file). </details> <details><summary>Ablation (once)</summary> `node scripts/ablation-replace.mjs` on the committed head replaced the new guard line with a marker comment (anchor 1 → 0, blob `08055dc8f89c` → `c063c9a460c2`), live MySQL: `Tests 3 failed | 13 passed (16)`, the three subject pins (pure unresolved orphan, tenant-arm legacy name, live cell); every CONTROL and the widening-arm pin stayed green. Restored by the tool: blob back to `08055dc8f89c`, `git diff HEAD` empty. </details> <details><summary>Gates</summary> On `1ead60236` (the final tree; `git merge origin/main` before opening: already up to date at `7d82b2dab`): - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 66 commands over the 3 changed paths (200 changed lines, under the 3000 threshold). Each was run with its exit code recorded before any pipe. - First pass: 62 exited 0, 4 exited 3 (PREREQUISITE NOT MET, not findings): `check-plugin-teardown-shape --self-test` (its fixture commit was outside this shallow clone; the commit was fetched), and `check:dual-build-cjs-loads`, `check:lean-entry-closure`, `check:type-check-debt` (they read built output of packages outside driver-sql's closure; `pnpm turbo run build --concurrency=2`, 120 of 120 tasks, VERDICT `command-exit 0`). All four re-run: exit 0. - `node scripts/pm/dispatch-gates.mjs --ran`: **66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN**, exit 0. - `pnpm lint` (repo-wide `eslint . --no-inline-config`): exit 0. eslint over the two touched source files: exit 0. </details> **NOT MEASURED here:** MariaDB with a shadow carrier (MariaDB takes no shadow route for this shape, see above); the full dogfood battery (no `!` title and no `(narrowing)` arm). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No spec change.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (Repo-wide `pnpm lint`: exit 0.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (`## 维护者速读` is the maintainer's Chinese summary the dispatch rules ask for.) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CamgV1EYRYcyP8yQ5h --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CamgV1EYRYcyP8yQ5h)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent ba8e993 commit 76684a7

3 files changed

Lines changed: 200 additions & 0 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
---
4+
5+
fix(driver-sql): the differ's orphan arm keeps a hash-shadow carrier whose key it could not read, instead of offering it as a destructive drop (#32399)
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On MySQL (and anywhere a #11627 hash shadow carries a unique key over a long TEXT column), `os migrate plan` / `apply` no longer offer a `drop_index`, categorized `destructive`, for a shadow-carried unique under an ObjectStack generated name when the shadow's generation expression could not be read. What that index enforces is unknown, so it is kept and nothing is offered: the answer the widening arm and the redefinition arm already give such a carrier. An orphaned carrier whose key was read is still offered as the orphan drop, described by the key it enforced. Measured on a live MySQL 8.0: before this change the unreadable carrier was offered as `drop_index` and `os migrate apply --allow-destructive` removed it; after it, the carrier stays and the resolved one beside it is still dropped.

‎packages/drivers/driver-sql/src/schema-drift.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3113,6 +3113,16 @@ export function diffManagedIndexes(args: {
31133113
// (#4884 — the boot advised dropping `idx_sys_metadata_overlay_draft`, the
31143114
// partial UNIQUE enforcing draft-overlay uniqueness, on a healthy fresh DB).
31153115
if (isRuntimeManagedIndex(p, runtimeCreated, tenantField)) continue;
3116+
// A hash-shadow carrier whose generation expression could NOT be read
3117+
// (`shadowKey` unresolved) gets the answer the widening and redefinition
3118+
// arms above give it: kept, nothing offered. We know by name that it is a
3119+
// driver-owned UNIQUE, but not WHAT it hashes, and the remedy below is a
3120+
// DROP — {@link isHashShadowCarrier}: never destroyed on a guess. The
3121+
// degraded outcome is a missing finding, never a dropped constraint.
3122+
//
3123+
// ⛔ The `!p.shadowKey` half is load-bearing, as in the redefinition arm: a
3124+
// RESOLVED orphan carrier is still an orphan and still offered below.
3125+
if (isHashShadowCarrier(p) && !p.shadowKey) continue;
31163126
// Commit cd1348802: an orphaned shadow carrier is still an orphan — its declaration
31173127
// is gone, and `drop_index` is the right remedy — but the report must name
31183128
// the constraint it enforced, not the digest column it stored.

‎packages/drivers/driver-sql/src/sql-driver-13015-shadow-carried-index-drift.test.ts‎

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import {
5353
isHashShadowColumn,
5454
parseHashShadowKeyParts,
5555
type ExpectedIndex,
56+
type LegacyUniqueReplacement,
5657
type PhysicalIndex,
5758
} from './schema-drift.js';
5859
import { MYSQL_CELL, declareDialectCell } from './live-dialect-matrix.testkit.js';
@@ -413,3 +414,182 @@ declareDialectCell(MYSQL_CELL, 'shadow-carried index drift (#13015)', (cell) =>
413414
}, 60_000);
414415
});
415416
});
417+
418+
// ─────────────────────────────────────────────────────────────────────────
419+
// The orphan arm: an UNRESOLVED carrier is kept, never offered as a drop
420+
// ─────────────────────────────────────────────────────────────────────────
421+
422+
/**
423+
* `isHashShadowCarrier`'s promise — a carrier "is never a thing this differ may
424+
* propose destroying on a guess" — held on the redefinition arm (above: an
425+
* unresolved carrier under a DECLARED name reports nothing) and, since the
426+
* widening arm learnt it, under a superseded narrower key's name. It did not
427+
* hold on the orphan arm: an unresolved carrier under any OTHER generated name
428+
* was offered as `drop_index`, categorized `destructive`. Its key could not be
429+
* read, so what that drop would remove is unknown.
430+
*
431+
* The orphan arm now gives the widening arm's answer: kept, nothing offered.
432+
* Every "nothing" below sits beside a colocated control in the same call — the
433+
* drifted ordinary unique, and a RESOLVED orphan carrier that is still offered
434+
* as the drop it really is — so an empty answer for the subject cannot be read
435+
* as a differ that stopped reporting orphans, or shadows, altogether.
436+
*/
437+
describe('the orphan arm keeps an unresolved carrier and offers no drop', () => {
438+
/** A carrier under a generated name no declaration and no widening entry names. */
439+
const ORPHAN_NAME = 'uniq_os13015_probe_retired';
440+
const orphanCarrier = (shadowKey?: PhysicalIndex['shadowKey']): PhysicalIndex => ({
441+
name: ORPHAN_NAME,
442+
columns: [hashShadowColumnFor(ORPHAN_NAME)],
443+
unique: true,
444+
...(shadowKey ? { shadowKey } : {}),
445+
});
446+
/** The CONTROL carrier: retired too, but its key was read. */
447+
const RESOLVED_NAME = 'uniq_os13015_probe_gone';
448+
const resolvedOrphanCarrier: PhysicalIndex = {
449+
name: RESOLVED_NAME,
450+
columns: [hashShadowColumnFor(RESOLVED_NAME)],
451+
unique: true,
452+
shadowKey: [
453+
{ column: 'organization_id', nullSafe: false },
454+
{ column: 'gone', nullSafe: false },
455+
],
456+
};
457+
const forName = (entries: ReturnType<typeof diff>, name: string) =>
458+
entries.filter((e) => (e.op as any).indexName === name || (e.op as any).dropIndexNames?.includes(name));
459+
460+
it('is a carrier the orphan arm would otherwise reach: a generated name, plain and unique', () => {
461+
expect(isHashShadowCarrier(orphanCarrier())).toBe(true);
462+
expect(orphanCarrier().shadowKey).toBeUndefined();
463+
});
464+
465+
it('an unresolved carrier no declaration names: nothing offered, while the resolved one is still a destructive drop', () => {
466+
const entries = diff([declaredControl], [orphanCarrier(), resolvedOrphanCarrier, physicalControl]);
467+
// The subject: no drop_index, no entry of any kind.
468+
expect(forName(entries, ORPHAN_NAME)).toEqual([]);
469+
// CONTROL 1 — the resolved orphan carrier is still the orphan arm's.
470+
const gone = forName(entries, RESOLVED_NAME);
471+
expect(gone.map((e) => [e.kind, e.op.type, e.category])).toEqual([['unmapped_index', 'drop_index', 'destructive']]);
472+
expect(gone[0]!.actual).toBe('UNIQUE (organization_id, gone)');
473+
// CONTROL 2 — the ordinary drifted unique.
474+
expect(forName(entries, CONTROL_NAME).map((e) => e.op.type)).toEqual(['recreate_index']);
475+
expect(entries.length).toBe(2);
476+
});
477+
478+
it('outside the widening arm: an unresolved carrier under a tenant-arm legacy name is kept, not dropped', () => {
479+
// The field-level tenant retirement (no `widenedBy`) excludes every carrier
480+
// from its `present` set and claims none, so the carrier fell through to
481+
// the orphan arm.
482+
const legacy: LegacyUniqueReplacement = {
483+
column: 'v',
484+
legacyNames: [ORPHAN_NAME],
485+
replacement: declaredOrgUnique,
486+
legacyColumns: ['v'],
487+
};
488+
const entries = diffManagedIndexes({
489+
table: TABLE,
490+
expected: [declaredOrgUnique],
491+
legacy: [legacy],
492+
physical: [orphanCarrier(), carrier(healthyKey)],
493+
tenantField: 'organization_id',
494+
});
495+
expect(forName(entries, ORPHAN_NAME)).toEqual([]);
496+
expect(entries).toEqual([]);
497+
});
498+
499+
it('CONTROL: the same carrier with its key read is still offered as the orphan drop', () => {
500+
const entries = diff([], [orphanCarrier(healthyKey)]);
501+
expect(entries.map((e) => [e.op.type, e.category, (e.op as any).indexName])).toEqual([
502+
['drop_index', 'destructive', ORPHAN_NAME],
503+
]);
504+
});
505+
506+
it('the widening arm\'s unresolved-carrier answer is unchanged: kept, nothing offered', () => {
507+
const NARROW = 'uniq_os13015_probe_organization_id';
508+
const narrower: PhysicalIndex = { name: NARROW, columns: [hashShadowColumnFor(NARROW)], unique: true };
509+
const legacy: LegacyUniqueReplacement = {
510+
column: 'organization_id',
511+
legacyNames: [NARROW],
512+
replacement: declaredOrgUnique,
513+
legacyColumns: ['organization_id'],
514+
widenedBy: ['v'],
515+
};
516+
const entries = diffManagedIndexes({
517+
table: TABLE,
518+
expected: [declaredOrgUnique],
519+
legacy: [legacy],
520+
physical: [narrower, carrier(healthyKey)],
521+
tenantField: 'organization_id',
522+
});
523+
expect(entries).toEqual([]);
524+
});
525+
});
526+
527+
/**
528+
* Two retired full-value UNIQUEs over columns MySQL cannot key directly, so both
529+
* take the #11627 shadow route; one shadow is then rebuilt with a generation
530+
* expression that names no column, which is what an unreadable carrier looks
531+
* like to `resolveHashShadowKeys` (it resolves to nothing).
532+
*/
533+
const twoRetiredCarriers = (name: string, indexes: Array<'unreadable' | 'resolved'>) => ({
534+
name,
535+
fields: {
536+
unreadable: { type: 'text', maxLength: 1024 },
537+
resolved: { type: 'text', maxLength: 1024 },
538+
},
539+
indexes: indexes.map((f) => ({ fields: [f], unique: true as const, name: `uniq_${name}_${f}` })),
540+
});
541+
542+
declareDialectCell(MYSQL_CELL, 'unresolved carrier on the orphan arm', (cell) => {
543+
describe('an unresolved orphan carrier against the live catalog', () => {
544+
let driver: SqlDriver;
545+
afterEach(async () => {
546+
await driver?.disconnect().catch(() => {});
547+
});
548+
549+
const indexNames = async (table: string): Promise<string[]> => {
550+
const knex = (driver as any).knex;
551+
const idx = await knex
552+
.select('INDEX_NAME')
553+
.from('information_schema.STATISTICS')
554+
.where({ TABLE_SCHEMA: knex.client.database(), TABLE_NAME: table });
555+
return idx.map((i: any) => String(i.INDEX_NAME));
556+
};
557+
558+
it('is never offered as drop_index and survives "os migrate apply --allow-destructive"; the resolved one is dropped', async () => {
559+
const TABLE = 'os32399_orphan';
560+
const unreadable = `uniq_${TABLE}_unreadable`;
561+
const resolved = `uniq_${TABLE}_resolved`;
562+
const shadow = hashShadowColumnFor(unreadable);
563+
564+
driver = new SqlDriver(cell.config());
565+
await driver.initObjects([twoRetiredCarriers(TABLE, ['unreadable', 'resolved'])]);
566+
const knex = (driver as any).knex;
567+
await knex.raw(`ALTER TABLE \`${TABLE}\` DROP INDEX \`${unreadable}\``);
568+
await knex.raw(`ALTER TABLE \`${TABLE}\` DROP COLUMN \`${shadow}\``);
569+
await knex.raw(
570+
`ALTER TABLE \`${TABLE}\` ` +
571+
`ADD COLUMN \`${shadow}\` VARBINARY(32) GENERATED ALWAYS AS (UNHEX(SHA2('unreadable', 256))) STORED, ` +
572+
`ADD UNIQUE KEY \`${unreadable}\` (\`${shadow}\`)`,
573+
);
574+
await driver.disconnect();
575+
576+
// A FRESH driver (empty runtime ledger), metadata declaring neither index.
577+
const retired = twoRetiredCarriers(TABLE, []);
578+
driver = new SqlDriver(cell.config());
579+
await driver.initObjects([retired]);
580+
expect(await indexNames(TABLE)).toEqual(expect.arrayContaining([unreadable, resolved]));
581+
582+
const drift = await driver.detectManagedDrift([retired]);
583+
// CONTROL: the resolved carrier is read and offered as the orphan drop.
584+
const gone = drift.filter((d) => (d.op as any).indexName === resolved);
585+
expect(gone.map((d) => d.op.type)).toEqual(['drop_index']);
586+
// The subject: nothing offered for the carrier whose key could not be read.
587+
expect(drift.filter((d) => (d.op as any).indexName === unreadable)).toEqual([]);
588+
589+
await driver.applyMigrationEntries(drift, { allowDestructive: true });
590+
const after = await indexNames(TABLE);
591+
expect(after).toContain(unreadable);
592+
expect(after).not.toContain(resolved);
593+
}, 60_000);
594+
});
595+
});

0 commit comments

Comments
 (0)