diff --git a/.github/actions/setup-python-env/action.yml b/.github/actions/setup-python-env/action.yml index 636fcd85a0..d47e96cb59 100644 --- a/.github/actions/setup-python-env/action.yml +++ b/.github/actions/setup-python-env/action.yml @@ -63,6 +63,13 @@ runs: echo "cache-path=$UV_CACHE_DIR" >> "$GITHUB_OUTPUT" shell: bash + - name: Use a writable cache directory for project tools + if: runner.os == 'Linux' + shell: bash + run: | + mkdir -p "$RUNNER_TEMP/project-cache" + echo "XDG_CACHE_HOME=$RUNNER_TEMP/project-cache" >> "$GITHUB_ENV" + # Publish before tests so a later failure or timeout cannot discard the download cache. - name: Save Python dependencies if: inputs.shared-cache == 'true' && steps.uv.outputs.cache-hit != 'true' && github.event_name != 'merge_group' diff --git a/.github/ci-paths.toml b/.github/ci-paths.toml index 5db6e4c550..1b1f8d8c4d 100644 --- a/.github/ci-paths.toml +++ b/.github/ci-paths.toml @@ -132,7 +132,7 @@ kimi = ["integrations/kimi-code/**", "tests/*kimi*", ".github/workflows/kimi-cod upgrade = [ "scripts/oceanbase_ci.py", "scripts/run_atomic_memory_clean_migration.py", "scripts/build_ops_bundle.py", - "release/**", "scripts/upgrade_*.py", "scripts/ci_legacy_upgrade_rejection.py", + "release/**", "scripts/schema_release.py", "tests/test_schema*.py", "scripts/upgrade_*.py", "scripts/ci_legacy_upgrade_rejection.py", "scripts/ci_release_smoke.py", "scripts/ci_ops_bundle_smoke.py", "scripts/capture_release_schema.py", "tests/release_upgrades/**", "tests/test_upgrade*.py", "tests/test_registered_source_maintenance_cli.py", "tests/test_managed_*maintenance.py", "tests/e2e/*migration*", "tests/e2e/*managed_startup*", diff --git a/.github/workflows/gateway.yml b/.github/workflows/gateway.yml index 7487e193eb..235df92f7a 100644 --- a/.github/workflows/gateway.yml +++ b/.github/workflows/gateway.yml @@ -30,7 +30,8 @@ jobs: ${{ !cancelled() && ((inputs.suites == '' && needs.changes.result != 'success') || fromJSON(inputs.suites || needs.changes.outputs.suites || '{}').gateway) }} runs-on: powercontext-ci-light - timeout-minutes: 20 + # Include Rust/Go toolchains, cold builds, and upstream protocol acceptance. + timeout-minutes: 45 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: diff --git a/.github/workflows/installation.yml b/.github/workflows/installation.yml index 3de4d41d4e..d7f9a58006 100644 --- a/.github/workflows/installation.yml +++ b/.github/workflows/installation.yml @@ -32,7 +32,7 @@ jobs: matrix: os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os == 'ubuntu-latest' && 'powercontext-ci-light' || matrix.os }} - timeout-minutes: 20 + timeout-minutes: 30 steps: - name: Check out uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index b2216512d2..4d3c2308de 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -177,7 +177,7 @@ jobs: quality: name: CI preflight if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} - timeout-minutes: 30 + timeout-minutes: 45 runs-on: powercontext-ci-light outputs: suites: ${{ steps.select.outputs.suites }} @@ -202,11 +202,15 @@ jobs: run: python3 scripts/ci_changes.py - name: Check License Header - timeout-minutes: 10 + # Include a cold Go toolchain download and license-eye build. + timeout-minutes: 20 uses: apache/skywalking-eyes/header@a196742f472feaffafea537ce5a2a4c3c53a8de4 # v0.9.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} INSTALL_DIR: ${{ runner.temp }} + # Self-hosted runner home caches may be owned by the image build user. + GOCACHE: ${{ runner.temp }}/license-go-build + GOMODCACHE: ${{ runner.temp }}/license-go-mod PATH: ${{ runner.temp }}:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin with: config: .licenserc.yaml @@ -222,12 +226,23 @@ jobs: - name: Cache prek environments uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 with: - path: ~/.cache/prek - key: prek-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.python.outputs.version }}-${{ hashFiles('.pre-commit-config.yaml') }} + path: ${{ runner.temp }}/prek + key: prek-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.python.outputs.version }}-${{ hashFiles('.pre-commit-config.yaml') }} - name: Run checks + env: + PREK_HOME: ${{ runner.temp }}/prek run: make check + - name: Validate cumulative migration against the PR base + if: github.event_name == 'pull_request' + env: + SCHEMA_BASE: ${{ github.event.pull_request.base.sha }} + run: uv run --locked python scripts/schema_release.py check --base-ref "$SCHEMA_BASE" + + - name: Test cumulative schema freezing and replay + run: uv run --locked pytest tests/test_schema_release.py tests/test_schema_draft.py -q + - name: Check OpenAPI contract run: make contract-test @@ -237,7 +252,8 @@ jobs: if: ${{ !cancelled() && needs.quality.result == 'success' && (fromJSON(needs.quality.outputs.suites || '{}').tests) }} # Unit jobs must outlast pytest plus uv cache publication. End-to-end jobs # also need time for subprocess tails on internal runners. - timeout-minutes: ${{ matrix.suite == 'e2e' && 55 || 50 }} + # Python 3.11/3.12 can exceed 55 minutes while the full E2E suite is still progressing. + timeout-minutes: ${{ matrix.suite == 'e2e' && 90 || 75 }} runs-on: powercontext-ci-standard strategy: fail-fast: true @@ -385,7 +401,8 @@ jobs: docs-tests: needs: [quality] if: ${{ !cancelled() && needs.quality.result == 'success' && (fromJSON(needs.quality.outputs.suites || '{}').docs_tests) }} - timeout-minutes: 15 + # Include cold checkout, environment setup, and cache publication. + timeout-minutes: 30 runs-on: powercontext-ci-light steps: - name: Check out @@ -847,7 +864,8 @@ jobs: dify-tools: needs: [quality, tests] if: ${{ !cancelled() && needs.quality.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.tests.result) && (fromJSON(needs.quality.outputs.suites || '{}').dify) }} - timeout-minutes: 15 + # Include cold dependency setup and cache publication around acceptance. + timeout-minutes: 30 runs-on: powercontext-ci-light steps: - name: Check out @@ -1280,7 +1298,8 @@ jobs: openclaw-package: needs: [quality, tests] if: ${{ !cancelled() && needs.quality.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.tests.result) && (fromJSON(needs.quality.outputs.suites || '{}').openclaw) }} - timeout-minutes: 20 + # Include cold dependency setup and cache publication around acceptance. + timeout-minutes: 40 runs-on: powercontext-ci-light env: OPENCLAW_VERSION: '2026.8.1' @@ -1417,7 +1436,8 @@ jobs: check-website: needs: [quality] if: ${{ !cancelled() && needs.quality.result == 'success' && (fromJSON(needs.quality.outputs.suites || '{}').website) }} - timeout-minutes: 20 + # Include cold checkout, environment setup, and cache publication. + timeout-minutes: 40 runs-on: powercontext-ci-standard steps: - name: Check out @@ -1660,7 +1680,8 @@ jobs: needs: [quality, tests] if: ${{ !cancelled() && needs.quality.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.tests.result) && (fromJSON(needs.quality.outputs.suites || '{}').helm) }} runs-on: powercontext-ci-light - timeout-minutes: 10 + # Include cold dependency setup and cache publication around acceptance. + timeout-minutes: 20 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: diff --git a/AGENTS.md b/AGENTS.md index 9c1d45efea..1dbd2784bc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,28 +76,39 @@ The operational field contract is documented in [Logs, metrics, and tracing](doc Use [REVIEW.md](REVIEW.md) when reviewing changes. -## Database Migration Names +## Database Migrations Read the migration guide before changing managed storage: [English](docs/en/docs/operate/database-migrations.md) / [中文](docs/zh/docs/operate/database-migrations.md). -- New Server revisions use `v___pr`, for example - `v1_5_2_pr2674`. Create a draft PR first. Use its number in this repository; keep the full ID within 32 characters. - Each PR adds at most one logical schema revision, shared by its backend implementations. - It may contain multiple DDL operations, data tasks and validations. If independent revision - checkpoints are necessary, split the work into dependent PRs. -- Agree on the target release before registering migrations, using the version declared in - `openapi/powercontext.yaml` and `release/upgrade-support.json`. At registration, the new prefix must - match both declarations. This does not require existing prefixes to track later version bumps. Feature PRs do not independently - bump the release. Once registered, keep the ID even if the change ships in a later release. -- Before merging, update against master, reconcile unpublished dependencies and conflicting schema - changes, and rerun migration validation. Keep a single head; `down_revision` determines order, - not PR numbers or lexical sorting. Check for duplicate IDs across the combined changes. -- Release preparation records the package-to-head mapping and verifies upgrades; it does not rename - revisions or postpone dependency reconciliation until publication. No schema change means no new revision. -- Preserve existing revision IDs, frozen resources, plans and checksums. Do not rewrite published - migrations. A development database that ran an earlier branch chain must be rebuilt or use an - explicitly validated conversion; changing `down_revision` alone does not migrate that database. +- Schema changes accumulate in one unpublished Server revision `000`, using + `server_resources/versions/000.py` and the matching `mysql/versions/000.py` under + `src/powercontext/builtin/persistence/migrations/`. Its `down_revision` is the last frozen head. + Create this draft only when storage changes; subsequent PRs edit the same draft rather than add revisions. +- Keep SQL, snapshots, native recovery layouts, domain tasks and all source/profile registrations in sync. + Give draft-owned resources names containing `000` (for example `schemas/sqlite-000.json`), and use + literal revision IDs and resource paths so the freeze tool can update references safely. + Never change frozen scripts or dependencies to accommodate a draft. +- Before merging, update against master, reconcile conflicts in the cumulative SQL and registrations, + and pass CI on the merged result. CI validates the chain, checks frozen history against the PR base, + replays registered SQLite sources and runs the selected installed-release upgrade acceptance. + Repository administrators must require these checks and an up-to-date branch or merge queue. +- When adopting the cumulative workflow, keep legacy revisions already in the master baseline unchanged. + Unmerged PRs with unpublished sequence/PR-named revisions must update against master and fold only + their remaining changes into the shared `000`, creating it after the latest frozen head if absent. + Reconcile SQL, resources, fingerprints, native layouts and all source/profile registrations with any + existing draft; remove the superseded unpublished entries and rebuild affected development databases. + Run baseline comparison and migration CI on the merged result. PR creation time grants no exemption; + an open PR need not merge before this policy. Never rename a published revision. +- Only released-version upgrades are supported. A database or recovery plan created by unpublished `000` + is disposable: rebuild it when the draft changes or freezes. Do not stamp it as a released revision. +- Release PRs run `make version-bump VERSION=X.Y.Z`, then `make schema-freeze VERSION=X.Y.Z`. + Freezing renames `000` to `vX_Y_Z`, including owned paths and registrations, and refreshes the + persistence digest after validating unchanged frozen history. Review the compatibility rationale, + record the version/head in release notes, and pass `make release-check` and artifact upgrade acceptance. + Publication rejects unfrozen drafts. No pending schema change means no new revision. +- After release, the next schema PR starts a new `000` after the frozen head. Published revisions, + including legacy sequence and PR-based names, retain their identities and resources permanently. ## Generated API Contract diff --git a/Makefile b/Makefile index fa1f3ed030..5ffab01765 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ notebooks-test: ## Execute provider-free tutorials in fresh kernels; use ARGS fo @uv run --locked --group notebooks python examples/jupyter/run.py $(ARGS) .PHONY: check -check: version-check upgrade-policy-check workflow-actions-check integration-manifest-check integration-guidance-check integration-lifecycle-check ## Run code quality tools. +check: schema-check version-check upgrade-policy-check workflow-actions-check integration-manifest-check integration-guidance-check integration-lifecycle-check ## Run code quality tools. .PHONY: integration-guidance integration-guidance-check integration-guidance: ## Copy shared Skills into native packages. @@ -280,7 +280,7 @@ version-check: ## Check release references and generated API code; optionally as @$(MAKE) api-generate-check js-api-generate-check .PHONY: release-check -release-check: version-check upgrade-policy-check docs-install ## Check version references and require matching bilingual notes for a stable release. +release-check: schema-release-check version-check upgrade-policy-check docs-install ## Check version references and require matching bilingual notes for a stable release. @cd website && node --import tsx --test tests/releases.test.ts .PHONY: upgrade-policy-check @@ -339,3 +339,13 @@ help: [[print(f'\033[36m{m[0]:<20}\033[0m {m[1]}') for m in re.findall(r'^([a-zA-Z0-9_-]+):.*?## (.*)$$', open(makefile).read(), re.M)] for makefile in ('$(MAKEFILE_LIST)').strip().split()]" .DEFAULT_GOAL := help + +.PHONY: schema-check schema-release-check schema-freeze +schema-check: ## Validate the shared draft and registered Server migration chains. + @uv run --locked python scripts/schema_release.py check + +schema-release-check: ## Reject an unfrozen 000 migration before publication. + @uv run --locked python scripts/schema_release.py check --release + +schema-freeze: ## Freeze shared 000 resources after version-bump: VERSION=X.Y.Z. + @uv run --locked python scripts/schema_release.py freeze diff --git a/desktop/scripts/prepare-openapi-generator.mjs b/desktop/scripts/prepare-openapi-generator.mjs index cc5c9e8eea..c503fe66e0 100644 --- a/desktop/scripts/prepare-openapi-generator.mjs +++ b/desktop/scripts/prepare-openapi-generator.mjs @@ -47,6 +47,9 @@ export async function getGeneratorInfo() { sha256: checksum.sha256.toLowerCase(), jar: join(dirname(generatorCli), "versions", `${version}.jar`), url: `https://repo.maven.apache.org/maven2/org/openapitools/openapi-generator-cli/${version}/openapi-generator-cli-${version}.jar`, + fallbackUrls: [ + `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/${version}/openapi-generator-cli-${version}.jar`, + ], }; } @@ -62,36 +65,45 @@ async function matchesChecksum(path, expected) { export async function prepareGenerator(info) { info ??= await getGeneratorInfo(); - const { jar, sha256, url, version } = info; + const { jar, sha256, url, fallbackUrls = [], version } = info; if (await matchesChecksum(jar, sha256)) return jar; await mkdir(dirname(jar), { recursive: true }); await rm(jar, { force: true }); const temporary = `${jar}.${randomUUID()}.tmp`; try { - // curl honors proxy settings and Retry-After, and retries only download failures. - await run( - "curl", - [ - "--fail", - "--location", - "--silent", - "--show-error", - "--retry", - "3", - "--retry-connrefused", - "--retry-max-time", - "120", - "--connect-timeout", - "10", - "--max-time", - "45", - "--output", - temporary, - url, - ], - { timeout: 180_000, windowsHide: true }, - ); + const urls = [url, ...fallbackUrls]; + for (const [index, downloadUrl] of urls.entries()) { + try { + // curl honors proxy settings and Retry-After, and retries only download failures. + await run( + "curl", + [ + "--fail", + "--location", + "--silent", + "--show-error", + "--retry", + "3", + "--retry-connrefused", + "--retry-max-time", + "120", + "--connect-timeout", + "10", + "--max-time", + "45", + "--output", + temporary, + downloadUrl, + ], + { timeout: 180_000, windowsHide: true }, + ); + break; + } catch (error) { + await rm(temporary, { force: true }); + if (index === urls.length - 1) throw error; + } + } if (!(await matchesChecksum(temporary, sha256))) { throw new Error(`SHA-256 mismatch for OpenAPI Generator ${version}`); } diff --git a/desktop/scripts/prepare-openapi-generator.test.mjs b/desktop/scripts/prepare-openapi-generator.test.mjs index 203bbc74b3..c682163571 100644 --- a/desktop/scripts/prepare-openapi-generator.test.mjs +++ b/desktop/scripts/prepare-openapi-generator.test.mjs @@ -105,3 +105,37 @@ test("a missing artifact fails without retrying or leaving a cached file", async assert.equal(requests, 1); assert.deepEqual(await readdir(directory), []); }); + +for (const status of [404, 429]) { + test(`a primary HTTP ${status} falls back to a verified artifact`, async (t) => { + const { info } = await fixture(t, (request, response) => { + if (request.url === "/mirror.jar") response.end(artifact); + else response.writeHead(status).end("unavailable"); + }); + info.fallbackUrls = [new URL("mirror.jar", info.url).href]; + + assert.equal(await prepareGenerator(info), info.jar); + assert.deepEqual(await readFile(info.jar), artifact); + }); +} + +test("a mismatched fallback artifact is rejected and cleaned up", async (t) => { + const { directory, info } = await fixture(t, (request, response) => { + if (request.url === "/mirror.jar") response.end("wrong artifact"); + else response.writeHead(404).end("unavailable"); + }); + info.fallbackUrls = [new URL("mirror.jar", info.url).href]; + + await assert.rejects(prepareGenerator(info), /SHA-256 mismatch/); + assert.deepEqual(await readdir(directory), []); +}); + +test("unavailable primary and fallback leave no cached artifact", async (t) => { + const { directory, info } = await fixture(t, (_request, response) => { + response.writeHead(404).end("unavailable"); + }); + info.fallbackUrls = [new URL("mirror.jar", info.url).href]; + + await assert.rejects(prepareGenerator(info), /404/); + assert.deepEqual(await readdir(directory), []); +}); diff --git a/docs/en/docs/operate/database-migrations.md b/docs/en/docs/operate/database-migrations.md index e703e270f0..ef4da92a54 100644 --- a/docs/en/docs/operate/database-migrations.md +++ b/docs/en/docs/operate/database-migrations.md @@ -149,15 +149,14 @@ read-only no-op. See [Migrate to Atomic Memory](atomic-memory-migration.md). ## Migration names and software versions -The target release is **PowerContext 1.5.2**. New Server migration names use -`v___pr`, for example `v1_5_2_pr2674`. -The version is the target release declared when the migration is registered, the PR number -identifies the introducing PR in this repository. Each PR adds at most one logical schema -revision, shared by its backend implementations; there is no PR-local sequence. Keep the full ID within the existing 32-character storage limit. +The target release is **PowerContext 1.5.2**. Schema changes for the next release accumulate +in the shared unpublished revision `000`. A release PR freezes that draft as `v__`; +there is no PR number or step suffix. Execution follows `down_revision`, not name sorting. +Without a schema change, a release keeps the previous database head and adds no revision. -Historical names retain `v___`, with a three-digit sequence -within the release. Historical sequence `000` identifies a registered baseline; upgrade -steps start at `001`. The following registered names remain unchanged: +Existing three-digit sequence names, PR-based names and legacy aliases remain readable and immutable. +Historical sequence `000` in a name such as `v1_3_0_000` identifies a baseline; it is distinct from the +literal mutable draft ID `000`. The following registered names remain unchanged: | Migration name | Software release | Step | Compatible stored revision | Meaning | | --- | --- | --- | --- | --- | @@ -191,13 +190,15 @@ contains `name`, `software_version`, `sequence` and the compatible `revision` ID {"revision":"v1_5_0_001","name":"v1_5_0_001","software_version":"1.5.0","sequence":1} ``` -For a PR-scoped name, the same fields describe the registration target; `sequence` is `null`: +For the unpublished draft, the descriptor is: ```json -{"revision":"v1_5_2_pr2674","name":"v1_5_2_pr2674","software_version":"1.5.2","sequence":null} +{"revision":"000","name":"000","software_version":null,"sequence":null} ``` -`sequence` remains populated for historical release-sequence names only. It does not define execution order. +After a release PR declares a target version and freezes the draft, `software_version` reports +that release and `sequence` remains `null`. Historical sequence names retain their numeric sequence; +previous PR-based names also remain supported. These descriptors never define execution order. The software version describes the registered database state, not the currently running binary or the source of an interrupted maintenance window. A release without storage changes may reuse @@ -208,33 +209,90 @@ frozen resources and recovery evidence. Their release-based names are display al additional executable revisions or accepted replacement IDs for stamping a database. This keeps existing plans and original backups usable. Partial prototype bundles keep their own opaque IDs. -For a new Server migration, create a draft PR first and use its PR-scoped name directly as -Alembic `revision`. Register its schema, domain steps and recovery checkpoints as usual. -Agree on the target release before the first schema PR registers a revision, using the version -already declared in `openapi/powercontext.yaml` and `release/upgrade-support.json`; feature PRs -must not independently bump it. At registration, the new prefix must match both declarations; -this requirement does not apply retroactively when the target release changes. A single revision -may contain multiple DDL operations, data tasks and validations, all executed during stopped-write -maintenance. If independent revision checkpoints are necessary, split the work into dependent PRs. The names above illustrate the naming format; they -do not register additional migrations or change the current head. - -Before merging, update against master and check the combined changes for duplicate IDs. -Reconcile unpublished dependencies and any conflicting schema operations, then rerun migration -validation and keep a single head, as required by [RFC #1771](../../rfcs/1771-unified-database-migrations.md). -`down_revision` references the actual predecessor (`v1_5_2_pr2639` when appending directly to the -current head). The framework follows this chain, not version, PR-number or lexical ordering. -For example, if the PR containing `v1_5_2_pr2688` merges first, `v1_5_2_pr2674` can depend -on it without either ID changing. A development database that already ran the earlier branch -chain must be rebuilt or use an explicitly validated conversion; editing `down_revision` does -not apply missing predecessors to that database. - -Release preparation records the package version and database head in the release notes and -verifies the supported upgrades. It must not defer dependency reconciliation until publication. -`make version-bump` updates release references, not migration IDs. Once registered, names and -version prefixes remain unchanged even if a PR ships later than planned; release notes identify -the actual shipping version. A release without schema changes adds no revision and keeps its head. -Existing `pc_schema_revision` values, frozen resources, plans and checksums remain unchanged; -`v1_5_0_005` is the database head of the published 1.5.2, and `v1_5_2_pr2639` is registered after it. Published migrations must not be rewritten. +### Develop the shared cumulative migration + +The first schema-changing PR after a release creates +`src/powercontext/builtin/persistence/migrations/server_resources/versions/000.py` with +`revision = "000"` and `down_revision` pointing to the latest frozen head. The corresponding native +entry is `server_resources/mysql/versions/000.py`. Later PRs edit this same logical migration. +A migration can contain multiple table changes, data transformations and validations; all execute +within stopped-write maintenance, without restarting the service between operations. + +SQL alone is not the complete migration contract. Update the main and registered source manifests, +SQLite fingerprints, native recovery layouts and applicable vector/Code profiles together. Register +new domain tasks and their resources under `000`. Keep draft-owned filenames explicit, such as +`schemas/sqlite-000.json`, `schemas/mysql-000.json` or `domain_000.py`, and use complete literal IDs +and paths in Python/JSON registrations. Keep SQL/data literals unchanged; the freeze tool rewrites +identity and registered path strings, not arbitrary text or generated paths. Do not share mutable +draft resources with frozen revisions. Do not add an empty draft to releases without storage changes. + +Before merging, update against master and resolve the cumulative script and registration conflicts. +Run `make schema-check` and the affected migration tests. CI compares frozen history with the PR base, +checks the SQLite/native dependency chains, and executes the cumulative SQLite upgrade from registered +sources with and without vectors. Existing selected installed-release acceptance also runs before merge; +PRs currently select SQLite, while full native acceptance remains scheduled/manual and release-gated. +A passing individual branch is insufficient: require checks on the merged result and enforce an +up-to-date branch or merge queue through repository settings. This PR workflow does not configure +GitHub branch protection automatically. + +Only upgrades between supported released versions are promised. Databases and plans produced by +unpublished `000` are disposable. Rebuild development databases when `000` changes or is frozen; +do not replay the edited draft on an already-stamped database or stamp `000` as a release. No +compatibility bridge from a development draft to the frozen release is provided. + +### Transition existing schema PRs + +The cumulative workflow applies when a schema PR updates against master. Legacy sequence and PR-based +revisions already in the master baseline remain immutable, including `v1_5_2_pr2639`. The baseline +comparison protects their IDs, resources and dependencies; adopting this workflow does not rename them. + +An unmerged PR that introduces an unpublished revision such as `v1_5_2_pr2674` must: + +1. Update against the latest master and identify only changes not already present in its frozen history + or shared draft. Do not copy SQL from a previous release back into the new draft. +2. Fold those changes into the existing `000`, or create it with `down_revision` pointing to the latest + frozen head if no draft exists. Reconcile execution order and dependencies with the cumulative changes. +3. Replace the superseded unpublished SQLite/native revision entries and draft-owned resource names; + update manifests, fingerprints, checkpoints, domain tasks and applicable source/vector/Code registrations + together. Preserve every frozen revision and its resources. +4. Rebuild development databases and plans created from the unpublished revision. Run `make schema-check`, + `uv run --locked python scripts/schema_release.py check --base-ref origin/master`, affected migration + tests and the selected upgrade acceptance on the merged result before merging. + +The PR opening date does not exempt new revisions from the gate. An open PR can merge after adoption by +following this conversion; it does not have to merge first. A legacy revision already merged into master +before adoption becomes part of the protected baseline. Published revisions must never be converted to +`000`; any further changes belong in the next cumulative migration. Release PRs freeze the accumulated +`000` through the normal release process. + +### Freeze in the release PR + +After resolving the release version, run these commands with its actual stable `X.Y.Z`: + +```bash +make version-bump VERSION=X.Y.Z +make schema-freeze VERSION=X.Y.Z +make release-check +``` + +The first command synchronizes release declarations and generated APIs. The second requires those +declarations to agree, validates all source chains, and freezes `000` as `vX_Y_Z`. It renames +000-owned resources and updates literal references in manifests, scripts and profiles. It validates +the complete staged result and unchanged historical revision checksums before writing, then refreshes +the persistence digest. Review the existing compatibility rationale rather than treating this digest +refresh as upgrade acceptance. If no draft exists, freezing is a no-op; existing heads remain unchanged. + +The release PR records the software version and schema head in release notes and verifies the exact +publication artifacts using the existing upgrade gate. Both release source checks and wheel acceptance +reject an unfrozen `000`, including releases that skip upgrade acceptance. Freezing does not merge SQL +at publication time: CI already validated the cumulative changes before their PRs merged. After release, +the next schema change starts a new `000` depending on the frozen head. The released scripts and resources +then remain immutable; failures are fixed in the next cumulative migration. + +Existing `pc_schema_revision` values, resources, plans and checksums remain unchanged by this workflow +change. The released 1.5.2 database head is `v1_5_0_005`; the existing `v1_5_2_pr2639` revision +follows it and remains unchanged. New cumulative drafts depend on that current head. No production +draft is introduced without a real storage change. ## Initialization and maintenance ownership diff --git a/docs/zh/docs/operate/database-migrations.md b/docs/zh/docs/operate/database-migrations.md index 757b309659..d3c65c82ca 100644 --- a/docs/zh/docs/operate/database-migrations.md +++ b/docs/zh/docs/operate/database-migrations.md @@ -121,14 +121,12 @@ MySQL 兼容后端的结构反射支持 CHECK 表达式中的二元 `+`、`-`、 ## 迁移编号与软件版本 -目标发布版本为 **PowerContext 1.5.2**。新增 Server 迁移名称采用 -`v<主版本>_<次版本>_<补丁版本>_pr`,例如 `v1_5_2_pr2674`。 -版本号是登记迁移时声明的目标发布版本,PR 号标识本仓库中引入迁移的 PR。 -每个 PR 最多新增一个逻辑 schema revision,各数据库后端实现共用该编号,不设 PR 内序号。 -完整 ID 必须满足现有存储的 32 字符上限。 +目标发布版本为 **PowerContext 1.5.2**。下一个版本的结构变更累积在公共未发布 revision `000` 中。 +发版 PR 将其冻结为 `v<主版本>_<次版本>_<补丁版本>`,不带 PR 号或步骤后缀。 +执行顺序由 `down_revision` 决定,不按名称排序。没有结构变化的发布沿用原数据库 head,不新增 revision。 -历史名称保留 `v<主版本>_<次版本>_<补丁版本>_<序号>` 格式,序号在同一版本内使用三位数字。 -历史序号 `000` 表示已登记的基线,升级步骤从 `001` 开始。以下已登记名称保持不变: +已有三位序号格式、PR 号格式及历史别名继续兼容,且不可改写。`v1_3_0_000` 等历史名称中的 +序号 `000` 表示基线,与完整 ID 为 `000` 的可变开发迁移不同。以下已登记名称保持不变: | 迁移名称 | 所属软件版本 | 步骤 | 兼容保留的 revision | 含义 | | --- | --- | --- | --- | --- | @@ -162,13 +160,14 @@ MySQL 兼容后端的结构反射支持 CHECK 表达式中的二元 `+`、`-`、 {"revision":"v1_5_0_001","name":"v1_5_0_001","software_version":"1.5.0","sequence":1} ``` -对于包含 PR 号的名称,相同字段描述登记时的目标版本,`sequence` 为 `null`: +未发布累计迁移的描述为: ```json -{"revision":"v1_5_2_pr2674","name":"v1_5_2_pr2674","software_version":"1.5.2","sequence":null} +{"revision":"000","name":"000","software_version":null,"sequence":null} ``` -`sequence` 仅对历史版本序号格式保留数值,不决定执行顺序。 +发版 PR 声明目标版本并冻结后,`software_version` 表示该发布版本,`sequence` 仍为 `null`。 +历史序号格式继续返回原序号,已有 PR 号格式也继续兼容。这些展示字段不决定执行顺序。 这里的软件版本描述已登记的数据库状态,不代表当前运行的软件包版本,也不代表中断维护窗口最初的来源。 没有存储变化的软件发布可以复用同一数据库 revision。命名不代表升级已经通过验收,完整发布门禁仍然生效。 @@ -177,28 +176,72 @@ MySQL 兼容后端的结构反射支持 CHECK 表达式中的二元 `+`、`-`、 新名称是它们的展示别名,不是额外的可执行 revision,也不能作为替代 ID 手工写入版本表。 这样可以继续使用已有计划和原始备份。局部原型 bundle 保留自己的独立编号。 -新增 Server 迁移前先创建 Draft PR,直接使用包含该 PR 号的名称作为 Alembic `revision`, -并正常登记结构、领域步骤和恢复检查点。在首个表结构 PR 登记迁移前统一确定目标发布版本, -使用 `openapi/powercontext.yaml` 与 `release/upgrade-support.json` 中已声明的版本; -功能 PR 不得各自升级目标版本。新增迁移登记时,名称前缀必须与这两处声明一致; -目标版本后续变化时,这项要求不追溯到已有迁移。一个 revision 可以包含多条 DDL、数据任务和校验, -统一在停写维护期间执行。如果确实需要独立的 revision 检查点,应拆成有依赖关系的多个 PR。 -上面的名称仅用于演示命名格式,不登记额外迁移,也不改变当前 head。 - -合并前同步 master,检查合并后的变更中是否存在重复 ID,整理未发布迁移的依赖与冲突的结构操作, -重新验证迁移并保持单一 head,遵循 [RFC #1771](../../rfcs/1771-unified-database-migrations.md)。 -`down_revision` 引用前一步的实际 ID;直接追加在当前 head 后时引用 `v1_5_2_pr2639`。 -框架按依赖链执行,不按版本、PR 号或名称字典序排序。例如,包含 `v1_5_2_pr2688` 的 PR -先合并时,`v1_5_2_pr2674` 可以依赖它,两者的 ID 都不必改变。 -已经执行旧分支迁移链的开发数据库必须重建,或采用明确验证过的转换方案;修改 `down_revision` -不会为该数据库自动执行缺失的前置迁移。 - -发版准备在发布说明中记录软件版本与数据库 head,并验证支持的升级路径,不能把依赖整理推迟到发布时。 -`make version-bump` 更新发布引用,不修改迁移 ID。名称与版本前缀一经登记便保持不变, -即使 PR 延期发布也不改名;实际交付版本由发布说明记录。没有结构变化的发布不新增 revision,沿用原 head。 -现有 `pc_schema_revision` 值、冻结资源、计划与校验和保持不变;`v1_5_0_005` 是已发布的 1.5.2 的数据库 head, -`v1_5_2_pr2639` 登记在它之后。 -已发布迁移不得重写。 +### 开发公共累计迁移 + +发布后第一个涉及表结构的 PR 创建 +`src/powercontext/builtin/persistence/migrations/server_resources/versions/000.py`, +设置 `revision = "000"`,`down_revision` 指向最近的冻结 head。 +原生后端入口为 `server_resources/mysql/versions/000.py`。后续 PR 修改同一个逻辑迁移。 +一个迁移可以包含多张表的变更、数据转换及校验,全部在停写维护期间执行,不在操作之间重启服务。 + +SQL 不是完整的迁移契约。必须同步更新主清单与已登记来源清单、SQLite 指纹、原生恢复布局及适用的 +向量/Code profile,并将新增领域任务和资源登记到 `000`。开发迁移专属文件名应明确包含 `000`, +例如 `schemas/sqlite-000.json`、`schemas/mysql-000.json` 或 `domain_000.py`;Python/JSON 登记使用 +完整的字面量 ID 和路径。SQL 和数据字面量保持不变;冻结工具替换身份与登记路径字符串,不替换任意 +文本或动态生成的路径。已冻结迁移不得依赖可变的开发资源。没有存储变更时不创建空迁移。 + +合并前同步 master,解决累计脚本及登记信息的冲突,运行 `make schema-check` 和受影响的迁移测试。 +CI 对照 PR 基线检查冻结历史,校验 SQLite/原生后端依赖链,并从已登记来源执行包含向量开关配置的 +SQLite 累计升级。现有已发布安装包升级验收也在合并前按选择执行;PR 当前选择 SQLite,完整原生后端 +验收仍由定时、手动和发布门禁执行。单个分支通过不足以证明合并结果正确;必须要求合并结果通过检查, +并通过仓库设置要求分支保持最新或使用合并队列。此 PR 流程不会自动配置 GitHub 分支保护。 + +仅承诺受支持的正式版本之间升级。未发布 `000` 生成的数据库和计划可以丢弃;`000` 修改或冻结后, +重建开发数据库,不在已登记的开发库上重放修改后的脚本,也不要将 `000` 手工 stamp 为正式版本。 +不提供开发迁移到冻结版本的兼容桥接。 + +### 迁移正在开发的表结构 PR + +涉及表结构的 PR 同步 master 后适用公共累计迁移流程。已进入 master 基线的历史序号和 PR 号格式 +revision 保持不可变,包括 `v1_5_2_pr2639`。基线比较保护它们的 ID、资源及依赖;采用本流程不重命名这些 revision。 + +尚未合并且引入了 `v1_5_2_pr2674` 等未发布 revision 的 PR 必须: + +1. 同步最新 master,仅识别尚未包含在冻结历史或公共开发迁移中的变更,不把上一发布版本的 SQL 再复制回新开发迁移。 +2. 将这些变更归入已有的 `000`;若尚不存在,则创建 `000`,使 `down_revision` 指向最新冻结 head。 + 与已有累计变更协调执行顺序及依赖。 +3. 替换被取代的未发布 SQLite/原生后端 revision 入口及开发迁移专属资源名称,同步更新清单、指纹、检查点、 + 领域任务和适用的来源/向量/Code 登记。保留所有冻结 revision 及其资源。 +4. 重建由未发布 revision 生成的开发数据库和计划。合并前针对合并结果运行 `make schema-check`、 + `uv run --locked python scripts/schema_release.py check --base-ref origin/master`、受影响的迁移测试及所选升级验收。 + +PR 创建时间不构成新增 revision 的门禁豁免。尚未合并的 PR 可以按上述流程转换后再合入,无需抢在本规范生效前合并。 +在规范生效前已经合入 master 的历史 revision 纳入受保护基线。已发布 revision 绝不能改为 `000`, +后续变更应进入下一个累计迁移。发版 PR 按正常发布流程冻结累计完成的 `000`。 + +### 在发版 PR 中冻结 + +确定发布版本后,用实际的稳定版本号替换下面的 `X.Y.Z`: + +```bash +make version-bump VERSION=X.Y.Z +make schema-freeze VERSION=X.Y.Z +make release-check +``` + +第一条命令同步发布声明和生成的 API。第二条要求版本声明一致,校验所有来源链,将 `000` 冻结为 +`vX_Y_Z`,重命名专属资源,并更新清单、脚本和 profile 中的字面量引用。 +写入前验证完整的暂存结果及历史 revision 校验和保持不变,再刷新持久化摘要。 +仍需评审兼容性说明,摘要刷新不代表升级验收通过。没有开发迁移时冻结命令不修改资源,继续沿用原 head。 + +发版 PR 在发布说明中记录软件版本与 schema head,并通过现有升级门禁验证最终发布包。 +发布源码检查和 wheel 验收都拒绝未冻结的 `000`,跳过升级验收的发布也不能携带它。 +冻结不是在发布时重新整合 SQL:累计变更已在各 PR 合并前通过 CI。发布后的下一次表结构变更重新创建 +`000`,依赖刚冻结的 head。已发布脚本与资源保持不可变,修复进入下一个累计迁移。 + +本流程调整不改变已有 `pc_schema_revision` 值、资源、计划和校验和。 +已发布的 1.5.2 数据库 head 为 `v1_5_0_005`;已有 `v1_5_2_pr2639` 登记在它之后,保持不变。 +新的累计开发迁移依赖这一当前 head。没有实际存储变化时不引入生产开发迁移。 ## 初始化与维护职责 diff --git a/release/upgrade-support.json b/release/upgrade-support.json index 129e26b437..c82db344ab 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.5.2", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "2fe54ccae7f9a4316afbb8f76a84e979f6ef6721f86b048e71568815b4c74a55", - "rationale": "Revision v1_5_2_pr2639 follows v1_5_0_005 on both registered source chains and all vector/Code profiles. It adds pc_source_runners (name, display name, registering principal type and identifier, nullable registration ID unique per principal, registration time, reported capabilities and digest, nullable last_seen_at) and pc_source_collect_targets (Scope and target identity, runner, capability, target key unique per Scope, runner and capability, parameters, enabled, configuration version, update audit, and runner-written status columns, including whether the last attempt left more to collect), and drops pc_source_write_plugins. The source_collection domain step refuses the upgrade while pc_source_write_plugins lists a plugin, so no loaded write plugin is lost silently; otherwise no existing record is rewritten. Earlier revision resources, frozen checksums and SQLite fingerprints are unchanged; the MySQL layout for the new tables is registered from the same SQLAlchemy DDL. Target checkpoints reuse pc_connector_checkpoints keyed by (scope_id, target_id) with a constant connector version; a commit for a collection target is validated against the target's runner, enabled state and configuration version in the transaction that writes the checkpoint and status. Portable bundles add source_runner (name, display name, registering principal and registration ID) and source_collect_target records; reported capabilities, last-seen time and target status restart empty. Revision v1_5_0_005 follows v1_5_0_004 on both registered source chains and all vector/Code profiles. It removes the storage of the previous Artifact plugin framework (family schemas, declarative search and vector index tables, and the plugin registration columns of pc_artifact_processing_binding_states) and adds the nullable pc_artifacts.metadata column, which records the plugin name and code digest of plugin-written revisions and stays NULL for built-in families. Its domain preflight refuses the upgrade while the previous framework still holds any registration, declaration or index row, and native maintenance refuses registered native vector spaces, so no data is dropped silently. Its readiness accepts directory-loaded 'plugin:' Processing bindings without durable registration and keeps the frozen built-in full-text checks; plugin families write no rows to pc_artifact_fts. Revision reads omit metadata so domain steps at earlier registered revisions still run. Portable Artifact revision records advance to schema version 3 with metadata, and version 2 records restore with metadata NULL. Earlier revision resources, fingerprints and checksums remain unchanged; local SQLite migration tests do not establish native seekDB/OceanBase or installed-release acceptance. Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use v___pr names directly, with the target version fixed at registration and at most one logical schema revision per PR. Revision descriptors parse this format while preserving historical release sequences, legacy aliases and opaque custom IDs. The sequence field is null for new PR-scoped names; dependency order still follows down_revision. This naming support changes no registered schema, frozen resource, persisted revision, plan identity or checksum. Software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. Gateway authorization adds the Scope-level gateway.user role and gateway.invoke action to the existing binding vocabulary. It does not change stored binding structure or migration resources: existing records retain their role and do not implicitly gain gateway.invoke; new grants use the existing binding persistence and resource validation. Existing upgrade support remains upgrade-required and is not certified by this digest refresh. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources. SQLite Topic Memory full-text helper version 2 assigns each Scope's helper rows to a hashed 2^32-rowid range above every rowid that version 1 assigned, so Topic replacement and search bound their FTS5 cursors to one Scope's range. Virtual table definitions, registered schema fingerprints, migration resources and authoritative active Topic rows are unchanged. Unmanaged initialization and the existing s1400 domain step rebuild version-1 helper rows from the active tables with exact identities and revisions; a managed database that still holds version-1 helper rows keeps the previous identity filters until the helper is rebuilt. bm25 statistics remain table-wide, so search hits, ordering and scores are unchanged. The standalone seekdb maintenance identity is derived from @@server_uuid and DATABASE() when ob_compatibility_mode is missing, NULL, or empty and VERSION() contains -OceanBase seekdb-. The db-migrate identity probe and the server-run tenant gate share one compatibility classifier; ORACLE and non-seekdb servers remain rejected. This is an admission-only change and does not alter registered table layouts, migration resources, persisted row encodings, or public interfaces. Source writes and text retrieval reuse parameterized SQL structures with fresh Scope, identity, revision, binding and increment values on every execution. Only the fixed built-in Content manifest construction and exact validated payload bytes reuse cached metadata; database registration and indexed-identity checks remain current, and callers receive deep copies. MySQL/OceanBase journal allocation retains SELECT FOR UPDATE; SQLite retains its write reservation. Concurrent Content captures coalesce already queued requests into bounded transactions, isolate individual failures after batch rollback, replay stable identities on cancellation and drain admitted callers during shutdown. No schema, migration, stored encoding, Source identity, journal ordering, processing counter semantics or upgrade support claims change. A Topic Memory window attempt whose publication loses the Topic head CAS to a concurrent replace or Dream records last_error_code head_conflict on its existing pc_topic_memory_work_budgets row, and the attempt ceiling and the next attempt's counter treat that one attempt as not spent. Provider request and token charges stay committed and are never refunded. No table layout, column, constraint, migration resource, revision checksum or row encoding changes; existing rows never carry head_conflict, so their counters and blocks keep their meaning. A binary without this change counts such an attempt as spent, which can only stop that frontier sooner. The Dashboard processing page reads the existing Source journal and Artifact lineage relation and marks only Sources with an exact Artifact citation. It introduces no new table or public JSON interface and does not reconstruct execution history, delivery or adoption. Source journal envelopes record an optional UTC saved_at timestamp for newly inserted records. This adds write metadata inside the existing powercontext-source-v1 payload, without changing registered tables, schema revisions, frozen migration resources or checksums. Historical envelopes and raw legacy payloads remain readable with unknown save time; replay does not invent a timestamp, and handoff receipt upgrades preserve the original timestamp. Source identity, material digests, journal positions and processing intent identities remain unchanged. This compatibility review does not establish installed-release upgrade acceptance; the upgrade-required policy and complete automatic matrix remain unchanged. Relocating access control from the Server package to the built-in runtime, removing the unused Source-cursor discovery query, and moving the code command out of the built-in Code package are code-organization changes. They change neither registered table layout nor migration data encodings: the generated table and index DDL for every persistence and access table is identical on the SQLite and MySQL dialects. Native MySQL schema recognition now requires the absence of core tables and columns removed by registered transitions before accepting a recovery prefix or completed revision. Independent extension tables and columns remain supported. This executes the existing v1_5_0_005 cleanup without changing frozen resources, revision checksums, stored encodings or the required installed-release acceptance matrix. Request-serving plugin hosts reconstruct authorization without requiring a background service identity; scheduled workers retain the explicit identity requirement. This changes only process-local authorization configuration, with no schema, migration, persisted encoding or upgrade support changes. OceanBase vector SQL parameters and literals serialize finite float32 arrays with orjson while retaining pyobvector dimension validation, reference readback and special-value handling. Vector column types and stored float32 values are unchanged. Source evidence bindings are inserted as a batch in the accepting Source transaction with the same exact identities and immutable declarations. Current Atomic Memory verification reads projection pages and vector presence while preserving authoritative content, state, tag, profile, evidence and vector-dimension checks under the existing snapshot contract. These changes introduce no schema revisions, registered migration resource changes, historical rewrites or new installed-release upgrade claims. The OceanBase and seekdb profiles gain a helper that builds engines for another database of the same tenant or instance with the deployment's connection settings; plugin hosts and Workers use it to open each plugin's own database. It reads and writes no core table and changes no schema, migration, persisted encoding or upgrade support. Migration refusal diagnostics now state that retained legacy plugin records have no supported in-place upgrade path; unloading or exporting does not clear them. This wording correction changes no schema, rejection criteria or data transformation. Native managed-schema compatibility compares required columns, indexes and normalized CHECK definitions without deep-copying unrelated extension tables. Validation remains read-only and preserves required-schema admission, caller-owned metadata and all registered schema, data and migration formats. The recurrence ledger exposes read-only queries over existing pc_recurrence_observation rows: observations_for_target returns one bucket, and event_counts_for_target aggregates its three event counts in SQL. Both filter by the indexed revision columns and by the signature hash plus its plaintext. They add no table, column, index, migration, stored encoding or write path, and existing ledger rows, upgrade acceptance cases and policy mode are unchanged. Complete Atomic Memory related enumeration admits a memory when the distinct candidate terms it contains meet the lexical threshold of the candidate's distinct terms, or number at least the minimum match count and cover the coverage fraction of the memory's own indexed words, so a long candidate reaches a short memory of the same fact; window siblings use the same rule. The per-row requirement is computed from the existing searchable text in SQL on SQLite, seekDB and OceanBase, and the native OceanBase path adds one MATCH block that applies whole-word coverage only to memories short enough to qualify below the candidate threshold. This threshold change leaves search, recovery probes, stored projections, registered schema resources and migrations unchanged. Plugin reloading can unregister, in the Server process, the Artifact access profile a plugin family registered when that plugin is removed or renames its family; built-in family profiles are never removed, and no table layout, migration resource, frozen checksum or persisted encoding changes. Atomic Memory evidence capture batches committed revisions in the existing transaction while preserving immutable first-writer histories, per-revision Source ownership and projection encoding. Historical Source reads join material and immutable bindings and batch retained manifests by exact definition version; a damaged ancillary manifest neutralizes only its own identity. Complete related vector recall validates all eligible projections and computes distances in one statement, rejecting invalid projections even outside the distance threshold. SQLite FTS query selection and impossible FTS recovery-probe short-circuiting change read execution only. No table, migration resource, stored encoding, journal order or installed-release upgrade support claim changes. Related hybrid ranks observe lexical results and complete vector validation in one SQL statement; page bodies and current authority remain separately admitted. Each backend prepares and decodes its rank query at one boundary; hybrid ranks retain RRF fusion when no lexical query can be formed. Single and batched active projection publication share current-tag loading under the caller transaction. Historical manifests use the same tolerant batch decoder for one or many identities. These read-execution changes preserve table layouts, stored formats, migrations and upgrade claims. Related hybrid ranks preserve the per-row lexical coverage rule of current related recall, including native full-text query blocks. No migration revision or persisted encoding changes." + "persistence_sha256": "e4aad4693caeef9e334e0c4614815f4f7edac3169819dc427163900be3964369", + "rationale": "Revision v1_5_2_pr2639 follows v1_5_0_005 on both registered source chains and all vector/Code profiles. It adds pc_source_runners (name, display name, registering principal type and identifier, nullable registration ID unique per principal, registration time, reported capabilities and digest, nullable last_seen_at) and pc_source_collect_targets (Scope and target identity, runner, capability, target key unique per Scope, runner and capability, parameters, enabled, configuration version, update audit, and runner-written status columns, including whether the last attempt left more to collect), and drops pc_source_write_plugins. The source_collection domain step refuses the upgrade while pc_source_write_plugins lists a plugin, so no loaded write plugin is lost silently; otherwise no existing record is rewritten. Earlier revision resources, frozen checksums and SQLite fingerprints are unchanged; the MySQL layout for the new tables is registered from the same SQLAlchemy DDL. Target checkpoints reuse pc_connector_checkpoints keyed by (scope_id, target_id) with a constant connector version; a commit for a collection target is validated against the target's runner, enabled state and configuration version in the transaction that writes the checkpoint and status. Portable bundles add source_runner (name, display name, registering principal and registration ID) and source_collect_target records; reported capabilities, last-seen time and target status restart empty. Revision v1_5_0_005 follows v1_5_0_004 on both registered source chains and all vector/Code profiles. It removes the storage of the previous Artifact plugin framework (family schemas, declarative search and vector index tables, and the plugin registration columns of pc_artifact_processing_binding_states) and adds the nullable pc_artifacts.metadata column, which records the plugin name and code digest of plugin-written revisions and stays NULL for built-in families. Its domain preflight refuses the upgrade while the previous framework still holds any registration, declaration or index row, and native maintenance refuses registered native vector spaces, so no data is dropped silently. Its readiness accepts directory-loaded 'plugin:' Processing bindings without durable registration and keeps the frozen built-in full-text checks; plugin families write no rows to pc_artifact_fts. Revision reads omit metadata so domain steps at earlier registered revisions still run. Portable Artifact revision records advance to schema version 3 with metadata, and version 2 records restore with metadata NULL. Earlier revision resources, fingerprints and checksums remain unchanged; local SQLite migration tests do not establish native seekDB/OceanBase or installed-release acceptance. Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. Unpublished Server schema changes accumulate in a shared 000 revision and its registered resources. Release preparation freezes this draft as v__ after declaring the target version. Development databases are disposable; only supported released-version upgrades are promised. Revision descriptors parse this format while preserving historical release sequences, legacy aliases and opaque custom IDs. The sequence field is null for frozen release names and 000; the draft has no software_version. Historical sequence and PR-based names remain readable. Dependency order still follows down_revision. This naming support changes no registered schema, frozen resource, persisted revision, plan identity or checksum. Software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. Gateway authorization adds the Scope-level gateway.user role and gateway.invoke action to the existing binding vocabulary. It does not change stored binding structure or migration resources: existing records retain their role and do not implicitly gain gateway.invoke; new grants use the existing binding persistence and resource validation. Existing upgrade support remains upgrade-required and is not certified by this digest refresh. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources. SQLite Topic Memory full-text helper version 2 assigns each Scope's helper rows to a hashed 2^32-rowid range above every rowid that version 1 assigned, so Topic replacement and search bound their FTS5 cursors to one Scope's range. Virtual table definitions, registered schema fingerprints, migration resources and authoritative active Topic rows are unchanged. Unmanaged initialization and the existing s1400 domain step rebuild version-1 helper rows from the active tables with exact identities and revisions; a managed database that still holds version-1 helper rows keeps the previous identity filters until the helper is rebuilt. bm25 statistics remain table-wide, so search hits, ordering and scores are unchanged. The standalone seekdb maintenance identity is derived from @@server_uuid and DATABASE() when ob_compatibility_mode is missing, NULL, or empty and VERSION() contains -OceanBase seekdb-. The db-migrate identity probe and the server-run tenant gate share one compatibility classifier; ORACLE and non-seekdb servers remain rejected. This is an admission-only change and does not alter registered table layouts, migration resources, persisted row encodings, or public interfaces. Source writes and text retrieval reuse parameterized SQL structures with fresh Scope, identity, revision, binding and increment values on every execution. Only the fixed built-in Content manifest construction and exact validated payload bytes reuse cached metadata; database registration and indexed-identity checks remain current, and callers receive deep copies. MySQL/OceanBase journal allocation retains SELECT FOR UPDATE; SQLite retains its write reservation. Concurrent Content captures coalesce already queued requests into bounded transactions, isolate individual failures after batch rollback, replay stable identities on cancellation and drain admitted callers during shutdown. No schema, migration, stored encoding, Source identity, journal ordering, processing counter semantics or upgrade support claims change. A Topic Memory window attempt whose publication loses the Topic head CAS to a concurrent replace or Dream records last_error_code head_conflict on its existing pc_topic_memory_work_budgets row, and the attempt ceiling and the next attempt's counter treat that one attempt as not spent. Provider request and token charges stay committed and are never refunded. No table layout, column, constraint, migration resource, revision checksum or row encoding changes; existing rows never carry head_conflict, so their counters and blocks keep their meaning. A binary without this change counts such an attempt as spent, which can only stop that frontier sooner. The Dashboard processing page reads the existing Source journal and Artifact lineage relation and marks only Sources with an exact Artifact citation. It introduces no new table or public JSON interface and does not reconstruct execution history, delivery or adoption. Source journal envelopes record an optional UTC saved_at timestamp for newly inserted records. This adds write metadata inside the existing powercontext-source-v1 payload, without changing registered tables, schema revisions, frozen migration resources or checksums. Historical envelopes and raw legacy payloads remain readable with unknown save time; replay does not invent a timestamp, and handoff receipt upgrades preserve the original timestamp. Source identity, material digests, journal positions and processing intent identities remain unchanged. This compatibility review does not establish installed-release upgrade acceptance; the upgrade-required policy and complete automatic matrix remain unchanged. Relocating access control from the Server package to the built-in runtime, removing the unused Source-cursor discovery query, and moving the code command out of the built-in Code package are code-organization changes. They change neither registered table layout nor migration data encodings: the generated table and index DDL for every persistence and access table is identical on the SQLite and MySQL dialects. Native MySQL schema recognition now requires the absence of core tables and columns removed by registered transitions before accepting a recovery prefix or completed revision. Independent extension tables and columns remain supported. This executes the existing v1_5_0_005 cleanup without changing frozen resources, revision checksums, stored encodings or the required installed-release acceptance matrix. Request-serving plugin hosts reconstruct authorization without requiring a background service identity; scheduled workers retain the explicit identity requirement. This changes only process-local authorization configuration, with no schema, migration, persisted encoding or upgrade support changes. OceanBase vector SQL parameters and literals serialize finite float32 arrays with orjson while retaining pyobvector dimension validation, reference readback and special-value handling. Vector column types and stored float32 values are unchanged. Source evidence bindings are inserted as a batch in the accepting Source transaction with the same exact identities and immutable declarations. Current Atomic Memory verification reads projection pages and vector presence while preserving authoritative content, state, tag, profile, evidence and vector-dimension checks under the existing snapshot contract. These changes introduce no schema revisions, registered migration resource changes, historical rewrites or new installed-release upgrade claims. The OceanBase and seekdb profiles gain a helper that builds engines for another database of the same tenant or instance with the deployment's connection settings; plugin hosts and Workers use it to open each plugin's own database. It reads and writes no core table and changes no schema, migration, persisted encoding or upgrade support. Migration refusal diagnostics now state that retained legacy plugin records have no supported in-place upgrade path; unloading or exporting does not clear them. This wording correction changes no schema, rejection criteria or data transformation. Native managed-schema compatibility compares required columns, indexes and normalized CHECK definitions without deep-copying unrelated extension tables. Validation remains read-only and preserves required-schema admission, caller-owned metadata and all registered schema, data and migration formats. The recurrence ledger exposes read-only queries over existing pc_recurrence_observation rows: observations_for_target returns one bucket, and event_counts_for_target aggregates its three event counts in SQL. Both filter by the indexed revision columns and by the signature hash plus its plaintext. They add no table, column, index, migration, stored encoding or write path, and existing ledger rows, upgrade acceptance cases and policy mode are unchanged. Complete Atomic Memory related enumeration admits a memory when the distinct candidate terms it contains meet the lexical threshold of the candidate's distinct terms, or number at least the minimum match count and cover the coverage fraction of the memory's own indexed words, so a long candidate reaches a short memory of the same fact; window siblings use the same rule. The per-row requirement is computed from the existing searchable text in SQL on SQLite, seekDB and OceanBase, and the native OceanBase path adds one MATCH block that applies whole-word coverage only to memories short enough to qualify below the candidate threshold. This threshold change leaves search, recovery probes, stored projections, registered schema resources and migrations unchanged. Plugin reloading can unregister, in the Server process, the Artifact access profile a plugin family registered when that plugin is removed or renames its family; built-in family profiles are never removed, and no table layout, migration resource, frozen checksum or persisted encoding changes. Atomic Memory evidence capture batches committed revisions in the existing transaction while preserving immutable first-writer histories, per-revision Source ownership and projection encoding. Historical Source reads join material and immutable bindings and batch retained manifests by exact definition version; a damaged ancillary manifest neutralizes only its own identity. Complete related vector recall validates all eligible projections and computes distances in one statement, rejecting invalid projections even outside the distance threshold. SQLite FTS query selection and impossible FTS recovery-probe short-circuiting change read execution only. No table, migration resource, stored encoding, journal order or installed-release upgrade support claim changes. Related hybrid ranks observe lexical results and complete vector validation in one SQL statement; page bodies and current authority remain separately admitted. Each backend prepares and decodes its rank query at one boundary; hybrid ranks retain RRF fusion when no lexical query can be formed. Single and batched active projection publication share current-tag loading under the caller transaction. Historical manifests use the same tolerant batch decoder for one or many identities. These read-execution changes preserve table layouts, stored formats, migrations and upgrade claims. Related hybrid ranks preserve the per-row lexical coverage rule of current related recall, including native full-text query blocks. No migration revision or persisted encoding changes." }, "cases": [], "automatic_sources": { diff --git a/scripts/run_upgrade_release_gate.py b/scripts/run_upgrade_release_gate.py index 6dd7467d66..89379f529b 100644 --- a/scripts/run_upgrade_release_gate.py +++ b/scripts/run_upgrade_release_gate.py @@ -92,6 +92,10 @@ def stage_distributions(dist: Path, staging: Path, *, release: bool) -> tuple[Pa shutil.copyfile(path, copied) staged.append(copied) wheel = staging / wheels[0].name + if release: + from schema_release import check_release_wheel + + check_release_wheel(wheel) if sources: validate_sdist(staging / sources[0].name, wheel, staging.parent) return wheel, staged diff --git a/scripts/schema_release.py b/scripts/schema_release.py new file mode 100644 index 0000000000..3ea94b0bd7 --- /dev/null +++ b/scripts/schema_release.py @@ -0,0 +1,409 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Validate the shared 000 migration and freeze it for a declared release.""" + +from __future__ import annotations + +import argparse +import ast +import hashlib +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +import tokenize +import warnings +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +MIGRATIONS = Path("src/powercontext/builtin/persistence/migrations") +SERVER = MIGRATIONS / "server_resources" +SOURCES = MIGRATIONS / "server_sources" +DRAFT = "000" +GIT = shutil.which("git") or "/usr/bin/git" +RELEASE_ID = re.compile(r"v(0|[1-9][0-9]*)_(0|[1-9][0-9]*)_(0|[1-9][0-9]*)") +DRAFT_TOKEN = re.compile(r"(? None: + manifest = json.loads((bundle.snapshot_directory / "manifest.json").read_text(encoding="utf-8")) + for resource in [*manifest.get("mysql_state_layouts", []), *manifest.get("mysql_layouts", [])]: + layout = json.loads((bundle.snapshot_directory / resource).read_text(encoding="utf-8")) + for entry in layout["revisions"].values(): + statements = entry["statements"] if isinstance(entry, dict) else entry + for statement in statements: + if statement.startswith("@"): + module, separator, operation = statement[1:].partition(":") + if not separator or not operation or module not in bundle.resources or not module.endswith(".py"): + message = f"Invalid conditional MySQL operation: {statement}" + raise ValueError(message) + + +def native_checksums(bundle): + from alembic.script import ScriptDirectory + + from powercontext.builtin.persistence.migrations.models import digest + + manifest = json.loads((bundle.snapshot_directory / "manifest.json").read_text(encoding="utf-8")) + # Native extensions define baseline tables that survive every revision. + # Bind both the registration and its bytes, including source overlays. + extensions = { + name: {"resource": resource, "checksum": bundle.resources[resource]} + for name, resource in manifest.get("mysql_schema_extensions", {}).items() + } + directory = bundle.snapshot_directory / "mysql" + hashes = { + path.relative_to(directory).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() + for path in directory.rglob("*.py") + } + for revision, resource in bundle.mysql_wrappers.items(): + hashes[f"versions/{revision}_registered.py"] = bundle.resources[resource] + # Match the native runner's environment and wrapper inputs, while also + # protecting scripts whose filenames do not follow the revision prefix. + return { + item.revision: digest({ + "env": hashes["env.py"], + "extensions": extensions, + "script": hashlib.sha256(Path(item.path).read_bytes()).hexdigest(), + "wrappers": { + name: value + for name, value in hashes.items() + if name.startswith(f"versions/{item.revision}_") or name == f"versions/{item.revision}.py" + }, + }) + for item in ScriptDirectory(str(directory)).walk_revisions() + } + + +def preserve_history(before, after) -> None: + for source, old in before.items(): + if source not in after: + message = f"Registered source removed: {source}" + raise ValueError(message) + new = after[source] + frozen = tuple(revision for revision in old.revisions if revision != DRAFT) + if new.revisions[: len(frozen)] != frozen: + message = f"Frozen migration history changed: {source}" + raise ValueError(message) + old_native, new_native = native_checksums(old), native_checksums(new) + for revision in frozen: + if ( + new.checksums.get(revision) != old.checksums[revision] + or new_native.get(revision) != old_native[revision] + or new.fingerprints.get(revision) != old.fingerprints[revision] + ): + message = f"Frozen migration resources changed: {source}/{revision}" + raise ValueError(message) + additions = new.revisions[len(frozen) :] + if len(additions) > 1 or any( + revision != DRAFT and not RELEASE_ID.fullmatch(revision) for revision in additions + ): + message = "Append only the shared 000 draft, or its single frozen release revision" + raise ValueError(message) + + +def checkout_resources(root: Path, ref: str, target: Path) -> str: + commit = subprocess.check_output( # noqa: S603 -- git resolves the ref without a shell + [GIT, "rev-parse", "--verify", "--end-of-options", f"{ref}^{{commit}}"], + cwd=root, + text=True, + ).strip() + data = subprocess.check_output( # noqa: S603 -- resolved commit and fixed paths + [GIT, "archive", commit, str(SERVER), str(SOURCES)], + cwd=root, + ) + with tarfile.open(fileobj=io.BytesIO(data)) as archive: + for member in archive.getmembers(): + if not member.isfile(): + continue + path = target / member.name + if not path.resolve().is_relative_to(target.resolve()): + message = "Invalid resource path in Git archive" + raise ValueError(message) + path.parent.mkdir(parents=True, exist_ok=True) + stream = archive.extractfile(member) + if stream is None: + message = "Missing resource in Git archive" + raise ValueError(message) + path.write_bytes(stream.read()) + return commit + + +def check(root: Path, *, base_ref: str | None = None, release: bool = False): + if base_ref is not None and not base_ref.strip(): + message = "--base-ref must not be empty; omit it to run without a baseline comparison" + raise ValueError(message) + current = bundles(root) + if release and any(bundle.head == DRAFT for bundle in current.values()): + message = "Release contains mutable 000; run make schema-freeze VERSION=X.Y.Z" + raise ValueError(message) + if base_ref is not None: + with tempfile.TemporaryDirectory(prefix="pc-schema-base-") as temporary: + base = Path(temporary) + commit = checkout_resources(root, base_ref, base) + previous = bundles(base) + preserve_history(previous, current) + head = current["server"].head + if head != DRAFT and head not in previous["server"].revisions: + policy = json.loads((root / "release/upgrade-support.json").read_text(encoding="utf-8")) + if head != "v" + policy["target_version"].replace(".", "_"): + message = "New frozen revision must match the declared release target" + raise ValueError(message) + print(f"Frozen migration history matches base: {commit}") + return current + + +def rewrite_json(value, names: dict[str, str], revision: str, field: str = ""): + identity_fields = {"revision", "down_revision", "source_revision", "target_revision"} + identity_maps = { + "revision_resources", + "sqlite_fingerprints", + "domain_readiness", + "revisions", + "mysql_wrappers", + "checkpoints", + } + identity_values = {"sqlite_baselines", "retained_revisions"} + if isinstance(value, str): + if value == DRAFT and field in identity_fields | identity_values: + return revision + if field == "statements" and value.startswith("@"): + module, separator, operation = value[1:].partition(":") + if separator: + return f"@{names.get(module, module)}:{operation}" + return names.get(value, value) + if isinstance(value, list): + return [rewrite_json(item, names, revision, field) for item in value] + if isinstance(value, dict): + result = {} + for key, item in value.items(): + new_key = revision if key == DRAFT and field in identity_maps else key + if new_key in result: + message = f"Freezing would duplicate JSON key {new_key}" + raise ValueError(message) + result[new_key] = rewrite_json(item, names, revision, field if field in identity_values else key) + return result + return value + + +def rewrite_python(content: str, names: dict[str, str], revision: str) -> str: + # Only revision assignments and known resource paths are rewritten. A data + # default or SQL literal equal to 000 must remain byte-for-byte unchanged. + identities = set() + lines = content.splitlines() + for node in ast.walk(ast.parse(content)): + if not isinstance(node, (ast.Assign, ast.AnnAssign)): + continue + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + if any(isinstance(target, ast.Name) and target.id in {"revision", "down_revision"} for target in targets): + value = node.value + if isinstance(value, ast.Constant) and value.value == DRAFT: + column = len(lines[value.lineno - 1].encode("utf-8")[: value.col_offset].decode("utf-8")) + identities.add((value.lineno, column)) + tokens = [] + for token in tokenize.generate_tokens(io.StringIO(content).readline): + if token.type == tokenize.STRING: + literal = ast.parse(token.string, mode="eval").body + value = literal.value if isinstance(literal, ast.Constant) else None + if isinstance(value, str): + updated = revision if token.start in identities else names.get(value, value) + if updated != value: + token = token._replace(string=repr(updated)) + tokens.append(token) + return tokenize.untokenize(tokens) + + +def freeze(root: Path, version: str) -> str | None: # noqa: C901 -- validate the full write plan before mutations + if not re.fullmatch(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", version): + message = "Freeze VERSION must be a stable X.Y.Z release" + raise ValueError(message) + revision = "v" + version.replace(".", "_") + if len(revision) > 32: + message = "Revision exceeds the 32-character storage limit" + raise ValueError(message) + policy_path = root / "release/upgrade-support.json" + policy = json.loads(policy_path.read_text(encoding="utf-8")) + contract = (root / "openapi/powercontext.yaml").read_text(encoding="utf-8") + declared = re.search(r"^ version: (.+)$", contract, re.MULTILINE) + if policy["target_version"] != version or declared is None or declared[1] != version: + message = "Run make version-bump first; VERSION must match both release declarations" + raise ValueError(message) + before = bundles(root) + if not any(bundle.head == DRAFT for bundle in before.values()): + return None # No schema change: preserve the existing head and all resources. + if any(revision in bundle.revisions for bundle in before.values()): + message = f"Release revision already exists: {revision}" + raise ValueError(message) + originals = { + path.relative_to(root): path.read_bytes() + for folder in (root / SERVER, root / SOURCES) + for path in folder.rglob("*") + if path.is_file() and path.suffix in {".py", ".json", ".sql"} + } + # Paths are registered relative to either the main bundle or its source overlay. + names = {} + for path in originals: + relative = ( + path.relative_to(SERVER) if path.is_relative_to(SERVER) else Path(*path.relative_to(SOURCES).parts[1:]) + ) + if DRAFT_TOKEN.search(relative.as_posix()): + names[relative.as_posix()] = DRAFT_TOKEN.sub(revision, relative.as_posix()) + # Support Path joins that spell the basename rather than the registered path. + names.update({Path(old).name: Path(new).name for old, new in list(names.items())}) + updates = {} + for path, raw in originals.items(): + destination = Path(DRAFT_TOKEN.sub(revision, path.as_posix())) + if destination != path and destination in originals: + message = f"Freeze destination already exists: {destination}" + raise ValueError(message) + content = raw.decode("utf-8") + if path.suffix == ".json": + value = json.loads(content) + updated = rewrite_json(value, names, revision) + if updated != value: + content = json.dumps(updated, ensure_ascii=False, indent=2) + "\n" + elif path.suffix == ".py": + content = rewrite_python(content, names, revision) + if destination in updates: + message = f"Duplicate freeze destination: {destination}" + raise ValueError(message) + updates[destination] = content.encode("utf-8") + # Validate the complete transformed bundle before touching the checkout. + with tempfile.TemporaryDirectory(prefix="pc-schema-freeze-") as temporary: + staging = Path(temporary) + for path, content in updates.items(): + target = staging / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + after = check(staging, release=True) + preserve_history(before, after) + if any(bundle.head != revision for bundle in after.values()): + message = "Freeze did not update every registered source head" + raise ValueError(message) + try: + for path, content in updates.items(): + if originals.get(path) != content: + (root / path).parent.mkdir(parents=True, exist_ok=True) + (root / path).write_bytes(content) + for path in originals.keys() - updates.keys(): + (root / path).unlink() + from upgrade_release_gate import managed_digest + + policy["schema_review"]["persistence_sha256"] = managed_digest(root) + policy_path.write_text(json.dumps(policy, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + except OSError: + for path in updates.keys() - originals.keys(): + (root / path).unlink(missing_ok=True) + for path, content in originals.items(): + (root / path).write_bytes(content) + raise + return revision + + +def check_release_wheel(wheel: Path) -> None: + """Inspect the actual publication artifact, not only the source checkout.""" + with zipfile.ZipFile(wheel) as archive: + for name in archive.namelist(): + if "/migrations/server_" not in name or "/versions/" not in name or not name.endswith(".py"): + continue + tree = ast.parse(archive.read(name), filename=name) + for node in tree.body: + if not isinstance(node, (ast.Assign, ast.AnnAssign)): + continue + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + if ( + any(isinstance(target, ast.Name) and target.id == "revision" for target in targets) + and isinstance(node.value, ast.Constant) + and node.value.value == DRAFT + ): + message = "Release wheel contains mutable 000; freeze the cumulative migration first" + raise ValueError(message) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("check", "freeze")) + parser.add_argument("--version", default=os.environ.get("VERSION")) + parser.add_argument("--base-ref") + parser.add_argument("--release", action="store_true") + args = parser.parse_args() + try: + if args.action == "freeze": + if not args.version: + message = "VERSION is required" + raise ValueError(message) # noqa: TRY301 -- CLI argument validation + result = freeze(ROOT, args.version) + print(f"Frozen schema: {result}" if result else "No pending schema change; head is unchanged") + else: + current = check(ROOT, base_ref=args.base_ref, release=args.release) + print(f"Server migration head: {current['server'].head}") + except (ValueError, OSError, RuntimeError, Warning, subprocess.CalledProcessError) as error: + print(f"Schema release check failed: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/upgrade_release_gate.py b/scripts/upgrade_release_gate.py index c9d91dd8a5..9fc1781223 100644 --- a/scripts/upgrade_release_gate.py +++ b/scripts/upgrade_release_gate.py @@ -509,6 +509,9 @@ def validate_target(root: Path, wheel: Path, *, release: bool, release_notes: st check_docs(root, policy) actual_version = wheel_version(wheel) if release: + from schema_release import check_release_wheel + + check_release_wheel(wheel) require(actual_version == policy["target_version"], "Wheel version differs from upgrade policy target") return policy diff --git a/src/powercontext/builtin/persistence/migrations/revision_names.py b/src/powercontext/builtin/persistence/migrations/revision_names.py index 6bc8725f21..762c2bc140 100644 --- a/src/powercontext/builtin/persistence/migrations/revision_names.py +++ b/src/powercontext/builtin/persistence/migrations/revision_names.py @@ -36,21 +36,24 @@ class RevisionName(TypedDict): } _NAME = re.compile(r"v(0|[1-9][0-9]*)_(0|[1-9][0-9]*)_(0|[1-9][0-9]*)_([0-9]{3})") -# Each PR introduces at most one logical revision, without a local sequence. +# Keep previously supported PR names readable; new releases freeze 000 as vX_Y_Z. _PR_NAME = re.compile(r"v(0|[1-9][0-9]*)_(0|[1-9][0-9]*)_(0|[1-9][0-9]*)_pr[1-9][0-9]*") +_RELEASE_NAME = re.compile(r"v(0|[1-9][0-9]*)_(0|[1-9][0-9]*)_(0|[1-9][0-9]*)") + def describe_revision(revision: str | None) -> RevisionName | None: """Describe a database state, not the running binary or its original source. - New revisions include the registration target release and PR number. Historical release sequences keep their original meaning. Unknown - legacy/custom IDs remain opaque; their software version is never guessed. + The mutable 000 draft has no software version. Frozen cumulative revisions + describe their release; historical sequence and PR names remain readable. + Unknown legacy/custom IDs remain opaque; their software version is never guessed. """ if revision is None: return None name = _LEGACY_NAMES.get(revision, revision) legacy_match = _NAME.fullmatch(name) - match = _PR_NAME.fullmatch(name) or legacy_match + match = _RELEASE_NAME.fullmatch(name) or _PR_NAME.fullmatch(name) or legacy_match return { "revision": revision, "name": name, diff --git a/src/powercontext/server/dashboard/content.py b/src/powercontext/server/dashboard/content.py index 91d4bb5f48..a9dce2b033 100644 --- a/src/powercontext/server/dashboard/content.py +++ b/src/powercontext/server/dashboard/content.py @@ -278,10 +278,12 @@ async def load_prompts(api: DashboardAPI, request: Request, ctx: dict[str, Any]) configuration = next((item for item in ctx["data"]["prompts"] if item["prompt_key"] == selected_key), None) artifact = None if configuration is None else configuration.get("artifact") raw_revision = request.query_params.get("prompt_revision") - if raw_revision is None and artifact is None: - return + if raw_revision is None: + if artifact is None: + return + raw_revision = str(artifact["revision"]) try: - selected = positive_revision(raw_revision if raw_revision is not None else str(artifact["revision"])) + selected = positive_revision(raw_revision) ctx["prompt_opened"] = await api.artifact_revision(ctx["scope"], "prompt", selected_key, selected) except ReadError as error: # Never substitute current content for an unavailable or invalid historical revision. diff --git a/tests/e2e/test_statistics_flow.py b/tests/e2e/test_statistics_flow.py index e2917ca79f..a71b1b041f 100644 --- a/tests/e2e/test_statistics_flow.py +++ b/tests/e2e/test_statistics_flow.py @@ -28,7 +28,7 @@ from powercontext.builtin.inference import character_token_estimator from powercontext.builtin.persistence.oceanbase import OceanBaseConfig from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.runtime import InferenceConfig +from powercontext.builtin.runtime import InferenceConfig, RuntimeConfig from powercontext.client import PowerContextClient from powercontext.http import ( ApproveCandidateRequest, @@ -74,6 +74,9 @@ def _settings(database_kind: str, database: Path) -> ServerSettings: auth=BearerAuthConfig(token=SecretStr(_AUTH_TOKEN)), access=AccessControlConfig(mode="enforced"), inference=InferenceConfig(generation_model="test"), + # This flow verifies persisted accounting and restart recovery. Allow + # slow CI writes to settle; bounded-loss deadlines have dedicated tests. + runtime=RuntimeConfig(model_usage_write_timeout_seconds=5.0, model_usage_flush_timeout_seconds=10.0), mcp=McpConfig(enabled=False), ) diff --git a/tests/native/test_installation.py b/tests/native/test_installation.py index 5cbd1a4876..2f9a677be1 100644 --- a/tests/native/test_installation.py +++ b/tests/native/test_installation.py @@ -42,7 +42,14 @@ def run( - command: list[str], root: Path, env: dict[str, str], name: str, *, stdin: str = "", success: bool = True + command: list[str], + root: Path, + env: dict[str, str], + name: str, + *, + stdin: str = "", + success: bool = True, + timeout: int = 300, ) -> str: with (root / f"{name}.log").open("w", encoding="utf-8") as log: result = subprocess.run( @@ -53,7 +60,7 @@ def run( text=True, stdout=log, stderr=subprocess.STDOUT, - timeout=300, + timeout=timeout, check=False, ) output = (root / f"{name}.log").read_text(encoding="utf-8", errors="replace") @@ -250,7 +257,9 @@ def test_install_configure_remember_and_reinstall(tmp_path: Path, environment: s UV_PYTHON_INSTALL_MIRROR="https://127.0.0.1:9/unavailable", POWERCONTEXT_UV_INSTALLER_URL="https://127.0.0.1:9/unavailable", ) - run(installer, tmp_path, env, "install") + # Cold bootstrap downloads Python and resolves the full dependency graph; + # a healthy regional mirror can spend nearly five minutes on resolution alone. + run(installer, tmp_path, env, "install", timeout=600) if environment.startswith("bootstrap"): python3 = Path(env["UV_PYTHON_BIN_DIR"]) / ("python3.exe" if sys.platform == "win32" else "python3") run( diff --git a/tests/test_ci_pipeline.py b/tests/test_ci_pipeline.py index f90ab9e10f..76720483a9 100644 --- a/tests/test_ci_pipeline.py +++ b/tests/test_ci_pipeline.py @@ -240,7 +240,7 @@ def test_website_build_uses_the_standard_internal_runner(): def test_all_end_to_end_suites_have_extended_timeout(): timeout = workflow("master.yml")["jobs"]["tests"]["timeout-minutes"] - assert timeout == "${{ matrix.suite == 'e2e' && 55 || 50 }}" + assert timeout == "${{ matrix.suite == 'e2e' && 90 || 75 }}" def test_installation_roles_use_only_two_python_runners(): diff --git a/tests/test_schema_draft.py b/tests/test_schema_draft.py new file mode 100644 index 0000000000..2120a59277 --- /dev/null +++ b/tests/test_schema_draft.py @@ -0,0 +1,36 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Exercise the actual cumulative Server draft on the registered source paths.""" + +import pytest + +from tests.builtin.persistence.test_release140_server_migrations import _source + + +@pytest.mark.parametrize("release", ["1.3.0", "1.4.0"]) +@pytest.mark.parametrize("vectors", [False, True]) +def test_registered_source_replays_complete_cumulative_draft(tmp_path, release, vectors): + _settings, _embedding, runner = _source(tmp_path, release=release, vectors=vectors) + plan = runner.plan(backup_policy="skip") + result = runner.apply( + plan_id=plan.plan_id, + backup_policy="skip", + accepted=True, + maintenance_confirmed=True, + accept_no_backup=True, + ) + assert result.revision == plan.target_revision + assert runner.verify().state == "ready" + assert not runner.apply().changed diff --git a/tests/test_schema_release.py b/tests/test_schema_release.py new file mode 100644 index 0000000000..df4cec5f2e --- /dev/null +++ b/tests/test_schema_release.py @@ -0,0 +1,543 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Cumulative migrations execute unchanged after freezing their release identity.""" + +import json +import shutil +import sqlite3 +import subprocess +import sys +import zipfile +from contextlib import closing +from pathlib import Path + +import pytest +import schema_release as schema +from sqlalchemy import create_engine + +from powercontext.builtin.persistence.migrations import MigrationBundle, MigrationError, SQLiteMigrationRunner +from powercontext.builtin.persistence.migrations.bundle import sqlite_inventory +from powercontext.builtin.persistence.migrations.models import digest +from powercontext.builtin.persistence.migrations.mysql_schema import MySQLSchema, _parse_table +from powercontext.builtin.persistence.migrations.revision_names import describe_revision + + +def write_json(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +def fingerprint(statements): + engine = create_engine("sqlite://") + try: + with engine.begin() as connection: + for statement in statements: + connection.exec_driver_sql(statement) + return digest(sqlite_inventory(connection)) + finally: + engine.dispose() + + +def set_version(root, version): + write_json( + root / "release/upgrade-support.json", + { + "target_version": version, + "schema_review": {"persistence_sha256": "pending", "rationale": "Fixture compatibility review"}, + }, + ) + contract = root / "openapi/powercontext.yaml" + contract.parent.mkdir(exist_ok=True) + contract.write_text(f"info:\n version: {version}\n") + + +@pytest.fixture +def draft(tmp_path): + root = tmp_path / "repo" + bundle = root / schema.SERVER + (bundle / "versions").mkdir(parents=True) + (bundle / "mysql/versions").mkdir(parents=True) + env = Path(__file__).parent / "fixtures/database_migrations/env.py" + shutil.copyfile(env, bundle / "env.py") + shutil.copyfile(env, bundle / "mysql/env.py") + baseline = "CREATE TABLE pc_items (id INTEGER PRIMARY KEY, label TEXT)" + changes = [ + "ALTER TABLE pc_items ADD COLUMN note TEXT DEFAULT '000'", + "ALTER TABLE pc_items ADD COLUMN enabled INTEGER DEFAULT 1", + ] + write_json(bundle / "schemas/sqlite-000.json", {"statements": changes, "description": "累计变更", "default": "000"}) + (bundle / "versions/v1_5_2.py").write_text( + "from alembic import op\nrevision = 'v1_5_2'\ndown_revision = None\n" + f"def upgrade():\n op.get_bind().exec_driver_sql({baseline!r})\n" + ) + (bundle / "versions/000.py").write_text( + "import json\nfrom pathlib import Path\nfrom alembic import op\n" + "revision = '000'\ndown_revision = 'v1_5_2'\nDEFAULT = '000'\n" + "def upgrade():\n data = Path(__file__).parents[1] / 'schemas/sqlite-000.json'\n" + " for statement in json.loads(data.read_text())['statements']:\n" + " op.get_bind().exec_driver_sql(statement)\n" + ) + for revision, previous in [("v1_5_2", None), ("000", "v1_5_2")]: + (bundle / f"mysql/versions/{revision}.py").write_text( + f"revision = {revision!r}\ndown_revision = {previous!r}\ndef upgrade():\n pass\n" + ) + write_json( + bundle / "manifest.json", + { + "revision_resources": {"v1_5_2": [], "000": ["schemas/sqlite-000.json"]}, + "sqlite_baselines": {fingerprint([baseline]): "v1_5_2"}, + "sqlite_fingerprints": {"v1_5_2": [fingerprint([baseline])], "000": [fingerprint([baseline, *changes])]}, + "affected_objects": ["pc_items"], + }, + ) + set_version(root, "1.5.3") + return root, baseline + + +def migrate(root, path, baseline): + with closing(sqlite3.connect(path)) as connection: + connection.execute(baseline) + connection.execute("INSERT INTO pc_items VALUES (1, '保留历史')") + connection.commit() + runner = SQLiteMigrationRunner(path, MigrationBundle(root / schema.SERVER)) + plan = runner.plan() + result = runner.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True) + assert runner.verify().state == "ready" + assert not runner.apply().changed + with closing(sqlite3.connect(path)) as connection: + rows = connection.execute("SELECT * FROM pc_items").fetchall() + return result.revision, rows + + +def test_cumulative_sql_preserves_data_before_and_after_freeze(draft, tmp_path): + root, baseline = draft + before = schema.bundles(root) + assert migrate(root, tmp_path / "draft.db", baseline) == ("000", [(1, "保留历史", "000", 1)]) + sql = (root / schema.SERVER / "schemas/sqlite-000.json").read_bytes() + assert schema.freeze(root, "1.5.3") == "v1_5_3" + after = schema.check(root, release=True) + schema.preserve_history(before, after) + assert (root / schema.SERVER / "schemas/sqlite-v1_5_3.json").read_bytes() == sql + assert not (root / schema.SERVER / "versions/000.py").exists() + assert "DEFAULT = '000'" in (root / schema.SERVER / "versions/v1_5_3.py").read_text() + assert migrate(root, tmp_path / "release.db", baseline) == ("v1_5_3", [(1, "保留历史", "000", 1)]) + released = describe_revision("v1_5_3") + pending = describe_revision("000") + assert released is not None and pending is not None + assert released["software_version"] == "1.5.3" + assert released["sequence"] is None + assert pending["software_version"] is None + assert schema.freeze(root, "1.5.3") is None + + +@pytest.mark.parametrize("declaration", ["revision", "revision: str"]) +def test_release_rejects_mutable_draft_in_source_and_wheel(draft, tmp_path, declaration): + root, _ = draft + with pytest.raises(ValueError, match="mutable 000"): + schema.check(root, release=True) + wheel = tmp_path / "release.whl" + name = "powercontext/builtin/persistence/migrations/server_resources/versions/shared.py" + with zipfile.ZipFile(wheel, "w") as archive: + archive.writestr(name, f"{declaration} = '000'\n") + with pytest.raises(ValueError, match="mutable 000"): + schema.check_release_wheel(wheel) + with zipfile.ZipFile(wheel, "w") as archive: + archive.writestr(name, f"{declaration} = 'v1_5_3'\n") + schema.check_release_wheel(wheel) + + +def test_freeze_rejects_wrong_version_without_writing(draft): + root, _ = draft + path = root / schema.SERVER / "versions/000.py" + original = path.read_bytes() + with pytest.raises(ValueError, match="both release declarations"): + schema.freeze(root, "1.5.4") + assert path.read_bytes() == original + + +def test_historical_revision_cannot_be_rewritten(draft): + root, _ = draft + before = schema.bundles(root) + path = root / schema.SERVER / "versions/v1_5_2.py" + path.write_text(path.read_text() + "# forbidden historical edit\n") + with pytest.raises(ValueError, match="Frozen migration resources changed"): + schema.preserve_history(before, schema.bundles(root)) + + +def test_freeze_cannot_overwrite_an_existing_resource(draft): + root, _ = draft + destination = root / schema.SERVER / "schemas/sqlite-v1_5_3.json" + destination.write_text("{}") + with pytest.raises(ValueError, match="destination already exists"): + schema.freeze(root, "1.5.3") + assert destination.read_text() == "{}" + assert (root / schema.SERVER / "versions/000.py").exists() + + +def test_native_chain_must_match_sqlite(draft): + root, _ = draft + path = root / schema.SERVER / "mysql/versions/000.py" + path.write_text("revision = 'other'\ndown_revision = 'v1_5_2'\n") + with pytest.raises(ValueError, match="chains differ"): + schema.check(root) + + +def test_next_cycle_reuses_000_without_modifying_frozen_release(draft): + root, _ = draft + schema.freeze(root, "1.5.3") + before = schema.bundles(root) + bundle = root / schema.SERVER + previous = (bundle / "versions/v1_5_3.py").read_bytes() + for directory in ["versions", "mysql/versions"]: + (bundle / directory / "000.py").write_text( + "revision = '000'\ndown_revision = 'v1_5_3'\ndef upgrade():\n pass\n" + ) + manifest = json.loads((bundle / "manifest.json").read_text()) + manifest["revision_resources"]["000"] = [] + manifest["sqlite_fingerprints"]["000"] = manifest["sqlite_fingerprints"]["v1_5_3"] + write_json(bundle / "manifest.json", manifest) + set_version(root, "1.5.4") + schema.preserve_history(before, schema.bundles(root)) + assert schema.freeze(root, "1.5.4") == "v1_5_4" + assert (bundle / "versions/v1_5_3.py").read_bytes() == previous + assert schema.check(root, release=True)["server"].head == "v1_5_4" + + +def test_freeze_updates_registered_source_overlay(draft): + root, _ = draft + source = root / schema.SOURCES / "1.5.2" + source.mkdir(parents=True) + shutil.copyfile(root / schema.SERVER / "manifest.json", source / "manifest.json") + write_json(source / "registration.json", {"remove_resources": []}) + assert schema.freeze(root, "1.5.3") == "v1_5_3" + assert {bundle.head for bundle in schema.check(root, release=True).values()} == {"v1_5_3"} + manifest = json.loads((source / "manifest.json").read_text()) + assert manifest["revision_resources"]["v1_5_3"] == ["schemas/sqlite-v1_5_3.json"] + + +def test_native_frozen_script_cannot_be_rewritten(draft): + root, _ = draft + before = schema.bundles(root) + path = root / schema.SERVER / "mysql/versions/v1_5_2.py" + path.write_text(path.read_text() + "# historical native mutation\n") + with pytest.raises(ValueError, match="Frozen migration resources changed"): + schema.preserve_history(before, schema.bundles(root)) + + +@pytest.mark.parametrize("source", ["empty", "1.5.1", "1.5.2"]) +@pytest.mark.parametrize("stale_sql", [True, False], ids=["stale-A-plus-B", "correct-B-only"]) +def test_delayed_pr_replays_released_sql(source, stale_sql, draft, tmp_path): + root, baseline = draft + resources = root / schema.SERVER + # Model A's draft before the 1.5.2 release, and B's copy of that draft. + for path in resources.rglob("*"): + if path.is_file() and path.suffix in {".py", ".json"}: + path.write_text(path.read_text().replace("v1_5_2", "v1_5_1")) + if path.name == "v1_5_2.py": + path.rename(path.with_name("v1_5_1.py")) + manifest_path = resources / "manifest.json" + manifest = json.loads(manifest_path.read_text()) + manifest["readiness_scope"] = "server" + write_json(manifest_path, manifest) + old_draft = (resources / "versions/000.py").read_text() + a_sql = json.loads((resources / "schemas/sqlite-000.json").read_text())["statements"] + set_version(root, "1.5.2") + assert schema.freeze(root, "1.5.2") == "v1_5_2" + released = schema.bundles(root) + database = tmp_path / "delayed-pr.db" + if source == "1.5.2": + migrate(root, database, baseline) + elif source == "1.5.1": + with closing(sqlite3.connect(database)) as connection: + connection.execute(baseline) + connection.execute("INSERT INTO pc_items VALUES (1, '保留历史')") + connection.commit() + + # B merges after the release: its dependency is correct, but it may still + # contain A's already-published non-idempotent ADD COLUMN statements. + b_sql = "ALTER TABLE pc_items ADD COLUMN b_value TEXT" + (resources / "versions/000.py").write_text(old_draft.replace("v1_5_1", "v1_5_2")) + (resources / "mysql/versions/000.py").write_text( + "revision = '000'\ndown_revision = 'v1_5_2'\ndef upgrade():\n pass\n" + ) + write_json(resources / "schemas/sqlite-000.json", {"statements": [*a_sql, b_sql] if stale_sql else [b_sql]}) + manifest = json.loads(manifest_path.read_text()) + manifest["revision_resources"]["000"] = ["schemas/sqlite-000.json"] + # The intended final fingerprint is correct in both cases. Structural + # registration alone cannot establish that the SQL reaches this state. + manifest["sqlite_fingerprints"]["000"] = [fingerprint([baseline, *a_sql, b_sql])] + write_json(manifest_path, manifest) + set_version(root, "1.6.0") + schema.preserve_history(released, schema.check(root)) + runner = SQLiteMigrationRunner(database, MigrationBundle(resources)) + + def upgrade(): + plan = runner.plan(backup_policy="skip") + return runner.apply( + plan_id=plan.plan_id, + backup_policy="skip", + accepted=True, + maintenance_confirmed=True, + accept_no_backup=True, + ) + + if stale_sql: + with pytest.raises(MigrationError) as failure: + upgrade() + assert failure.value.code == "invalid_database" + assert "duplicate column name: note" in str(failure.value.__cause__) + print(f"{source}: structure check PASSED; SQL replay FAILED: duplicate column name: note") + with closing(sqlite3.connect(database)) as connection: + columns = [row[1] for row in connection.execute("PRAGMA table_info(pc_items)")] + assert "b_value" not in columns + if source != "empty": + assert connection.execute("SELECT label FROM pc_items").fetchall() == [("保留历史",)] + else: + assert upgrade().revision == "000" + assert runner.verify().state == "ready" + assert not runner.apply().changed + with closing(sqlite3.connect(database)) as connection: + columns = [row[1] for row in connection.execute("PRAGMA table_info(pc_items)")] + assert {"note", "enabled", "b_value"} <= set(columns) + if source != "empty": + assert connection.execute("SELECT label FROM pc_items").fetchall() == [("保留历史",)] + print(f"{source}: structure check PASSED; corrected B-only SQL replay PASSED") + + +def test_freeze_preserves_historical_f_strings(draft): + root, _ = draft + path = root / schema.SERVER / "versions/v1_5_2.py" + content = path.read_text() + '\ndef message(name):\n return f"existing {name}"\n' + path.write_text(content) + assert schema.freeze(root, "1.5.3") == "v1_5_3" + assert path.read_text() == content + + +@pytest.mark.parametrize("source", ["server", "1.4.0"]) +def test_vector_profile_history_cannot_be_rewritten(tmp_path, source): + for directory in (schema.SERVER, schema.SOURCES): + shutil.copytree(schema.ROOT / directory, tmp_path / directory) + before = schema.bundles(tmp_path) + bundle = before[source] + directory = bundle.source_directory or bundle.directory + path = directory / "profiles/vector.json" + profile = json.loads((bundle.snapshot_directory / "profiles/vector.json").read_text()) + profile["source_capture_sha256"]["review_probe"] = "changed provenance" + write_json(path, profile) + with pytest.raises(ValueError, match="Frozen migration resources changed"): + schema.preserve_history(before, schema.bundles(tmp_path)) + + +@pytest.mark.parametrize("source", ["server", "1.4.0"]) +def test_native_environment_history_cannot_be_rewritten(tmp_path, source): + for directory in (schema.SERVER, schema.SOURCES): + shutil.copytree(schema.ROOT / directory, tmp_path / directory) + before = schema.bundles(tmp_path) + bundle = before[source] + directory = bundle.source_directory or bundle.directory + path = directory / "mysql/env.py" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text((bundle.snapshot_directory / "mysql/env.py").read_text() + "\n# changed native environment\n") + with pytest.raises(ValueError, match="Frozen migration resources changed"): + schema.preserve_history(before, schema.bundles(tmp_path)) + + +def test_freeze_preserves_native_checkpoint_layouts(draft): + root, baseline = draft + directory = root / schema.SERVER + change = "CREATE TABLE pc_notes (id INTEGER PRIMARY KEY)" + write_json(directory / "schemas/mysql-baseline.json", {"mysql": [baseline]}) + write_json(directory / "schemas/mysql-checkpoint-000.json", {"mysql": [baseline, change]}) + write_json( + directory / "schemas/mysql-history.json", + { + "format": "powercontext.mysql-layouts.v1", + "revisions": {"v1_5_2": [baseline]}, + "checkpoints": {"v1_5_2": "schemas/mysql-baseline.json"}, + }, + ) + write_json( + directory / "schemas/mysql-000.json", + { + "format": "powercontext.mysql-layouts.v1", + "revisions": {"000": [change]}, + "checkpoints": {"000": "schemas/mysql-checkpoint-000.json"}, + }, + ) + path = directory / "manifest.json" + manifest = json.loads(path.read_text()) + manifest["mysql_layouts"] = ["schemas/mysql-history.json", "schemas/mysql-000.json"] + manifest["revision_resources"]["v1_5_2"] = ["schemas/mysql-history.json", "schemas/mysql-baseline.json"] + manifest["revision_resources"]["000"] += ["schemas/mysql-000.json", "schemas/mysql-checkpoint-000.json"] + write_json(path, manifest) + before = schema.check(root) + expected = MySQLSchema(before["server"]).required("000") + + assert schema.freeze(root, "1.5.3") == "v1_5_3" + + after = schema.check(root, release=True) + native = MySQLSchema(after["server"]) + assert native.required("v1_5_3") == expected + assert native.statements("v1_5_3") == (change,) + schema.preserve_history(before, after) + + +@pytest.mark.parametrize("missing_module", [False, True]) +def test_freeze_preserves_conditional_native_operation(draft, missing_module): + root, baseline = draft + directory = root / schema.SERVER + module = directory / "domain_000.py" + module.write_text( + "def execute(connection, operation, configuration):\n" + ' connection.exec_driver_sql("INSERT INTO pc_items VALUES (7, ?)", (operation,))\n' + ) + table, inventory = _parse_table(baseline) + write_json( + directory / "schemas/mysql-000.json", + { + "format": "powercontext.mysql-state-layouts.v1", + "revisions": { + "v1_5_2": {"statements": [baseline], "changes": [{table: inventory}]}, + "000": {"statements": ["@domain_000.py:000"], "changes": [{}]}, + }, + }, + ) + path = directory / "manifest.json" + manifest = json.loads(path.read_text()) + manifest["mysql_state_layouts"] = ["schemas/mysql-000.json"] + manifest["revision_resources"]["000"].append("schemas/mysql-000.json") + write_json(path, manifest) + if missing_module: + module.unlink() + with pytest.raises(ValueError, match="Invalid conditional MySQL operation"): + schema.freeze(root, "1.5.3") + assert (directory / "versions/000.py").exists() + assert not (directory / "versions/v1_5_3.py").exists() + return + + for revision in ("000", "v1_5_3"): + if revision != "000": + assert schema.freeze(root, "1.5.3") == revision + assert not module.exists() + bundle = schema.check(root)["server"] + native = MySQLSchema(bundle) + layout = json.loads((directory / f"schemas/mysql-{revision}.json").read_text()) + statement = layout["revisions"][revision]["statements"][0] + engine = create_engine("sqlite://") + try: + with engine.begin() as connection: + connection.exec_driver_sql(baseline) + native.execute(connection, statement, {}, revision=revision) + assert connection.exec_driver_sql("SELECT * FROM pc_items").all() == [(7, "@000")] + finally: + engine.dispose() + + +@pytest.mark.parametrize("source", ["server", "1.4.0"]) +@pytest.mark.parametrize("change", ["schema", "remove-registration", "redirect-registration"]) +def test_frozen_code_profile_and_registration_cannot_change(tmp_path, source, change): + for directory in (schema.SERVER, schema.SOURCES): + shutil.copytree(schema.ROOT / directory, tmp_path / directory) + before = schema.bundles(tmp_path) + bundle = before[source] + directory = bundle.source_directory or bundle.directory + manifest = json.loads((bundle.snapshot_directory / "manifest.json").read_text()) + resource = manifest["mysql_schema_extensions"]["seekdb_code"] + original = (bundle.snapshot_directory / resource).read_bytes() + if change == "schema": + profile = json.loads(original) + profile["statements"] = [sql.replace("`payload_bytes`", "`payload_size`") for sql in profile["statements"]] + profile["tables"] = dict(_parse_table(sql) for sql in profile["statements"]) + write_json(directory / resource, profile) + elif change == "remove-registration": + del manifest["mysql_schema_extensions"]["seekdb_code"] + write_json(directory / "manifest.json", manifest) + else: + replacement = "profiles/seekdb-code-replacement.json" + path = directory / replacement + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(original) + manifest["mysql_schema_extensions"]["seekdb_code"] = replacement + write_json(directory / "manifest.json", manifest) + after = schema.bundles(tmp_path) + if change == "schema": + old_schema = MySQLSchema(bundle, embedded_code=True) + new_schema = MySQLSchema(after[source], embedded_code=True) + with pytest.raises(MigrationError, match="incompatible_schema"): + new_schema.verify(old_schema.required(bundle.head), bundle.head) + with pytest.raises(ValueError, match="Frozen migration resources changed"): + schema.preserve_history(before, after) + + +@pytest.mark.parametrize("baseline", ["", " "]) +def test_cli_rejects_explicit_empty_baseline(draft, monkeypatch, capsys, baseline): + root, _ = draft + monkeypatch.setattr(schema, "ROOT", root) + monkeypatch.setattr(sys, "argv", ["schema_release.py", "check", "--base-ref", baseline]) + assert schema.main() == 1 + output = capsys.readouterr() + assert "--base-ref must not be empty" in output.err + assert "Server migration head" not in output.out + + +def test_cli_allows_omitting_baseline(draft, monkeypatch, capsys): + root, _ = draft + monkeypatch.setattr(schema, "ROOT", root) + monkeypatch.setattr(sys, "argv", ["schema_release.py", "check"]) + assert schema.main() == 0 + output = capsys.readouterr() + assert "Server migration head: 000" in output.out + assert "matches base" not in output.out + + +def test_cli_reports_verified_baseline_and_rejects_history_edits(draft, monkeypatch, capsys): + root, _ = draft + # Archive the same registered directory roots as the real repository. + (root / schema.SOURCES).mkdir(parents=True) + (root / schema.SOURCES / ".gitkeep").write_text("") + + def git(*args): + return subprocess.check_output( + [ + schema.GIT, + "-c", + "core.hooksPath=/dev/null", + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + *args, + ], + cwd=root, + text=True, + ).strip() + + git("init", "--quiet") + git("add", ".") + git("commit", "--quiet", "--no-gpg-sign", "-m", "Fixture baseline") + commit = git("rev-parse", "HEAD") + monkeypatch.setattr(schema, "ROOT", root) + monkeypatch.setattr(sys, "argv", ["schema_release.py", "check", "--base-ref", "HEAD"]) + assert schema.main() == 0 + assert f"Frozen migration history matches base: {commit}" in capsys.readouterr().out + path = root / schema.SERVER / "versions/v1_5_2.py" + path.write_text(path.read_text() + "\n# changed frozen history\n") + assert schema.main() == 1 + output = capsys.readouterr() + assert "Frozen migration resources changed" in output.err + assert "matches base" not in output.out + monkeypatch.setattr(sys, "argv", ["schema_release.py", "check", "--base-ref", "refs/heads/missing-baseline"]) + assert schema.main() == 1 + assert "matches base" not in capsys.readouterr().out