Skip to content

feat(appkit): apply committed database migrations on deploy start, in schema app by default - #654

Draft
ditadi wants to merge 2 commits into
mainfrom
stack/database-dev-flow/01-migrations-on-deploy
Draft

ditadi wants to merge 2 commits into
mainfrom
stack/database-dev-flow/01-migrations-on-deploy

Conversation

@ditadi

@ditadi ditadi commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

The design is #677.

This PR absorbs #655 (the app default schema) and the schema-ownership recovery hint from the old #675.

What did you change, and why?

A deployed App Builder app has no person or CI job to run its migrations, so it has to apply them itself when it starts. This PR is for apps on the beta database() plugin. Once an app sets APPKIT_DB_MIGRATE_ON_START=true, each deploy applies the committed drizzle-kit migrations in config/database/migrations before the app serves. An app without the flag never migrates. Its one visible change is that tables now default to the Postgres schema app.

Migrate on start works like this:

  • database() applies pending migrations in setup(), after the pool opens and before select 1, the declared-schema check and server.start().
  • It migrates only when the flag is true, DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET are set, and PGUSER is set and equals DATABRICKS_CLIENT_ID. So only the app's own service principal migrates, and a local or databricks apps run-local start never does. When the flag is set and the process does not qualify, it logs why. A flag value other than true is ignored with a warning.
  • A migrating start reads its branch from LAKEBASE_ENDPOINT (projects/<p>/branches/<b>/endpoints/<e>) and fails when that is unset or has another form. It refuses a branch with the exact shape of a dev or session branch (dev-<user>-<hash6>, session-<hash6>-<id>), and a -pooler host.
  • Each migration runs and is recorded in its own transaction, so a failure keeps the ones before it.
  • One advisory lock per schema makes instances apply in turn. The wait is capped at 5 minutes and logs the holder's pid and application_name. Each table lock waits 5 s, three times per migration. The session sets client_connection_check_interval to 10 s and warns when the server rejects it. A start with nothing pending takes no lock.
  • The journal is reconciled with the recorded rows, one to one within a when. A deploy start refuses a stranded migration (older than the last recorded one and never run), an edited one (line endings ignored), a when it cannot pair, a diverged history, and a 0000_baseline whose tables exist only in part. A baseline whose tables all exist is recorded as applied. Recorded rows the checkout lacks log a warning.
  • The migrator uses __drizzle_migrations only when it is an ordinary table. It records only into a journal owned by a role it trusts, and reads another role's journal only when it has no row-level security.
  • Each failure names the step and the SQLSTATE. A 42501 names the schema owner and the connecting role, puts the two-apps case first, and never suggests ALTER ... OWNER TO. For an app recreated with a new service principal, it gives the databricks postgres delete-role --reassign-owned-to recovery.
  • Each run logs one line with the counts, the lock wait and the duration, and one line per applied migration.

The app default works like this:

  • defineSchema() without a schemaName puts tables and enums in app. The service principal creates and owns app on its first start, because on Lakebase it has no CREATE on public. An explicit { schemaName: "public" } keeps unqualified SQL.
  • An app whose tables are still in public fails setup with an error that says so and shows { schemaName: "public" }. With the flag on, startup refuses to migrate an implicit app that has none of the declared tables while public has some. Otherwise the first migration would create empty copies and the app would serve them.
  • A 42501 on public asks for GRANT CREATE ON SCHEMA public only when the role lacks it. Otherwise it names the table ownership problem.
  • The dev-playground passes { schemaName: "public" }, because its tables were created by hand there.

CI's test job gets a postgres:17 service and sets APPKIT_TEST_PG_URL, so the *.pg.test.ts suites run on every PR. The plugin docs cover the flag, the app default and the upgrade from public. The design doc gets the matching details.

What this PR does not do:

  • It adds no CLI. The stranded-migration error names appkit db clean and appkit db migrate, which feat(appkit): add the appkit db commands for the database development flow #666 adds.
  • The plugin stays hidden: true, so databricks apps init does not offer it.
  • It adds no span or metric for migrations, only log lines.
  • The dev and session branch refusal runs inside migrate on start, so an app without the flag still starts on such a branch.

Nothing migrates until an app sets the flag, so this PR is safe to deploy alone.

