diff --git a/.deploy/mta.yaml b/.deploy/mta.yaml index f2a9e0f0b..1acecd9f1 100644 --- a/.deploy/mta.yaml +++ b/.deploy/mta.yaml @@ -10,7 +10,7 @@ ID: tutorials-ims # Bump this on each release you deploy — it's the version shown by `cf mtas` # and in the mtar filename (tutorials-ims_.mtar). Deploy is manual: # `cd .deploy && mbt build && cf deploy mta_archives/tutorials-ims_.mtar -e ../deploy/.mtaext -f`. -version: 1.44.2 +version: 1.44.3 # Top-level parameters (overridable per-env via deploy/.mtaext). parameters: diff --git a/CLAUDE.md b/CLAUDE.md index 5821c3f64..0af1cff9a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -159,4 +159,4 @@ The load-bearing few. **Full detail for every relocated item → [tutorials-ims- - **External channels subsystem** — `Channels` entity (`db/channels.cds`) is the source of truth; re-ingest via `npm run seed-channels`; directory at `/channels` (baked by `fetch-channels` in `build:all`); verb-lane fill via `npm run promote-channels`; community items never land in `START_HERE`. → [channels.md](docs/developers/reference/channels.md). - **TechEd sessions subsystem (#2312)** — new `TechEd*` entities (`db/external/teched.cds`, NOT reused `CommunityEvents`), loaded via a **`using` side-effect** in `db/external-content.cds` (don't delete the import); RainFocus ingest (`POST https://events.rainfocus.com/api/sessions`, headers `rfapiprofileid`/`rfwidgetid` per venue from `RAINFOCUS_{TE26,TEV26}_PROFILE`/`_WIDGET` env — live-confirmed defaults baked in, IDs may rotate; speakers embedded in `participants[]`, tracks in `attributevalues[attribute=="Track"]`, offset-paginated); idempotent seed via `scripts/seed-teched.cjs`; public `/build/teched` feed; corrected fetcher + delta cron jobs shipped in #2332; `/teched/` page + island, KG projection, embeddings, and Devtoberfest cross-linking are later units. → [teched.md](docs/developers/reference/teched.md). - **Signed provenance envelope (#2245)** — `PROVENANCE_ENVELOPE_ENABLED` (DB config, default OFF, DEV-first); two anonymous Express endpoints (`/content/tutorials/:slug/provenance` and `/.well-known/tutorial-provenance/jwks.json`); signing key = `PROVENANCE_SIGNING_KEY` credstore secret (Ed25519 PKCS8 PEM); rotate via `/admin-ui/#secrets`. Fail-open. → gotchas.md "Signed provenance envelope". -- **Optimized draft deletion `draft_admin_integrity` is OFF (#2909 / #2993, CAP 10.2)** — `cds.fiori.draft_admin_integrity: false` in package.json (all profiles). It was briefly enabled but shipped to PROD WITHOUT the required HANA `ON DELETE CASCADE` constraints, orphaning draft rows and making missions un-editable (`DRAFT_ALREADY_EXISTS` / `Not Found`, no discard affordance) — the 2026-11-02 PROD outage. Disabled for all profiles; draft deletion uses the pre-10.2 per-row `after('DELETE')` child hooks + `after('DISCARD')` root reconcile. The real draft shadow tables are `ADMINSERVICE_*_DRAFTS` (NOT `com_sap_developers_ims_*_drafts`). Orphan sweep: `scripts/cleanup-draft-orphans.cjs --commit` (deletes draft rows whose `DraftAdministrativeData_DraftUUID` has no admin-data parent; preserves live drafts). Re-enabling the `dad` strategy is blocked on an unresolved HDI make-graph problem for the cascade `.hdbconstraint` (inline FK → error 8250014; standalone constraint → 8212001 on delta deploy) — tracked in #2993; the flag must stay OFF until that deploys cleanly to a real HANA container. → gotchas.md "Optimized draft deletion". Re-enable runbook: docs/developers/operations/draft-integrity-reenable.md. +- **Optimized draft deletion `draft_admin_integrity` is OFF (#2909 / #2993, CAP 10.2)** — `cds.fiori.draft_admin_integrity: false` in package.json (all profiles). It was briefly enabled but shipped to PROD WITHOUT the required HANA `ON DELETE CASCADE` constraints, orphaning draft rows and making missions un-editable (`DRAFT_ALREADY_EXISTS` / `Not Found`, no discard affordance) — the 2026-11-02 PROD outage. Disabled for all profiles; draft deletion uses the pre-10.2 per-row `after('DELETE')` child hooks + `after('DISCARD')` root reconcile. The real draft shadow tables are `ADMINSERVICE_*_DRAFTS` (NOT `com_sap_developers_ims_*_drafts`). Orphan sweep: `scripts/cleanup-draft-orphans.cjs --commit` (deletes draft rows whose `DraftAdministrativeData_DraftUUID` has no admin-data parent; preserves live drafts). Re-enable is in progress under #2993: constraints are CAP-native (`createDraftAdminDataConstraints` in `@sap/cds-compiler` 7.2.1, 46 × `NOT VALIDATED ON DELETE CASCADE`) — the real blocker was the project root deduping `@sap/cds-compiler` to 7.0.1 (no draft-constraint code); fixed by a `package.json` overrides pin. Build-level proof done (46 constraints emit locally); deploy-level proof (HANA delta deploy + preflight `verified (46/46)` + dad-hook audit) is pending. Flag stays OFF until the HANA deploy is green. → gotchas.md "Optimized draft deletion". Re-enable runbook: docs/developers/operations/draft-integrity-reenable.md. diff --git a/docs/developers/operations/draft-integrity-reenable.md b/docs/developers/operations/draft-integrity-reenable.md index 16dac409d..512d734d8 100644 --- a/docs/developers/operations/draft-integrity-reenable.md +++ b/docs/developers/operations/draft-integrity-reenable.md @@ -1,18 +1,22 @@ # Safely Re-enabling `draft_admin_integrity` on Production -**Status:** DEFERRED — This runbook documents the SAFE re-enable procedure for `cds.fiori.draft_admin_integrity`. The flag is currently **disabled** (`false` in `package.json`). Re-enable ONLY after all green checks — another outage is unacceptable. This runbook exists so it CAN be done safely when the decision is made; it is NOT an instruction to do it now. +**Status:** IN PROGRESS (build-level proof done; deploy-level pending live HANA) — This runbook documents the SAFE re-enable procedure for `cds.fiori.draft_admin_integrity`. The flag is currently **disabled** (`false` in `package.json`). Re-enable ONLY after all green checks — another outage is unacceptable. This runbook exists so it CAN be done safely when the decision is made; it is NOT an instruction to do it now. **Context:** - Issue #2909: introduced the flag (CAP 10.2) + missing cascade constraints → PROD outage. - Issue #2968: added the preflight check `srv/lib/draft-integrity-preflight.js`. - Issue #2992: disabled the flag for all profiles and fixed the preflight (it had queried non-existent `com_sap_developers_ims_*_drafts` names instead of the real `ADMINSERVICE_*_DRAFTS` discovered from `SYS.TABLE_COLUMNS`). - Issue #2994: added the orphan cleanup sweep `scripts/cleanup-draft-orphans.cjs`. -- Issue #2993 (this work): added the build-time FK injection `scripts/patch-draft-cascade-constraints.cjs`, the gate test `test/admin-drafts-cascade-gate.test.js`, and this runbook. +- Issue #3003: reverted a hand-rolled constraint attempt (`scripts/patch-draft-cascade-constraints.cjs`) that blocked all MTA deploys (HDI errors 8250014 / 8212001 / 8212012). Hand-rolling is the rejected approach; do not reintroduce it. +- Issue #2993 (this work): pinned `@sap/cds-compiler` to 7.2.1 (root had deduped to 7.0.1, which has no draft-constraint code) so CAP emits the 46 native cascade constraints through the `hdbmigrationtable` build path; added the gate test `test/admin-drafts-cascade-gate.test.js`. **Key facts:** -- The inline FK (`FOREIGN KEY ... ON DELETE CASCADE` inside the `COLUMN TABLE (...)` body) is created **ENFORCED** by HANA — `NOT VALIDATED` is an `ALTER TABLE` affordance only and cannot be specified inline. This means orphaned draft rows **must be swept BEFORE the constraint-bearing HDbtable is deployed**, or HANA will reject the deploy. +- CAP's compiler (`createDraftAdminDataConstraints` in `@sap/cds-compiler` 7.2.1, `lib/transform/forRelationalDB.js`) emits the draft cascade constraints **natively** when `cds.fiori.draft_admin_integrity: true` + non-plain `sqlDialect`. The `package.json` `overrides` pin (`"@sap/cds-compiler": "7.2.1"`) ensures the right compiler is used; without it the root deduped to 7.0.1 (no draft constraint code). +- There are exactly **46 constraints**, one per `*_drafts` shadow table: `ON DELETE CASCADE`, **NOT VALIDATED**, ENFORCED, INITIALLY DEFERRED. FK: `AdminService__drafts.DraftAdministrativeData_DraftUUID → DRAFT_DraftAdministrativeData(DraftUUID)`. +- The constraints are **NOT VALIDATED** — pre-existing orphan rows do **not** block the deploy. The old "sweep orphans before deploy" premise was specific to hand-rolled ENFORCED inline FKs (reverted in #3003) and is void for the native path. - `CDS_*` env-var overrides do NOT reach `cds.fiori.draft_admin_integrity` on deployed builds — only the baked `package.json` value counts. -- Preflight is HANA-only and fail-open; SQLite unit tests do not require cascade FKs. +- Constraint generation is independent of `cds.features.assert_integrity` (the global FK switch). Do not enable that flag; it is a non-goal. +- Preflight is HANA-only and fail-open; SQLite unit tests do not require cascade constraints. --- @@ -22,58 +26,59 @@ - [ ] You have `cf login` credentials for the target environment (DEV first, then PROD). - [ ] Node.js 22+ and `npm` are installed locally. - [ ] `@sap/cds-dk` is globally available (`cds --version`). +- [ ] `cds build --production` emits 46 `AdminService.*_drafts_DraftAdministrativeData.hdbconstraint` files into `gen/db` (build-level proof; verified locally in #2993 Task 1). --- -## Step 1: Sweep Orphaned Drafts (Dry-Run First) +## Step 1: Verify Build Emits 46 Constraints -The inline FK is ENFORCED — HANA will reject deploying the constraint if orphaned draft rows already exist in the schema. Sweep orphans **before** deploying the constraint-bearing build. +Confirm the local build produces the 46 native cascade constraints. **This does NOT require live HANA.** -**Locally, with credentials bound to the target environment:** +```bash +npm run build:all +# or for the CAP-only build: +cds build --production +``` -1. Set up the service binding (one-time): - ```bash - npm run bind:setup # if this is your first hybrid run - ``` +After the build, count the constraint files: -2. Run a dry-run to inspect any orphans: - ```bash - npx cds bind --exec -- node scripts/cleanup-draft-orphans.cjs --dry-run - ``` +```bash +ls gen/db/src/gen/ | grep -c '\.hdbconstraint$' +``` -3. **Expected output:** Zero orphans found: - ``` - Scanning for orphaned drafts... - Found 0 orphaned draft rows. (All clean.) - ``` +**Expected:** `46` + +If the count is wrong: +- Confirm `@sap/cds-compiler` resolves to 7.2.1 (`node -e "console.log(require('@sap/cds-compiler/package.json').version)"` from the project root). +- Confirm `package.json` has `"overrides": { "@sap/cds-compiler": "7.2.1" }` (or equivalent `resolutions`). +- Run `npm install` and retry. -4. **If orphans are found**, inspect them (the script prints details) and decide whether to proceed. If you expect orphans from the #2909 outage: - - Commit/note the findings. - - Run WITHOUT `--dry-run` to delete: - ```bash - npx cds bind --exec -- node scripts/cleanup-draft-orphans.cjs --commit - ``` - - Verify the count matches the dry-run scan. - - Re-run dry-run to confirm zero before proceeding. +**Do NOT proceed to Step 2 if the count is not 46.** --- -## Step 2: Deploy with Cascade Constraints (Flag Still `false`) +## Step 2: Deploy to Target HANA (Constraints, Flag Still `false`) -The Task 1 patch `scripts/patch-draft-cascade-constraints.cjs` already injects `ON DELETE CASCADE` foreign keys into the 46 draft tables in the generated `gen/db/src/gen/AdminService.*_drafts.hdbtable` files. +The constraints are **NOT VALIDATED** — they deploy safely over any existing schema, even if orphaned draft rows are present. No pre-sweep is required as a deploy precondition. -**On the target environment (DEV or PROD), after Step 1 confirms zero orphans:** +Before deploying, crack the mtar archive and confirm the `.hdbconstraint` files are present (same pattern as the Step 3.5 admin-bundle check in `scripts/check-shipped-admin-bundle.cjs`): -1. Ensure the MTA includes the latest `cds build --production` output with the patched constraints. -2. Deploy the MTA as usual (e.g., `npm run deploy -- --env dev` or via CI/CD): - ```bash - npm run build:all - cd .deploy && mbt build && cf deploy mta_archives/*.mtar -e ../deploy/dev.mtaext -f - ``` -3. The FK is enforced — a clean schema (zero orphans from Step 1) is the precondition for the deploy to succeed. -4. Verify deployment success and CAP service startup. +```bash +# After mbt build completes: +unzip -l .deploy/mta_archives/*.mtar | grep hdbconstraint | wc -l +``` + +**Expected:** `46` -**Note:** The constraints land on every build already (while `draft_admin_integrity` is `false`). This step ensures they have deployed to the target environment HANA schema with a clean baseline. +Deploy to DEV first: + +```bash +export CAP_BASE_URL="https://tutorial-system-dev-tutorials-srv.cfapps.eu10-005.hana.ondemand.com" +npm run build:all +cd .deploy && mbt build && cf deploy mta_archives/*.mtar -e ../deploy/dev.mtaext -f +``` + +**Verify deployment success and CAP service startup before proceeding.** --- @@ -83,99 +88,132 @@ After deployment, the CAP service logs startup messages. Look for the preflight **Expected log:** ``` -[draft-integrity-preflight] verified (N/N) +[draft-integrity-preflight] verified (46/46) ``` -where N is the count of verified draft tables (typically 46 for Admin/Mission/Group/Author services + compositions). + +The preflight discovers tables from `SYS.TABLE_COLUMNS` at runtime — it does not use a hardcoded list. **If you see a WARN instead:** ``` [draft-integrity-preflight] ⚠ missing: ``` -**STOP.** The constraints are incomplete or not deployed. Do not proceed to Step 4. Investigate: -- Is the MTA's `gen/db` module serving the patched HDbtable files? -- Did the HANA HDI deployment succeed (check `cf logs --recent`)? -- Run `cds build --production` locally and verify `gen/db/src/gen/AdminService.*_drafts.hdbtable` files contain the `ON DELETE CASCADE` clause. +**STOP.** The constraints are incomplete or not deployed. Investigate: +- Is the mtar's `gen/db` module serving the `.hdbconstraint` files? Re-check Step 2 — was the mtar verified to contain 46 `.hdbconstraint` files before deploy? +- Did the HANA HDI deployment succeed? Check `cf logs --recent`. +- Confirm `@sap/cds-compiler` version in the deployed build (check package-lock.json on the branch that was built). ---- +**Do NOT proceed to Step 4 until the preflight logs `verified (46/46)`.** -## Step 4: Run the Gate Test (Mission Draft Lifecycle) +### Optional: baseline orphan check -The gate test `test/admin-drafts-cascade-gate.test.js` verifies that Mission draftEdit + discard leaves zero orphaned child drafts. +The NOT VALIDATED constraints mean pre-existing orphans do not block deployment. However, running a dry-run gives a clean baseline reading for the smoke step later: -**Locally:** ```bash -npx vitest run test/admin-drafts-cascade-gate.test.js +npm run bind:setup # if this is your first hybrid run +npx cds bind --exec -- node scripts/cleanup-draft-orphans.cjs --dry-run ``` -**Expected:** All tests pass (green), including: -- Draft creation, edit, and discard lifecycle. -- Zero orphaned `Missions.drafts` rows after discard. -- Zero orphaned `CompletionPathItems.drafts` rows after parent discard. - -**If the test fails,** re-examine Step 1–3. Do NOT proceed to Step 5 until this test is green. +This is informational only — it is not a deploy gate. --- -## Step 5: Flip the Flag in `package.json` - -**ONLY after Steps 1–4 are green on the target environment**, update the flag: +## Step 4: Flip the Flags in `package.json` -1. Edit `package.json`: - - Line ~461: find the `"cds": { "fiori": { ... } }` block and set `"draft_admin_integrity": true`. - - Line ~486: find the `"[development]": { "cds": { "fiori": { ... } } }` block and set `"draft_admin_integrity": true`. +**ONLY after Steps 1–3 are green on DEV**, update the three flags: -2. Example (before): +1. Edit `package.json` — find the `"cds": { "fiori": { ... } }` block (two occurrences: top-level and `[development]`) and set: ```json "cds": { "fiori": { - "draft_admin_integrity": false - } - } - ``` - Example (after): - ```json - "cds": { - "fiori": { - "draft_admin_integrity": true + "draft_admin_integrity": true, + "draft_orphan_cleanup": true + }, + "drafts": { + "deleteStrategy": "dad" } } ``` -3. Commit and push the change: +2. Commit and push: ```bash git add package.json - git commit -m "feat(config): enable draft_admin_integrity globally (#2993)" + git commit -m "feat(config): enable draft_admin_integrity + orphan_cleanup + dad (#2993)" git push origin ``` -4. Run a fresh build with the flag ON: +3. Rebuild and redeploy DEV: ```bash npm run build:all + cd .deploy && mbt build && cf deploy mta_archives/*.mtar -e ../deploy/dev.mtaext -f ``` -5. Deploy to the target environment: +--- + +## Step 5: Audit `after('DISCARD')` / `after('DELETE')` Reconcile Hooks Under `dad` + +**This step is PROD-blocking.** CAP's `dad` (Draft Admin Data) delete strategy changes which event handlers fire during draft deletion — the DB cascade may bypass app-level reconcile hooks. + +This project has custom reconcile handlers: +- `srv/lib/completion-reconcile.js` +- `srv/lib/pipeline-log-reconciler.js` +- `srv/lib/topic-cluster-reconcile.js` + +These are tested in `test/admin-drafts-discard-reconcile.test.js` under the flag-OFF path. Under `dad`, verify they still fire: + +1. Run the existing reconcile test suite: ```bash - cd .deploy && mbt build && cf deploy mta_archives/*.mtar -e ../deploy/dev.mtaext -f + npx vitest run test/admin-drafts-discard-reconcile.test.js ``` + This is a SQLite-level test and is flag-agnostic — passing it is necessary but not sufficient. + +2. **Add a HANA-level test** (or perform a manual verification on DEV) confirming each `after('DISCARD')` / `after('DELETE')` reconcile side effect still fires after a `dad` draft discard. The SQLite gate test cannot catch a bypass; HANA is required. + +**Do NOT proceed to Step 6 (PROD) until the hook audit on DEV is confirmed.** + +--- + +## Step 6: Run the Gate Test (Mission Draft Lifecycle) + +The gate test `test/admin-drafts-cascade-gate.test.js` verifies that Mission draftEdit + discard leaves zero orphaned child drafts. This test runs against local SQLite — it confirms business logic under the flag, not the deployed HANA schema. The Step 3 preflight and Step 5 hook audit cover the HANA side. + +```bash +npx vitest run test/admin-drafts-cascade-gate.test.js +``` + +**Expected:** All tests pass, including: +- Draft creation, edit, and discard lifecycle. +- Zero orphaned `Missions.drafts` rows after discard. +- Zero orphaned `CompletionPathItems.drafts` rows after parent discard. + +**If the test fails,** re-examine Steps 1–5. Do NOT proceed to Step 7 until this test is green. --- -## Step 6: Smoke Test – Mission Discard on Deployed Environment +## Step 7: Smoke Test – Mission Discard on Deployed DEV -After the re-deployed service is running with the flag `true`, verify the behavior end-to-end: +After the re-deployed DEV service is running with the flags `true`, verify end-to-end: 1. **Via Admin UI** (`/admin-ui/#/admin/missions`): - - Create or open an existing Mission draft. - - Edit it (add a step, change the title, etc.). - - Click **Discard** (or equivalent button). - - Expected: Discard succeeds; no orphaned rows left in `Missions.drafts` or child composition tables. + - Open an existing Mission draft (or create one). + - Edit it (change the title or add a step). + - Click **Discard** (or equivalent). + - Expected: Discard succeeds; no orphaned rows in `Missions.drafts` or child composition tables. -2. **Verify no errors in the server logs:** +2. **Verify in the server logs:** ```bash - cf logs --recent | grep -i error + cf logs --recent | grep -i "error\|draft" ``` -3. **If discard fails or errors appear,** rollback the flag to `false`, redeploy, and investigate the error. Escalate to the team. +3. **If discard fails or errors appear,** roll back (see Rollback Plan below) and investigate before attempting PROD. + +--- + +## Environment Order + +**Always test DEV first (Steps 1–7), then repeat Step 2 → Step 5 on PROD.** + +- **DEV:** Lower risk; catch any logic gaps before production. +- **PROD:** Only after DEV smoke passes for at least 2–4 hours without incident. --- @@ -183,10 +221,12 @@ After the re-deployed service is running with the flag `true`, verify the behavi If any step fails or the deployed service encounters errors: -1. Revert the flag to `false` in `package.json` (Steps 1–2): +1. Revert the flags in `package.json`: ```json - "draft_admin_integrity": false + "draft_admin_integrity": false, + "draft_orphan_cleanup": false ``` + (Remove `deleteStrategy: dad` or revert to its prior value.) 2. Commit, push, and redeploy: ```bash @@ -197,18 +237,16 @@ If any step fails or the deployed service encounters errors: cd .deploy && mbt build && cf deploy mta_archives/*.mtar -e ../deploy/.mtaext -f ``` -3. The enforced constraints remain in the schema but the flag controls whether the runtime relies on them. With the flag `false` the app-level reconcile path runs instead, so the deployed constraints are dormant but harmless. +3. The cascade constraints remain in the schema but are inert without the flag — no orphan risk. The app-level reconcile path resumes. -4. Investigate the root cause before attempting re-enable again. Involve the team. - ---- - -## Environment Order - -**Always test DEV first, then PROD.** +4. If orphaned drafts accumulated during the flag-ON window, sweep them: + ```bash + npx cds bind --exec -- node scripts/cleanup-draft-orphans.cjs --dry-run + # Review output, then: + npx cds bind --exec -- node scripts/cleanup-draft-orphans.cjs --commit + ``` -- **DEV:** Lower risk; catch any logic gaps before production. -- **PROD:** Only after DEV smoke test passes for at least 2–4 hours without incident. +5. Investigate and involve the team before retrying. --- @@ -218,7 +256,8 @@ If any step fails or the deployed service encounters errors: - **#2968:** Added the preflight check `srv/lib/draft-integrity-preflight.js`. - **#2992:** Disabled the flag for all profiles and fixed the preflight (queried non-existent `com_sap_developers_ims_*_drafts` instead of real `ADMINSERVICE_*_DRAFTS` from `SYS.TABLE_COLUMNS`). - **#2994:** Added the orphan cleanup sweep `scripts/cleanup-draft-orphans.cjs`. -- **#2993:** Added the build-time FK injection `scripts/patch-draft-cascade-constraints.cjs`, the gate test `test/admin-drafts-cascade-gate.test.js`, and this runbook. +- **#3003:** Reverted hand-rolled constraint script (`scripts/patch-draft-cascade-constraints.cjs`) — blocked MTA deploys with HDI errors 8250014 / 8212001 / 8212012; do not reintroduce. +- **#2993 (this work):** Pinned `@sap/cds-compiler` to 7.2.1 so CAP emits 46 native `NOT VALIDATED` cascade constraints through the `hdbmigrationtable` build path; added gate test; rewrote this runbook. --- diff --git a/docs/superpowers/plans/2026-11-13-draft-admin-integrity-reenable.md b/docs/superpowers/plans/2026-11-13-draft-admin-integrity-reenable.md new file mode 100644 index 000000000..a485cfd0c --- /dev/null +++ b/docs/superpowers/plans/2026-11-13-draft-admin-integrity-reenable.md @@ -0,0 +1,251 @@ +# Draft Admin Integrity Re-enable Implementation Plan (#2993) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Deliver CAP 10.2's Optimized Draft Deletion end-to-end — native `NOT VALIDATED` cascade constraints on all 46 `*_drafts` tables flowing through our `.hdbmigrationtable` build, `draft_admin_integrity` + `draft_orphan_cleanup` + `deleteStrategy: dad` re-enabled, with a `dad` handler-firing audit proven on real HANA. + +**Architecture:** CAP's compiler already emits the 46 `DraftAdministrativeData_DraftUUID → DRAFT_DraftAdministrativeData(DraftUUID)` cascade constraints (`NOT VALIDATED`) under a full `to.hdi` compile. The one unknown is why they do not surface through our `to.hana`/`.hdbmigrationtable` delta path; Task 1 diagnoses and fixes that. Everything after is config flips gated on real-HANA verification, in the order: constraints-deployed → preflight-green → flag-on → handler-audit. + +**Tech Stack:** SAP CAP (`@sap/cds@10.2.2`, `@sap/cds-dk@10.2.0`, compiler 7.2.1), SAP HANA Cloud (HDI), MTA/mbt deploy, Vitest, Node 22. + +**Spec:** `docs/superpowers/specs/2026-11-13-draft-admin-integrity-reenable-design.md` + +## Global Constraints + +- Branch off fresh `origin/DEV`; PR targets **DEV**, never main. Never deploy a feature branch. +- `CDS_*` env overrides do NOT reach these flags — only baked `package.json` / `.cdsrc.json` values count. +- Do NOT enable `cds.features.assert_integrity` (model-wide FKs — explicit non-goal). +- Do NOT hand-author `.hdbconstraint` files or reintroduce `scripts/patch-draft-cascade-constraints.cjs` (rejected approach B; reverted in #3003). If native output cannot flow, **stop and escalate** — do not hand-roll. +- Authoritative count: **46** draft cascade constraints, `ON DELETE CASCADE`, `NOT VALIDATED`, one per `*_drafts` table. +- Flags stay OFF in `package.json` until constraints are verified present on the target HANA schema (the #2909 anti-pattern is flag-on-without-constraints). +- Real draft shadow tables are `ADMINSERVICE_*_DRAFTS`; the draft admin parent is `DRAFT_DraftAdministrativeData`. +- Deploy hygiene: `cf target` before push; pause sap-devs scheduler during long deploys; clean Hugo tree (#2886). + +## Review Focus + +- **Pre-existing orphans at deploy time** — constraints are `NOT VALIDATED`, so an orphan-laden schema must still deploy without error (covered by Task 3's deploy + Task 2's build asserting `NOT VALIDATED`). +- **`dad` bypassing `after('DISCARD')` reconcile** — rollup correctness could silently regress; the SQLite gate test cannot see it (Task 5 HANA-level audit). +- **`dad` bypassing `after('DELETE')` child reconcile on active-entity delete** — same class, delete path rather than discard (Task 5). +- **Preflight reading flag-on but constraints absent** — must WARN (not pass) so a bad deploy is caught before serving (Task 4). +- **Non-mission draft entities (Tutorials, Groups, Steps)** — the cascade must cover all 46 tables, not just Missions; a partial set leaves other entities corruptible (Task 2 count assertion = 46). + +--- + +### Task 1: Make native draft cascade constraints flow through the production build + +**Files:** +- Investigate (read-only): `node_modules/@sap/cds-dk/lib/build/plugins/hana/{index.js,2migration.js}`, `node_modules/@sap/cds-dk/node_modules/@sap/cds/lib/compile/cdsc.js`, `node_modules/@sap/cds-dk/node_modules/@sap/cds-compiler/lib/transform/forRelationalDB.js` +- Likely modify (one of): `.cdsrc.json` (journaling/compile config), `package.json` (dependency bump), or `patches/` (minimal `patch-package` shim) — determined by the diagnosis +- No test file (exit criterion is a build-artifact assertion, Step 4) + +**Interfaces:** +- Produces: a `cds build --production` that writes 46 `AdminService.*_drafts_DraftAdministrativeData.hdbconstraint` files into `gen/db/src/gen/`, each `ON DELETE CASCADE … NOT VALIDATED`. Tasks 2–3 consume this build output. + +- [ ] **Step 1: Reproduce the gap.** Set `cds.fiori.draft_admin_integrity: true` in `package.json` (both blocks), run `CDS_ENV=production npx cds build --production`, confirm `find gen -name '*DraftAdministrativeData*.hdbconstraint' | wc -l` = 0. This is the known failing baseline. + +- [ ] **Step 2: Diagnose which path drops the constraints.** The generator (`forRelationalDB.js:348`) runs only if `sqlDialect !== 'plain'` AND `options.draft_admin_integrity === true`. The full `to.hdi` compile emits all 46; our build uses `.hdbmigrationtable` via `cds.compile.to.hana` → `to.hdi.migration` (3-arg delta, `cdsc.js:154` option-flatten). Instrument the option object reaching the compiler in the migration path (temporary logging in a tmp-dir script that loads cds-dk's compiler — NOT by editing node_modules; that is blocked). Rank-ordered suspects: (a) `@cds.persistence.journal` interaction, (b) option-flatten at `cdsc.js:154`, (c) cds-dk 10.2.0 / compiler 7.2.1 gap needing a version bump or `patch-package` shim. + +- [ ] **Step 3: Apply the narrowest fix that satisfies Step 4.** Config change (a/b) preferred; dependency bump or `patch-package` shim (c) only if config cannot. If a cds-dk/cds bump is used, re-verify the committed `cds-caching+2.1.0.patch` still applies (CLAUDE.md gotcha) and run `npm test -- test/admin-drafts-cascade-gate.test.js`. **If none of (a)–(c) yields the exit criterion without hand-rolling, STOP and escalate to the user — do not proceed.** + +- [ ] **Step 4: Verify the exit criterion.** +Run: `CDS_ENV=production npx cds build --production && find gen -name '*DraftAdministrativeData*.hdbconstraint' | wc -l` +Expected: `46`. Then confirm one file contains `ON DELETE CASCADE` and `NOT VALIDATED` (not `VALIDATED`/`ENFORCED`-only): +Run: `grep -l 'NOT VALIDATED' gen/db/src/gen/AdminService.Missions_drafts_DraftAdministrativeData.hdbconstraint` +Expected: the file path (match found). + +- [ ] **Step 5: Revert the `draft_admin_integrity` flag back to `false`** in both `package.json` blocks (the build change from Step 3 stays; the flag flip was only to prove the build). Confirm `grep -c '"draft_admin_integrity": false' package.json` = 2. + +- [ ] **Step 6: Commit** (build-config change only, flags still off) + +```bash +git add .cdsrc.json package.json patches/ 2>/dev/null +git commit -m "build(#2993): surface native draft cascade constraints in hdbmigrationtable build" +``` + +--- + +### Task 2: Build-artifact test asserting the 46 NOT VALIDATED cascades + +**Files:** +- Create: `test/draft-cascade-build.test.js` +- Depends on Task 1's build output + +**Interfaces:** +- Consumes: Task 1's `cds build` producing 46 draft `.hdbconstraint`s. +- Produces: a CI-runnable guard that the constraints exist and are `NOT VALIDATED` — prevents silent regression of Task 1. + +- [ ] **Step 1: Write the failing test.** A Vitest test that runs (or reads a committed fixture of) the production build's draft constraint files and asserts count and shape. Because a full `cds build` in a unit test is slow, compile in-process via cds-dk's compiler with `draft_admin_integrity: true` + `sqlDialect: 'hana'` (pattern proven in the spike probe) and assert on the emitted `.hdbconstraint` strings. + +```javascript +import { describe, it, expect } from 'vitest'; +// loads cds-dk's compiler, compiles ['db','srv'], collects *.hdbconstraint +describe('#2993 native draft cascade constraints', () => { + it('emits 46 DraftAdministrativeData ON DELETE CASCADE constraints', () => { + const draftCascades = compileAndCollectDraftCascades(); // array of constraint strings + expect(draftCascades.length).toBe(46); + }); + it('emits them NOT VALIDATED (deploy-safe over existing orphans)', () => { + const draftCascades = compileAndCollectDraftCascades(); + for (const c of draftCascades) { + expect(c).toMatch(/ON DELETE CASCADE/); + expect(c).toMatch(/NOT VALIDATED/); + } + }); +}); +``` + +- [ ] **Step 2: Run to verify it fails** if Task 1 is incomplete. +Run: `npm test -- test/draft-cascade-build.test.js` +Expected: PASS once Task 1 landed (if run before Task 1's fix, count ≠ 46 → FAIL). + +- [ ] **Step 3: Implement the `compileAndCollectDraftCascades()` helper** in the test file — resolve cds-dk's `@sap/cds-compiler`, `cds.load(['db','srv'])`, `compiler.to.hdi(csn, { draft_admin_integrity: true, sqlDialect: 'hana' })`, filter keys ending `.hdbconstraint` whose content matches `DraftAdministrativeData` + `CASCADE`. + +- [ ] **Step 4: Run to verify it passes.** +Run: `npm test -- test/draft-cascade-build.test.js` +Expected: PASS (both assertions). + +- [ ] **Step 5: Commit** + +```bash +git add test/draft-cascade-build.test.js +git commit -m "test(#2993): assert 46 NOT VALIDATED draft cascade constraints emit" +``` + +--- + +### Task 3: Deploy constraints to DEV HANA (flags still OFF) — REQUIRES LIVE ENV + +**Files:** +- No source change; this is a deploy + artifact-verification task. Requires `cf login` to DEV. + +**Interfaces:** +- Consumes: Task 1 build output. Produces: 46 constraints present on DEV HANA schema; precondition for Task 4. + +- [ ] **Step 1: Confirm clean baseline (informational).** `npx cds bind --exec -- node scripts/cleanup-draft-orphans.cjs --dry-run` → record orphan count. (Not a gate — constraints are `NOT VALIDATED` — but informs Task 5 expectations.) + +- [ ] **Step 2: Full build + deploy to DEV** per CLAUDE.md canonical local deploy (`npm run build:all` then `mbt build` + `cf deploy … -e ../deploy/dev.mtaext -f`), wrapped in `scripts/quiet-run.sh`. `cf target` first; confirm DEV space. + +- [ ] **Step 3: Verify constraints landed in the mtar AND the schema.** Crack the mtar (as Step 3.5 admin-bundle check does) to confirm the 46 `.hdbconstraint`s shipped. Then on DEV HANA via `cds bind`: query `SYS.REFERENTIAL_CONSTRAINTS` for FKs on `ADMINSERVICE_*_DRAFTS` referencing `DRAFT_DraftAdministrativeData`. +Expected: 46 constraints present, `IS_VALIDATED = 'FALSE'`. + +- [ ] **Step 4: Confirm no deploy error over existing orphans** (proves `NOT VALIDATED` behavior). If Step 1 found orphans, the successful deploy is the evidence. Record in the PR. + +--- + +### Task 4: Verify preflight reports verified (46/46) on DEV — REQUIRES LIVE ENV + +**Files:** +- Read: `srv/lib/draft-integrity-preflight.js` (existing `checkDraftCascadeConstraints`, `wireDraftIntegrityPreflight`) +- Modify only if the preflight's discovery misses the real count + +**Interfaces:** +- Consumes: Task 3's deployed constraints. Produces: green preflight — the gate that authorizes Task 5's flag flip. + +- [ ] **Step 1: Read DEV CAP startup logs** (`cf logs tutorials-srv --recent`) after Task 3's deploy. The flag is still OFF, so the preflight may report the informational "flag off" path — confirm the constraint-discovery query itself returns 46 (add a one-off diagnostic log or query `SYS.TABLE_COLUMNS`/`SYS.REFERENTIAL_CONSTRAINTS` directly via `cds bind`). + +- [ ] **Step 2: If discovery count ≠ 46, fix the preflight discovery** (the stale 27-entry `DRAFT_TABLES` list is deprecated; discovery must come from the live catalog). Add/adjust so it reports `verified (46/46)` once the flag is on. + +- [ ] **Step 3: Commit any preflight fix** + +```bash +git add srv/lib/draft-integrity-preflight.js +git commit -m "fix(#2993): preflight discovers all 46 draft cascade tables" +``` + +--- + +### Task 5: Audit `dad` handler-firing + HANA-level reconcile test — REQUIRES LIVE ENV + +**Files:** +- Create: `test/admin-drafts-dad-reconcile.hybrid.test.js` (HANA-bound, via `cds bind --exec`) +- Read: `test/admin-drafts-discard-reconcile.test.js` (existing SQLite reconcile test to mirror), `srv/lib/completion-reconcile.js`, `srv/lib/pipeline-log-reconciler.js`, `srv/lib/topic-cluster-reconcile.js` + +**Interfaces:** +- Consumes: Task 4 green preflight. Produces: proof that `after('DISCARD')`/`after('DELETE')` reconcile side effects still fire under `dad`. PROD-blocking gate. + +- [ ] **Step 1: Write the failing HANA-level test.** Mirror `admin-drafts-discard-reconcile.test.js`'s seed/assert strategy (seed a user whose rollup heals on reconcile), but run against real HANA via `cds bind --exec` with `deleteStrategy: dad` active. Assert the reconcile side effect (user rollup heals to COMPLETED after a Mission draft discard) still occurs. + +```javascript +// test/admin-drafts-dad-reconcile.hybrid.test.js — run via npm run test:hybrid +it('fires MISSION reconcile when a Mission draft is discarded under dad', async () => { + // seed active mission + user at COMPLETED-eligible state + // draftEdit then DISCARD the mission draft + // assert reconcile ran: user rollup === 'COMPLETED' +}); +``` + +- [ ] **Step 2: Run against HANA with dad temporarily on** (via `cds bind --exec` + a scoped env/config enabling `dad` for the test run). +Expected: establishes whether reconcile fires or is bypassed. If bypassed → the test FAILS, exposing the regression. + +- [ ] **Step 3: If `dad` bypasses the hooks, add an explicit reconcile trigger** on the draft-delete path that `dad` preserves (e.g. an `after('DELETE')` on `DRAFT.DraftAdministrativeData` or the service-level discard handler), so reconcile fires regardless of strategy. Keep the pre-10.2 hooks for the flat fallback. + +- [ ] **Step 4: Run to verify it passes.** +Run: `npm run test:hybrid -- test/admin-drafts-dad-reconcile.hybrid.test.js` +Expected: PASS (reconcile fires under dad). + +- [ ] **Step 5: Commit** + +```bash +git add test/admin-drafts-dad-reconcile.hybrid.test.js srv/ +git commit -m "test(#2993): prove dad draft discard still fires rollup reconcile on HANA" +``` + +--- + +### Task 6: Flip the flags + deleteStrategy, redeploy DEV, gate green — REQUIRES LIVE ENV + +**Files:** +- Modify: `package.json` (both `cds.fiori` blocks) — set `draft_admin_integrity: true`, add `draft_orphan_cleanup: true`; set `cds.drafts.deleteStrategy: dad` (placement following existing fiori-config convention) + +**Interfaces:** +- Consumes: Tasks 3 (constraints deployed), 4 (preflight green), 5 (hooks proven). This is the only task that turns on runtime behavior. + +- [ ] **Step 1: Set the flags.** `draft_admin_integrity: true` + `draft_orphan_cleanup: true` in both `package.json` fiori blocks; add `deleteStrategy: dad`. Confirm `grep -c '"draft_admin_integrity": true' package.json` = 2. + +- [ ] **Step 2: Run the SQLite gate test** (flag-agnostic, must stay green). +Run: `npm test -- test/admin-drafts-cascade-gate.test.js` +Expected: PASS (zero child draft orphans after Mission draftEdit→discard). + +- [ ] **Step 3: Full build + deploy to DEV** (`scripts/quiet-run.sh`, `cf target` first). + +- [ ] **Step 4: Verify preflight now logs verified (46/46)** (not WARN) in DEV startup logs. +Run: `cf logs tutorials-srv --recent | grep draft-integrity-preflight` +Expected: `verified (46/46)`. + +- [ ] **Step 5: DEV smoke.** Via `cds bind`, perform a real Mission draftEdit→discard, then query `ADMINSERVICE_COMPLETIONPATHITEMS_DRAFTS` for rows with the discarded `DraftAdministrativeData_DraftUUID`. +Expected: zero orphaned child draft rows on real HANA. + +- [ ] **Step 6: Commit** + +```bash +git add package.json +git commit -m "feat(#2993): re-enable draft_admin_integrity + orphan_cleanup + dad strategy" +``` + +--- + +### Task 7: Rewrite runbook + correct CLAUDE.md gotcha + +**Files:** +- Rewrite: `docs/developers/operations/draft-integrity-reenable.md` +- Modify: `CLAUDE.md` ("Optimized draft deletion" gotcha) + +**Interfaces:** +- Consumes: the verified sequence from Tasks 1–6. Produces: docs matching reality. + +- [ ] **Step 1: Rewrite `draft-integrity-reenable.md`.** Remove Steps 1–2's hand-rolled ENFORCED-FK / pre-sweep premise and all references to `scripts/patch-draft-cascade-constraints.cjs` (does not exist; reverted #3003). Document the native `NOT VALIDATED` path and the verified ordering: build-change → deploy constraints (flags off) → preflight green → flag flip → dad hook audit. + +- [ ] **Step 2: Correct the CLAUDE.md gotcha.** State: constraints are CAP-native and `NOT VALIDATED`; the real blocker was the `to.hana`/`.hdbmigrationtable` build-format path (not HDI make-graph errors 8250014/8212001, not hand-authoring). Update the #2993 status line. + +- [ ] **Step 3: Commit** + +```bash +git add docs/developers/operations/draft-integrity-reenable.md CLAUDE.md +git commit -m "docs(#2993): rewrite re-enable runbook for native NOT VALIDATED path" +``` + +--- + +## Notes on execution + +Tasks 1, 2, 7 are workstation-local (no HANA). Tasks 3–6 **require a live DEV HANA + `cf login`** and cannot be verified locally — they are the honest ceiling of what can be done without the environment. Task 1 may **stop-and-escalate** if no non-hand-rolled fix satisfies its exit criterion. Task 5 may surface a real `dad` regression requiring a handler change (Step 3). Do not flip any flag (Task 6) until Tasks 3–5 are green on DEV. diff --git a/docs/superpowers/specs/2026-11-13-draft-admin-integrity-reenable-design.md b/docs/superpowers/specs/2026-11-13-draft-admin-integrity-reenable-design.md new file mode 100644 index 000000000..ab763257e --- /dev/null +++ b/docs/superpowers/specs/2026-11-13-draft-admin-integrity-reenable-design.md @@ -0,0 +1,99 @@ +# Design: Re-enable `draft_admin_integrity` with native cascade constraints + orphan cleanup (#2993) + +**Date:** 2026-11-13 +**Status:** Proposed — awaiting approval +**Issue:** [#2993](https://github.com/sap-tutorials/tutorials-ims/issues/2993) +**Size:** Project (multi-step, spans config + build pipeline + real-HANA verification) + +--- + +## Intent and the why + +CAP 10.2's "Optimized Draft Deletion" (`cds.fiori.draft_admin_integrity`) was enabled in #2909 **without its database half ever deploying** — the runtime began deleting only the `DraftAdministrativeData` record and trusting a DB `ON DELETE CASCADE` that did not exist. Every mission draft activate/discard orphaned child draft rows, making missions un-editable in PROD (2026-11-02 outage). #2992 disabled the flag and fixed the preflight; #3003 reverted a hand-rolled-constraint attempt that blocked all MTA deploys. + +This work delivers the **whole feature, correctly**: CAP's native draft cascade constraints flowing through our build, the `dad`-strategy runtime behavior re-enabled on top of them, **and** `draft_orphan_cleanup` as defense-in-depth so a future gap can never silently corrupt drafts again. + +**Why the whole feature (not just orphan cleanup):** the decision is to adopt the optimization CAP intends, not just stop the bleeding. Orphan cleanup alone keeps missions editable but leaves draft deletion on the slow per-table `flat` strategy; the full feature gives single-cascade deletion (`dad`) *and* a self-healing safety net. + +## Goals + +1. CAP's native draft cascade `.hdbconstraint`s (46, one per `*_drafts` table) are generated **and actually land in the deployed MTA** on a real HANA container. +2. `cds.fiori.draft_admin_integrity: true` re-enabled (all profiles) **only after** the constraints are verified deployed via the fixed preflight. +3. `cds.fiori.draft_orphan_cleanup: true` enabled as a permanent safety net, independent of the cascade. +4. The gate test proves Mission draftEdit→discard leaves **zero** orphaned child draft rows. +5. The outage is structurally impossible to repeat: flag-on without constraints-present is caught before serving. + +## Non-goals + +- Enabling the global `cds.features.assert_integrity` DB-constraints switch (model-wide FKs on all ~146 associations). The spike proved the draft cascade is **independent** of it; we do not touch it. +- Reworking the orphan cleanup sweep script (`scripts/cleanup-draft-orphans.cjs`, #2994) — it stays as the manual emergency tool. +- Changing draft table names or the draft model. + +## Anti-goals (what would make this a failure even if it "works") + +- Flipping `draft_admin_integrity: true` again while the constraints are not verifiably present on the target HANA schema. This is the exact #2909 mistake; the preflight gate exists to make it impossible. +- Hand-authoring `.hdbconstraint` files. The spike proved CAP generates them natively and `NOT VALIDATED`; hand-rolling re-enters the #3003 HDI make-graph failure. If CAP's native output cannot be made to flow, we **stop and escalate**, we do not hand-roll. +- A deploy that blocks on the constraints (the #3003 regression). + +## Constraints + +- **Verification requires a real HANA delta deploy.** No local/SQLite build can prove the constraints flow through the `.hdbmigrationtable` path or that HDI accepts them on a delta deploy. DEV HANA is the first real test. +- **`CDS_*` env overrides do not reach these flags** (verified: neither build-time nor runtime). Only baked `package.json` / `.cdsrc.json` values count. +- **DEV/main branching:** feature branch → PR to **DEV**, not main. Never deploy a feature branch; deploy from fresh `origin/DEV`. +- **Deploy hygiene:** `cf target` before push; pause the sap-devs scheduler during long deploys; clean Hugo working tree (#2886 Step 0.5). + +## Approaches considered + +### A. Native CAP constraints through the build + `dad` + orphan cleanup — **CHOSEN** +Make CAP's native `createDraftAdminDataConstraints` output flow through our `.hdbmigrationtable` build, deploy it `NOT VALIDATED`, verify via preflight, then flip `draft_admin_integrity: true` and enable `draft_orphan_cleanup: true`. +- **Trades off:** carries one genuinely unresolved engineering risk — the constraints generate under the full `to.hdi` compile but were **not observed** surfacing through our `to.hana`/hdbmigrationtable delta path in the spike. Resolving that (config vs. cds-dk behavior) is the core task. +- **Why chosen:** it is the only approach that delivers the whole feature using CAP's own, correctly-formed (`NOT VALIDATED`, deploy-safe) artifacts. + +### B. Hand-authored `.hdbconstraint` artifacts — **REJECTED** +Author the 46 cascade constraints by hand. +- **Rejected because:** this is exactly what #3003 reverted (HDI errors 8250014 / 8212001 / 8212012, blocked every MTA deploy). The spike also showed CAP's native output is `NOT VALIDATED` while hand-rolled inline FKs are forced `ENFORCED VALIDATED` — strictly worse. + +### C. `draft_orphan_cleanup` only, cascades never enabled — **REJECTED as the whole fix** +- **Rejected because:** the user's decision is to implement the whole feature. Orphan cleanup alone leaves draft deletion on the slow `flat` strategy and does not deliver the optimization. It is **retained as a component** of approach A (goal 3), not the endpoint. + +## Builder-check resolutions (verified facts — do not re-investigate) + +- **`scripts/patch-draft-cascade-constraints.cjs` does not exist and is not wired** anywhere (verified: absent from the tree; no reference in `package.json` or `scripts/`). It was reverted in #3003 and never re-landed. Do NOT reintroduce it (that is rejected approach B). Any doc mention of it is stale. +- **46 is authoritative.** Compiling this model (`to.hdi`, `draft_admin_integrity: true`, `sqlDialect: hana`) emits exactly **46** `DraftAdministrativeData … ON DELETE CASCADE … NOT VALIDATED` constraints — one per `*_drafts` shadow table. The preflight's stale 27-entry `DRAFT_TABLES` list is deprecated; it discovers tables from `SYS.TABLE_COLUMNS` at runtime, so `N` = 46 on a correctly-deployed schema. +- **`cds.fiori.draft_orphan_cleanup` is a real, recognized key** in installed `@sap/cds@10.2.2` (`cds.env.fiori`, Node runtime, default `false`). Goal 3 will not silently no-op. It belongs in the fiori config block alongside `draft_admin_integrity`. +- **Constraints are CAP-native and `NOT VALIDATED`** — pre-existing orphans do NOT block the deploy. The old runbook's "sweep orphans before deploy" gate does not apply to this path. + +## The how — decided + +Ordered so correctness gates are green before any risky flip, mirroring `docs/developers/operations/draft-integrity-reenable.md`: + +1. **Resolve the build-path question (the core engineering task).** Determine why the 46 native constraints surface through the full `to.hdi` compile but not the observed `cds.compile.to.hana` / `.hdbmigrationtable` delta path. Prime suspects, in order: (a) a journaling / `@cds.persistence.journal` interaction (cf. the known "full `cds build` suppresses hdbmigrationtable version bumps via the cds-caching statistics hana task clobbering the last-dev csn baseline" gotcha — same `to.hana` delta path); (b) an option-flatten on the migration path (`cdsc.js:154` `Object.assign` REVISIT); (c) a genuine cds-dk 10.2.0 / compiler 7.2.1 gap requiring a version bump or `patch-package` shim. **Builder's latitude** on *how* to instrument, but the exit criterion is fixed: a `cds build --production` of this project emits `AdminService.*_drafts_DraftAdministrativeData.hdbconstraint` (×46, `NOT VALIDATED`, `ON DELETE CASCADE`) into `gen/db`. If none of (a)–(c) yields this without hand-rolling, **stop and escalate** — do not fall back to approach B. +2. **Set `cds.features.assert_integrity`?** — No. Confirmed non-goal; the draft pass needs only `draft_admin_integrity` + a non-plain dialect. +3. **Keep flags OFF while building.** Constraints land in the build with `draft_admin_integrity` still `false` in `package.json` (generation is a compile concern; runtime behavior is the flag). Deploy constraints first. +4. **Deploy to DEV HANA (delta).** Verify the `.hdbconstraint`s are in the MTA (crack the mtar, as Step 3.5 does for admin bundles) and that HDI accepts them `NOT VALIDATED` on a delta deploy over the existing container. This is the first real proof. +5. **Verify preflight.** `srv/lib/draft-integrity-preflight.js` must log `verified (N/N)` (not WARN) on DEV. Pre-existing orphans do **not** block (constraints are `NOT VALIDATED`); still run `cleanup-draft-orphans.cjs --dry-run` for a clean baseline reading. +6. **Flip `draft_admin_integrity: true`** (both `package.json` blocks) + **`draft_orphan_cleanup: true`**; set `cds.drafts.deleteStrategy: dad` per CAP docs. Redeploy DEV. +7. **Audit custom draft-deletion handlers under `dad` (REQUIRED — handler-firing change).** CAP docs warn `dad` "changes which event handlers are called during draft deletion." This repo has custom `after('DISCARD')` / `after('DELETE')` reconcile hooks (`srv/lib/completion-reconcile.js`, `srv/lib/pipeline-log-reconciler.js`, `srv/lib/topic-cluster-reconcile.js`) with a dedicated `test/admin-drafts-discard-reconcile.test.js` — added to survive with the flag OFF. Under `dad` the DB cascade may bypass exactly those hooks. The SQLite gate test is flag-agnostic and will NOT catch a bypass. Audit each reconcile hook's behavior under `dad`, and add a **HANA-level** (not SQLite) test proving the reconcile side effects still fire after a `dad` draft discard. This is a PROD-blocking gate. +8. **Gate test green.** `test/admin-drafts-cascade-gate.test.js` — Mission draftEdit→discard leaves zero orphaned child draft rows (SQLite-level runtime check; the HANA cascade is proven by steps 4–5, the hook behavior by step 7). +9. **Smoke on DEV**, then promote the same sequence to PROD via the normal DEV→main release flow. +10. **Rewrite** `docs/developers/operations/draft-integrity-reenable.md` (not a light update): its current Steps 1–2 are built around the *rejected* hand-rolled ENFORCED inline FK (`scripts/patch-draft-cascade-constraints.cjs`, reverted in #3003) whose premise ("sweep orphans BEFORE deploy or HANA rejects it") is **void** for CAP's native `NOT VALIDATED` constraints. Retire that patch-script path from the doc entirely. Also correct the CLAUDE.md "Optimized draft deletion" gotcha: native `NOT VALIDATED` constraints; the real blocker was the build-format path (`to.hana`/`.hdbmigrationtable`), not HDI make-graph or hand-authoring. + +## What's left to the builder + +- The instrumentation method for step 1 and the specific fix (config change, dependency bump, or minimal `patch-package` shim) — provided the exit criterion in step 1 is met and approach B is not used. +- Exact wording of the doc/gotcha updates. +- Whether `deleteStrategy: dad` is set via `package.json` or `.cdsrc.json` (follow existing fiori-config placement). + +## Rollback + +- Pre-flip (steps 1–5): constraints are `NOT VALIDATED` and inert without the flag — no behavior change, nothing to roll back beyond reverting the build change. +- Post-flip: revert `draft_admin_integrity` + `draft_orphan_cleanup` + `deleteStrategy` to prior values and redeploy; the constraints may remain (harmless). Orphan sweep via `cleanup-draft-orphans.cjs --commit` if any accumulated. + +## Verification (evidence required before "done") + +- `cds build --production` emits 46 draft `.hdbconstraint`s locally (step 1 exit criterion). +- mtar contains them (cracked-archive diff). +- DEV HANA delta deploy succeeds; preflight logs `verified (46/46)`. +- Gate test passes. +- **Hook audit (step 7):** a HANA-level test confirms each `after('DISCARD')`/`after('DELETE')` reconcile side effect still fires under `deleteStrategy: dad`. PROD-blocking. +- DEV smoke: a Mission draftEdit→discard, then a direct query confirming zero orphaned child draft rows on real HANA. diff --git a/package-lock.json b/package-lock.json index c895dc736..3481b6890 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5354,9 +5354,9 @@ } }, "node_modules/@sap/cds-compiler": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/@sap/cds-compiler/-/cds-compiler-7.0.1.tgz", - "integrity": "sha512-Qwk9jitwSSwPB9FTB/Q6gYPxFsJxswhfsO9Ux77HTxjIhse8O/Hlq2XzkpVSTyaAVr8Lo7wLfpytHwKQScZTwQ==", + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/@sap/cds-compiler/-/cds-compiler-7.2.1.tgz", + "integrity": "sha512-VgiOQxtYLQs/lWSA5P6LzbiSlluX+o3wYImkoASUl/spmBo/nkF/L/zwNCYCQD6MiIKkgzmToGIlsZEqsGozvQ==", "license": "SEE LICENSE IN LICENSE", "bin": { "cdsc": "bin/cdsc.js", diff --git a/package.json b/package.json index e21afc705..ed606829f 100644 --- a/package.json +++ b/package.json @@ -246,6 +246,9 @@ "undici": "8.10.2", "vue-virtual-scroller": "3.0.5" }, + "overrides": { + "@sap/cds-compiler": "7.2.1" + }, "cds": { "protocols": { "graphql": { @@ -463,7 +466,11 @@ "fuzzy": false }, "fiori": { - "draft_admin_integrity": false + "draft_admin_integrity": true, + "draft_orphan_cleanup": true + }, + "drafts": { + "deleteStrategy": "dad" }, "websocket": { "kind": "socket.io", @@ -488,7 +495,8 @@ "diagram": true }, "fiori": { - "draft_admin_integrity": false + "draft_admin_integrity": true, + "draft_orphan_cleanup": true } }, "mcp": { diff --git a/test/draft-cascade-build.test.js b/test/draft-cascade-build.test.js new file mode 100644 index 000000000..2df9c888a --- /dev/null +++ b/test/draft-cascade-build.test.js @@ -0,0 +1,114 @@ +// test/draft-cascade-build.test.js +// +// Build-artifact guard for #2993: the production build (compiler 7.2.1, pinned +// via package.json overrides) must emit exactly 46 NOT VALIDATED draft +// DraftAdministrativeData ON DELETE CASCADE constraints. +// +// This test compiles the CDS model in-process (no `cds build` child process) +// using cds-dk's bundled @sap/cds-compiler with draft_admin_integrity: true. +// It is independent of the runtime feature flag (cds.fiori.draft_admin_integrity) +// which stays false in the committed config — this test exercises the compiler +// output shape only. +// +// Why cds-dk's compiler? The overrides pin in package.json ensures that after +// `npm install`, root @sap/cds-compiler is 7.2.1 — the first version that ships +// the createDraftAdminDataConstraints generator with NOT VALIDATED rendering. +// cds-dk's nested copy is also 7.2.1 and is addressable before the root install +// is run, making both paths equivalent post-install. +// +// Regression: if the overrides pin is removed and lockfile reverts to 7.0.1, +// compiler.to.hdi emits 0 draft constraints → count assertion fails → CI red. + +import { describe, it, expect } from 'vitest'; +import { createRequire } from 'node:module'; +import { join } from 'node:path'; + +// Project root: one level up from the test directory. +const PROJECT_ROOT = join(import.meta.dirname, '..'); + +// createRequire anchored to the project root so Node's module resolution +// algorithm walks node_modules starting from the project tree — the same +// algorithm that `cds build` uses when it resolves @sap/cds-compiler. +const require = createRequire(join(PROJECT_ROOT, 'package.json')); + +/** + * Compile the project's CDS model in-process and collect every .hdbconstraint + * string that references DraftAdministrativeData with an ON DELETE CASCADE clause. + * + * Uses cds-dk's bundled @sap/cds-compiler (7.2.1 after the #2993 overrides pin) + * with `draft_admin_integrity: true` so the generator is active regardless of the + * committed runtime flag setting. + * + * @returns {Promise} array of constraint DDL strings + */ +async function compileAndCollectDraftCascades() { + // Resolve via cds-dk's nested compiler path. After the #2993 overrides pin + // takes effect on `npm install`, root @sap/cds-compiler also becomes 7.2.1, + // so both resolution paths yield the same binary. We prefer cds-dk's path + // because it resolves correctly in both the pre- and post-install states + // of an isolated git worktree (where root node_modules may still carry 7.0.1). + const cdsDkPkgPath = require.resolve('@sap/cds-dk/package.json'); + const cdsDkBase = cdsDkPkgPath.replace(/[/\\]package\.json$/, ''); + + // Load @sap/cds from the same tree that cds-dk ships so model loading is + // consistent with what the production build uses. Compiler is resolved first + // so both require calls complete before we touch process.env. + const cdsPkgPath = require.resolve('@sap/cds/package.json', { paths: [cdsDkBase] }); + const cdsBase = cdsPkgPath.replace(/[/\\]package\.json$/, ''); + const cds = require(join(cdsBase, 'lib', 'index.js')); + + // Compiler is resolved from cds-dk's own node_modules (7.2.1). + const compiler = require(require.resolve('@sap/cds-compiler', { paths: [cdsDkBase] })); + + // Scope CDS_ENV='production' so the model includes @cap-js/hana artifacts. + // Restore immediately after the compile to avoid leaking the mutation into + // co-running unit tests that share this worker process. + const prevCdsEnv = process.env.CDS_ENV; + let csn, hdi; + try { + process.env.CDS_ENV = 'production'; + csn = await cds.load(['db', 'srv'], { root: PROJECT_ROOT }); + // Compile to HDI with the cascade constraint generator enabled. + hdi = compiler.to.hdi(csn, { draft_admin_integrity: true, sqlDialect: 'hana' }); + } finally { + if (prevCdsEnv === undefined) { + delete process.env.CDS_ENV; + } else { + process.env.CDS_ENV = prevCdsEnv; + } + } + + // Collect .hdbconstraint files whose bodies reference DraftAdministrativeData + // and contain a CASCADE clause (i.e. the draft FK constraints we are guarding). + return Object.entries(hdi) + .filter( + ([name, content]) => + name.endsWith('.hdbconstraint') && + typeof content === 'string' && + content.includes('DraftAdministrativeData') && + content.includes('CASCADE'), + ) + .map(([, content]) => content); +} + +describe('#2993 native draft cascade constraints', () => { + // Cache the result across both `it` blocks so the compiler runs once per suite. + let draftCascadesPromise; + const getDraftCascades = () => { + if (!draftCascadesPromise) draftCascadesPromise = compileAndCollectDraftCascades(); + return draftCascadesPromise; + }; + + it('emits 46 DraftAdministrativeData ON DELETE CASCADE constraints', async () => { + const draftCascades = await getDraftCascades(); + expect(draftCascades.length).toBe(46); + }); + + it('emits them NOT VALIDATED (deploy-safe over existing orphans)', async () => { + const draftCascades = await getDraftCascades(); + for (const c of draftCascades) { + expect(c).toMatch(/ON DELETE CASCADE/); + expect(c).toMatch(/NOT VALIDATED/); + } + }); +});