How do you know it works?

  • apply.test.ts, history.test.ts, migrate-on-start.test.ts and lifecycle.test.ts cover the transactions, each reconcile case, the locks, the message for each failed step, the identity rule, the endpoint and branch refusals, and the pooler refusal. define-schema.test.ts, schema-check.test.ts, tables-left-in-public.test.ts and ownership.test.ts cover the app default, the public errors and the ownership hints.
  • apply.pg.test.ts (26 tests), schema-check.pg.test.ts and tables-left-in-public.pg.test.ts run against Postgres. They cover an enum value added in one migration and used in the next, a failed migration fixed and applied again, a stranded migration that changes nothing, instances starting together, the lock wait limit, a table lock retried and then failing with 55P03, a schema owned by another role, a view at the journal's name, an edited migration, a CRLF checkout, baseline adoption, and app tables left in public.
  • On this branch, with Postgres 17, pnpm build, pnpm -r typecheck, pnpm check, pnpm test (349 files and 6595 tests passed, 1 skipped) and pnpm docs:build passed. They ran one commit before a one-line fix to the design doc's Flag Strategy table, and the head differs from that commit only in that line.
  • dev-obo.integration.test.ts failed once with EADDRINUSE on a fixed port, which this PR does not touch. It passed on rerun.
  • The database tooling and the appkit db commands do not exist on this branch, and a git grep for imports of either finds nothing.
  • The second commit removes narration comments and moves their meaning into names and small extracted functions. A script listed every string literal the diff changes, and no text in a throw, warn, info, ok or fail call changed. Tests changed only to follow the renamed fields.
  • Two GPT reviewers read the consolidation. The split reviewer found one doc issue, how the design doc described which branches appkit db changes, and that line is fixed. The cleanup reviewer found nothing.
  • bundle-size-baseline.json records the new @databricks/appkit size. The packed tarball grows from 1,409,598 to 1,454,413 bytes (+3.2%). It was measured before the comment cleanup, which only shrinks the package.
  • Earlier rounds checked real Lakebase. An earlier revision of the old feat(appkit): apply committed database migrations on deploy start, in schema app by default #654 ran on a Lakebase project with a throwaway deploy branch and app. On 2026-11-15, a throwaway Lakebase fork confirmed that the developer role can write the service principal's rows but cannot alter its tables.

This revision was not run against a real Lakebase workspace. The design's done criterion for this PR, a throwaway app that deploys and applies 0000 and then 0001, is still open.

This pull request and its description were written by Isaac.

@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

📦 Bundle size report

Compared against bundle-size-baseline.json (main).

@databricks/appkit

npm tarball (packed): 1.4 MB (-6.3 KB) — gzipped download (dist + bin; excludes release-only docs/NOTICE).

dist raw gzip
JS (runtime) 1.4 MB (-6.6 KB) 516 KB (-2.8 KB)
Type declarations 482 KB 174 KB
Source maps 2.8 MB (-10 KB) 956 KB (-4.3 KB)
Other 11 KB 3.7 KB
Total 4.7 MB (-17 KB) 1.6 MB (-7.1 KB)
Per-entry composition (own code — deps external (as shipped))
Entry Initial (gz) Lazy (gz) Total (gz) node_modules (min) Own code (min)
. 118 KB 2.4 KB 121 KB external 378 KB
./beta 127 KB (+204 B) 4.5 KB 132 KB (+204 B) external 382 KB (+823 B)
./testing 47 KB 38 KB 85 KB external 246 KB
./tsdown 630 B 0 B 630 B external 1.0 KB
./type-generator 31 KB 0 B 31 KB external 89 KB

Chunks:

Entry Chunk Load Size (gz)
. index.js initial 114 KB
. utils.js initial 4.6 KB
. remote-tunnel-manager.js lazy 2.4 KB
./beta beta.js initial 101 KB
./beta stream-manager.js initial 5.9 KB
./beta define-schema.js initial 5.9 KB
./beta service-context.js initial 4.3 KB
./beta modular.js initial 3.6 KB
./beta databricks.js initial 3.3 KB
./beta wide-event-emitter.js initial 2.8 KB
./beta client.js initial 645 B
./beta index.js initial 20 B
./beta index.js lazy 4.0 KB
./beta supervisor-api.js lazy 201 B
./beta databricks.js lazy 188 B
./beta index.js lazy 124 B
./testing manifest.js initial 33 KB
./testing index.js initial 10 KB
./testing wide-event-emitter.js initial 2.9 KB
./testing index.js lazy 34 KB
./testing remote-tunnel-manager.js lazy 2.4 KB
./testing utils.js lazy 1.8 KB
./tsdown index.js initial 630 B
./type-generator index.js initial 31 KB

@databricks/appkit-ui

npm tarball (packed): 393 KB (-4 B) — gzipped download (dist + bin; excludes release-only docs/NOTICE).

dist raw gzip
JS (runtime) 430 KB 146 KB
Type declarations 250 KB 93 KB (-1 B)
Source maps 837 KB 281 KB
CSS 16 KB 3.2 KB
Total 1.5 MB 522 KB (-1 B)
Per-entry composition (consumer bundle — deps bundled, peerDeps external)
Entry Initial (gz) Lazy (gz) Total (gz) node_modules (min) Own code (min)
./js 5.3 KB 49 KB 55 KB 208 KB 14 KB
./js/beta 2.4 KB 0 B 2.4 KB 0 B 5.3 KB
./react 441 KB 49 KB 489 KB 1.4 MB 180 KB
./react/beta 13 KB 0 B 13 KB 25 KB 13 KB

Chunks:

Entry Chunk Load Size (gz)
./js index.js initial 5.2 KB
./js chunk initial 120 B
./js apache-arrow lazy 49 KB
./js/beta beta.js initial 2.4 KB
./react index.js initial 439 KB
./react tslib initial 2.1 KB
./react apache-arrow lazy 49 KB
./react/beta beta.js initial 13 KB

@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🤖 AppKit PR bot

🔬 Run evals

Start an eval for this PR from the evals-monitor app: Go to Evals Monitor →

📦 Try this PR's app template

Scaffolds a new app from this PR's SDK build. Run it in any folder (requires the GitHub CLI — gh auth login — and the Databricks CLI):

gh run download 45843177866 -R databricks/appkit -n appkit-template-0.105.0-pr.6b845c4-stack-database-dev-flow-01-migrations-on-deploy-654 -D appkit-pr-654 \
  && unzip -o "appkit-pr-654/appkit-template-0.105.0-pr.6b845c4-stack-database-dev-flow-01-migrations-on-deploy-654.zip" -d "appkit-pr-654" \
  && databricks apps init --template "appkit-pr-654"

The template pins @databricks/appkit and @databricks/appkit-ui to tarballs built from this branch, so the scaffolded app runs against this PR's code.

ditadi and others added 2 commits November 26, 2026 14:16
…pp by default

The database plugin can apply the app's committed drizzle-kit migrations when
the deployed app starts. The flag APPKIT_DB_MIGRATE_ON_START is off by default
and the plugin stays hidden, so no app changes until it opts in.

What ships:

- Migrate on start in setup(), before the schema check and server.start(). It
  runs only when PGUSER is set and equals DATABRICKS_CLIENT_ID, with
  DATABRICKS_CLIENT_SECRET set, and logs why when it skips.
- A refusal to start on a branch shaped like a dev or session branch, and on a
  -pooler endpoint.
- One transaction per migration, a migration lock per schema with a bounded
  wait, a 5 s lock timeout with retries, and client_connection_check_interval
  set to 10 s, with a warning when the server rejects it.
- The reconcile states: pending, current, stranded, edited (ignoring line
  endings), ambiguous, ahead and partial-baseline, matched one to one within a
  `when`. A deploy start refuses stranded, edited, ambiguous and diverged
  histories.
- The journal trust rule, a lock-free read on a current branch, and a log line
  per run and per applied migration.
- Tables in the Postgres schema `app` unless defineSchema() names another one.
  Startup refuses to create the tables in an implicit `app` when `public`
  already has them, and the schema check names that cause.
- Owner errors that name both roles, the two-apps case first, and the
  `databricks postgres delete-role --reassign-owned-to` recovery.
- A real-Postgres test suite, run in CI against a postgres:17 service.
- The design doc and plugin docs for these behaviors.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: ditadi <victordperd@gmail.com>
…d in the runtime

Comments that restated a name, narrated the next lines or argued about our
own code are gone. The ones that explain a foreign constraint (Postgres,
drizzle, pg-pool, the Apps platform) stay as they were.

Where a comment carried meaning a name should, the name now carries it:

- ApplyMigrationsResult.unknown is unknownRecordedCount, LOCK_ATTEMPTS is
  TABLE_LOCK_ATTEMPTS, and the SQLSTATE classes are named constants.
- The journal refusals are not-a-table, untrusted-owner and
  untrusted-row-security.
- The branch-name limits are LAKEBASE_MAX_BRANCH_ID_LENGTH and
  USER_HASH_HEX_LENGTH, and the ignored flag value is ignoredFlagValue.

Behavior-preserving extractions replace the prose that explained the control
flow: beforeApply runs outside the error-wrapping try, reconcileUnderLock and
adoptBaseline come out of applyPendingMigrations, readJournalRelation and
assertJournalUsable replace journalTableExists, deployedAppIdentityGap holds
the identity checks, and the dev-playground memory database names its setup
responders.

The plugin doc's Basic usage no longer says the plugin never migrates tables.
It names APPKIT_DB_MIGRATE_ON_START.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: ditadi <victordperd@gmail.com>
@ditadi
ditadi removed this pull request from stack #667 November 26, 2026 14:50
ditadi added a commit that referenced this pull request Nov 26, 2026
…ionals from one table

The health-check note in app.yaml.tmpl and the usage note in the scaffolded
schema.ts are gone. README.md.tmpl and the plugin doc carry the same content,
and the app.yaml note rendered into every app, with or without the plugin.

The smoke test's three copies of the strip-a-conditional block are one table
of named patterns run by one loop. It scaffolds byte-identical output with
and without --all-plugins.

The design doc's Background and Flag Strategy name the three PRs, #654, #666
and #675, instead of the closed ones. Migrations on deploy says again that
scaffolded apps set APPKIT_DB_MIGRATE_ON_START, which holds once this PR
ships the template.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: ditadi <victordperd@gmail.com>
@ditadi
ditadi force-pushed the stack/database-dev-flow/01-migrations-on-deploy branch from 0a9a688 to 87a7c72 Compare November 26, 2026 14:51
@ditadi ditadi changed the title feat(appkit): apply committed database migrations on deploy start feat(appkit): apply committed database migrations on deploy start, in schema app by default Nov 26, 2026
@ditadi
ditadi added this pull request to stack #752 November 26, 2026 14:52

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant