diff --git a/docs/en/docs/develop/plugins.md b/docs/en/docs/develop/plugins.md index e0cfd80ce0..6c33404912 100644 --- a/docs/en/docs/develop/plugins.md +++ b/docs/en/docs/develop/plugins.md @@ -162,6 +162,10 @@ Listing, reading revisions and history, governance state, and tags call no plugi `source_refs`. Content identical to the current revision adds no revision, so repeated delivery never writes duplicate revisions. `writer.stable_id(...)` derives a stable ID from its inputs, so the same Source always writes to the same Artifact. +- For an Artifact read outside the transaction with `writer.get` and similar methods, core checks at write time whether + it changed since: if its content was edited, or it was forgotten, restored, or merged, the write conflicts, the batch of + Sources is delivered again later, and the plugin decides again from the new state. The plugin need not compare anything + itself. - Other operations include `tx.set_lifecycle`, `tx.merge`, `tx.revert`, and `tx.set_tags`; read current state with `writer.get`, `writer.list`, and `writer.by_source`. `tx.revert` and `tx.set_lifecycle` return `ArtifactChange`: `result.artifact` is the target snapshot, @@ -248,7 +252,9 @@ class Notes: write. - The response reports the revision this write committed, even if later writes have followed. - Raising `InvalidContent` returns 422 with the message shown to the caller. -- User changes record provenance as the person who made them, as edits of built-in Artifacts do. +- User changes record provenance as the person who made them, as edits of built-in Artifacts do. What is recorded is + the request's `content` as submitted: a method may treat it as a description of one change and write content computed + from it, and the provenance still keeps what the caller submitted. ## Define Source types @@ -363,7 +369,10 @@ plugin = ArtifactPlugin( - `scope.read` / `scope.contribute`: the caller needs that permission on the Scope in the path parameter named by `scope_param`. - In handlers, `ctx.require(action, scope_id)` checks further permissions and makes the API return 403 when the caller - lacks them; `ctx.allowed(...)` only answers true or false. + lacks them; `ctx.allowed(...)` only answers true or false. When an API only accepts a request and `generate` changes + an existing Artifact later, first check the caller's write permission on that Artifact with + `ctx.require("artifact.write", scope_id, artifact_id=...)`: the background write has no caller identity. This check + covers only Artifacts of this plugin's family. - Reading and writing core data: `ctx.reads(scope_id)` reads with the caller's permissions; `ctx.writer(scope_id)` and `ctx.sources.submit(...)` work only for Scopes whose `scope.contribute` was confirmed earlier in the request (by the route's `access` or a prior `ctx.require`). Changing an existing Artifact, including its tags, handles, and lifecycle, @@ -371,7 +380,10 @@ plugin = ArtifactPlugin( - Writes in APIs do not record who did what. When you need that provenance, submit the operation as a Source, as in the example above, and let `generate` write the new revision referencing it. - To create a Scope, call `ctx.scopes.create(title=..., summary=..., idempotency_key=...)`; the caller needs - `server.admin`. + `server.admin`. `ctx.scopes.list()` returns the Scopes this plugin created that the caller can read. + `ctx.scopes.update(scope_id, expected_version=..., title=..., summary=...)` changes a Scope this plugin created and + also needs `server.admin`; the API returns 404 when the Scope does not exist and 403 when another plugin or user + created it. - `request.body` is the validated `request_model` instance, `bytes`, or `None`, according to `body`; `request.path_params`, `request.query`, and `request.caller` are the path parameters, query parameters, and caller. - Return a Pydantic model or a dict for JSON, `BinaryResponse(content=..., content_type=..., filename=...)` for a file, @@ -409,9 +421,16 @@ async def setup(ctx): return Notes(ctx) ``` -- `ctx.storage.engine()` returns an async SQLAlchemy engine for `plugins/.sqlite3` in the data directory. The - plugin owns its tables and migrations; core never reads or backs up this storage. Only SQLite deployments are supported - for now; on Servers using OceanBase or seekdb, accessing `ctx.storage` raises an error. +- `ctx.storage.engine()` returns an async SQLAlchemy engine for this plugin's storage only, on the Server's database + backend and with its connection settings: `plugins/.sqlite3` in the data directory on SQLite deployments, + and a database named `powercontext_plugin_` (with `-` replaced by `_`) on the same tenant or instance on + OceanBase and seekdb deployments. `ctx.storage.backend` names the backend (`sqlite`, `oceanbase`, or `seekdb`) so the + plugin can choose its table definitions and indexes. The plugin owns its tables and migrations; core never reads or + backs up this storage. +- On OceanBase and seekdb, core creates the database when the plugin loads and reuses an existing one. When the Server's + database login cannot create databases, the deployer creates it and grants access beforehand. If the database is + missing and cannot be created, or its name exceeds 64 characters (a plugin name longer than 44), the plugin still + loads, and `ctx.storage.engine()` raises an error that states the reason. - This storage is outside core's transactions. Store large content such as files and vectors under its content digest and reference the digest from Artifacts: retried writes and rolled-back transactions then leave only unreferenced records, never Artifacts pointing at the wrong data. @@ -444,9 +463,14 @@ plugin = ArtifactPlugin(..., pages=PluginPages(directory="ui", entry="index.html - The page appears in the Dashboard's side navigation at `/dashboard/plugins/`. - The page runs in a sandboxed iframe without the user's session; the Dashboard forwards its requests as the current user, - only to routes the plugin declares. + only to routes the plugin declares and to the generic Artifact API of the plugin's family. - `client.request(method, path, options)` accepts `json`, `body` (such as a file's `ArrayBuffer`), `contentType`, and `query`, and returns `status`, `ok`, `json`, `blob`, and `filename`. +- `client.artifacts(method, path, options)` calls the generic Artifact API of this plugin's family, with no route to + declare. `path` follows `/v1/scopes/{scope_id}/artifacts/{family}`: an empty string lists (`GET`) or creates (`POST`), + `/{artifact_id}` reads or edits, `/{artifact_id}/forget` forgets, and so on. `options` also takes `scopeId` (the page's + current Scope by default) and `ifMatch`, and the result also has `etag` and `location`. Permissions, version checks, + and provenance are the same as calling the generic API directly, and the page cannot name another family. - Build the page as a single-page app: after the page navigates, the Dashboard stops forwarding and asks the user to reopen it. Browser dialogs such as `alert` and `confirm` are unavailable in the sandbox. - Pages are static files only (HTML, JavaScript, CSS, images, fonts), up to 5 MiB each; scripts may come only from the @@ -466,6 +490,5 @@ plugin = ArtifactPlugin(..., pages=PluginPages(directory="ui", entry="index.html ## Current limits - Updating a plugin requires a Server restart; hot reload is not available yet. -- Dedicated plugin storage supports only SQLite deployments for now. - Deployers install plugin dependencies into the Server environment by hand. - Plugin code has the Server's permissions; host processes and Workers isolate failures, not untrusted code. diff --git a/docs/zh/docs/develop/plugins.md b/docs/zh/docs/develop/plugins.md index 3bf1fe904a..379dbf9044 100644 --- a/docs/zh/docs/develop/plugins.md +++ b/docs/zh/docs/develop/plugins.md @@ -153,6 +153,8 @@ Server 在一个独立的子进程中导入 `plugin.py` 并检查声明,导入 - 调用模型、解析文件等慢操作放在事务之外,事务里只做写入。 - `tx.put(artifact_id, content=..., source_refs=[...])` 写一个新版本,`source_refs` 记录出处。内容与当前版本相同时不产生新版本, 所以重复交付不会写出重复的版本。`writer.stable_id(...)` 按输入生成稳定的 ID,便于同一条 Source 总是写到同一个 Artifact。 +- 事务外用 `writer.get` 等方法读过的 Artifact,写入时 core 会核对它之后有没有变化:内容被修改过,或者被遗忘、恢复、合并过, + 这次写入都会冲突,整批 Source 稍后再次交付,插件基于新状态重新决定。插件不需要自己比较。 - 还可以用 `tx.set_lifecycle`、`tx.merge`、`tx.revert`、`tx.set_tags` 等方法,以及 `writer.get`、`writer.list`、 `writer.by_source` 读取当前状态。 `tx.revert` 和 `tx.set_lifecycle` 返回 `ArtifactChange`:`result.artifact` 是目标快照, @@ -228,7 +230,8 @@ class Notes: (修改内容时为 412),插件不必自己重复检查。方法只负责校验内容并完成约定的那一次写入。 - 接口返回本次写入提交的版本,即使之后已有其他写入。 - 抛出 `InvalidContent` 时接口返回 422,错误信息展示给调用者。 -- 用户修改会以修改人的身份记录出处,与内置 Artifact 的修改相同。 +- 用户修改会以修改人的身份记录出处,与内置 Artifact 的修改相同。记录的是请求中的 `content` 原文:方法可以把它当作对一次 + 修改的描述,写入另行算出的内容,出处里保留的仍是调用者提交的那一份。 ## 定义 Source 类型 @@ -340,12 +343,17 @@ plugin = ArtifactPlugin( - `authenticated`:只要求已登录; - `scope.read` / `scope.contribute`:要求调用者对 `scope_param` 指定的路径参数中的 Scope 具备该权限。 - 处理函数里用 `ctx.require(action, scope_id)` 检查其他权限,不具备时接口返回 403;`ctx.allowed(...)` 只返回真假。 + 接口只是接受请求、之后由 `generate` 修改已有 Artifact 时,先用 + `ctx.require("artifact.write", scope_id, artifact_id=...)` 检查调用者对这个 Artifact 的写权限:后台写入时没有调用者身份。 + 这项检查只针对本插件 family 的 Artifact。 - 读写核心数据:`ctx.reads(scope_id)` 按调用者权限读取;`ctx.writer(scope_id)` 和 `ctx.sources.submit(...)` 只能用于本次 请求中已经确认 `scope.contribute` 的 Scope(路由声明了该权限,或处理函数先调用了 `ctx.require`)。修改已有 Artifact (包括标签、handle 和生命周期)还需要调用者对该 Artifact 有 `artifact.write` 权限,与通用接口相同;没有权限时接口返回 403。 - 接口中的写入不会自动记录"谁做了什么"。需要这类出处时,像上面的例子一样把操作作为 Source 提交,由 `generate` 写入新版本并 引用它。 - 需要创建 Scope 时用 `ctx.scopes.create(title=..., summary=..., idempotency_key=...)`,要求调用者具备 `server.admin`。 + `ctx.scopes.list()` 返回本插件创建、且调用者可读的 Scope。`ctx.scopes.update(scope_id, expected_version=..., title=..., + summary=...)` 修改本插件创建的 Scope,同样要求 `server.admin`;Scope 不存在时接口返回 404,不是本插件创建的返回 403。 - `request.body` 按 `body` 声明是校验后的 `request_model` 实例、`bytes` 或 `None`;`request.path_params`、`request.query`、 `request.caller` 分别是路径参数、查询参数和调用者。 - 返回值:Pydantic 模型或 dict 返回 JSON;`BinaryResponse(content=..., content_type=..., filename=...)` 返回文件; @@ -379,9 +387,13 @@ async def setup(ctx): return Notes(ctx) ``` -- `ctx.storage.engine()` 返回一个 SQLAlchemy 异步引擎,指向数据目录下的 `plugins/<插件名>.sqlite3`。表结构和迁移由插件自己 - 管理,core 不读取、不备份这块存储。目前只支持 SQLite 部署;使用 OceanBase 或 seekdb 的 Server 上,访问 `ctx.storage` - 会报错。 +- `ctx.storage.engine()` 返回一个 SQLAlchemy 异步引擎,只指向本插件的存储,使用 Server 的数据库后端和连接配置:SQLite + 部署是数据目录下的 `plugins/<插件名>.sqlite3`;OceanBase 和 seekdb 部署是同一个租户或实例上名为 + `powercontext_plugin_<插件名>` 的库(`-` 换成 `_`)。`ctx.storage.backend` 给出后端(`sqlite`、`oceanbase` 或 `seekdb`), + 插件据此选择建表语句和索引。表结构和迁移由插件自己管理,core 不读取、不备份这块存储。 +- OceanBase 和 seekdb 上的库在插件加载时由 core 创建,已存在则直接使用。Server 的数据库登录没有建库权限时,由部署者 + 事先建好并授权。库不存在又无法创建,或者库名超过 64 个字符(插件名超过 44 个字符)时,插件照常加载,调用 + `ctx.storage.engine()` 时报错并说明原因。 - 这块存储不在 core 的事务里。大块内容(文件、向量)建议按内容摘要保存,再在 Artifact 中引用摘要:写入重试或事务回滚只会 留下没人引用的记录,不会让 Artifact 指向错误的数据。 - 存储属于整个插件,不按 Scope 隔离。按 `scope_id` 划分数据,并在读取时确认数据属于本次请求的 Scope。 @@ -411,9 +423,14 @@ plugin = ArtifactPlugin(..., pages=PluginPages(directory="ui", entry="index.html ``` - 页面出现在 Dashboard 左侧导航中,地址是 `/dashboard/plugins/<插件名>`。 -- 页面运行在沙箱 iframe 中,拿不到用户的登录会话;请求由 Dashboard 以当前用户的身份转发,只能调用本插件声明的路由。 +- 页面运行在沙箱 iframe 中,拿不到用户的登录会话;请求由 Dashboard 以当前用户的身份转发,只能调用本插件声明的路由和本插件 + family 的通用 Artifact 接口。 - `client.request(method, path, options)` 的 `options` 可以有 `json`、`body`(例如文件的 `ArrayBuffer`)、`contentType` 和 `query`;返回 `status`、`ok`、`json`、`blob`、`filename`。 +- `client.artifacts(method, path, options)` 调用本插件 family 的通用 Artifact 接口,不需要声明路由。`path` 接在 + `/v1/scopes/{scope_id}/artifacts/{family}` 之后:空字符串是列表(`GET`)或新建(`POST`),`/{artifact_id}` 是读取或编辑, + `/{artifact_id}/forget` 是遗忘,依此类推。`options` 另有 `scopeId`(默认是页面当前的 Scope)和 `ifMatch`;返回值另有 + `etag` 和 `location`。权限、版本校验和出处记录与直接调用通用接口相同,页面不能指定其他 family。 - 页面要做成单页应用:页面跳转后 Dashboard 会停止转发,提示用户重新打开。沙箱中不能使用 `alert`、`confirm` 等浏览器对话框。 - 只提供静态文件(HTML、JavaScript、CSS、图片、字体),单个文件不超过 5 MiB;脚本只能来自插件自己的目录和 `/dashboard/plugins/_client.js`。 @@ -432,6 +449,5 @@ plugin = ArtifactPlugin(..., pages=PluginPages(directory="ui", entry="index.html ## 当前限制 - 插件更新需要重启 Server,还不支持热加载。 -- 插件专属存储目前只支持 SQLite 部署。 - 插件依赖由部署者手动安装到 Server 环境。 - 插件代码与 Server 有相同的权限,宿主进程和 Worker 隔离的是故障,不是不可信代码。 diff --git a/evaluation/memory/prepared_context_budget/reports/budget-v1/report.json b/evaluation/memory/prepared_context_budget/reports/budget-v1/report.json index 2b493e60a2..fd53b0351a 100644 --- a/evaluation/memory/prepared_context_budget/reports/budget-v1/report.json +++ b/evaluation/memory/prepared_context_budget/reports/budget-v1/report.json @@ -1889,7 +1889,7 @@ "sensitivity_of": null, "path": "assembly", "max_bytes": 3000, - "input_sha256": "bc7766a4de352fc6d6a3f704a95c5b1cd9239555f210a4767746d4bfb9b03933", + "input_sha256": "74132e65051a1c2c34aedde5f414789d373136598206ce4234d31aabd88b0e17", "baseline_content_bytes": 2952, "candidate_content_bytes": 3000, "baseline_coverage": 0.5857421563596759, @@ -2047,7 +2047,7 @@ "sensitivity_of": null, "path": "assembly", "max_bytes": 1400, - "input_sha256": "391945926fe015cfee954ef91b0cec6ebd2e50564af31d86f54008fa3af2bbd1", + "input_sha256": "8d00f828905ab0d2e5a2a6a12bc521b8a88e425b3270d759dac83ff52d293038", "baseline_content_bytes": 1399, "candidate_content_bytes": 1400, "baseline_coverage": 0.4944314063466925, @@ -2159,7 +2159,7 @@ "sensitivity_of": null, "path": "assembly", "max_bytes": 640, - "input_sha256": "7960458af30d40aff0c152b08205fd1ed19094e940756936be4a17580048e76d", + "input_sha256": "3c2cf212de65546866d245aad3703f51771a391a84b0de78ee30e69fa01f4d28", "baseline_content_bytes": 640, "candidate_content_bytes": 640, "baseline_coverage": 0.051853254067369715, @@ -2330,7 +2330,7 @@ "sensitivity_of": null, "path": "assembly", "max_bytes": 2400, - "input_sha256": "e996105f32ead0a09138d8182dde67e23252c8dca26a009fc37fb038f953a345", + "input_sha256": "93a5308fa74066923ec1fa76c687ea3e5b9b4b7792131cc4e79a8b9f724f683f", "baseline_content_bytes": 2234, "candidate_content_bytes": 2400, "baseline_coverage": 0.4690000933206748, @@ -2703,7 +2703,7 @@ "sensitivity_of": "assembly-large-early-then-small", "path": "assembly", "max_bytes": 3000, - "input_sha256": "bfb0fc5f1aad7c0558a227dd8cee2319fef9a9100de3c9a5ae95f3108d7a8e3d", + "input_sha256": "119ec1d83cfd36e1c008dd0205d193d0a20beec1c52452ea2fbe68544c58e92a", "baseline_content_bytes": 3000, "candidate_content_bytes": 3000, "baseline_coverage": 0.8389852114932723, diff --git a/evaluation/memory/prepared_context_budget/reports/budget-v1/report.md b/evaluation/memory/prepared_context_budget/reports/budget-v1/report.md index 6404479238..2c34e54acc 100644 --- a/evaluation/memory/prepared_context_budget/reports/budget-v1/report.md +++ b/evaluation/memory/prepared_context_budget/reports/budget-v1/report.md @@ -217,7 +217,7 @@ Inputs SHA-256: `7898b82f155accc150e507ba8eab48a1a1aa34681521dd71e201af5fa0f6bc6 ### `assembly-large-early-then-small` -Inputs SHA-256: `bc7766a4de352fc6d6a3f704a95c5b1cd9239555f210a4767746d4bfb9b03933` +Inputs SHA-256: `74132e65051a1c2c34aedde5f414789d373136598206ce4234d31aabd88b0e17` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | @@ -231,7 +231,7 @@ Inputs SHA-256: `bc7766a4de352fc6d6a3f704a95c5b1cd9239555f210a4767746d4bfb9b0393 ### `assembly-controls-and-line-endings` -Inputs SHA-256: `391945926fe015cfee954ef91b0cec6ebd2e50564af31d86f54008fa3af2bbd1` +Inputs SHA-256: `8d00f828905ab0d2e5a2a6a12bc521b8a88e425b3270d759dac83ff52d293038` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | @@ -242,7 +242,7 @@ Inputs SHA-256: `391945926fe015cfee954ef91b0cec6ebd2e50564af31d86f54008fa3af2bbd ### `assembly-infeasible-640` -Inputs SHA-256: `7960458af30d40aff0c152b08205fd1ed19094e940756936be4a17580048e76d` +Inputs SHA-256: `3c2cf212de65546866d245aad3703f51771a391a84b0de78ee30e69fa01f4d28` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | @@ -257,7 +257,7 @@ Inputs SHA-256: `7960458af30d40aff0c152b08205fd1ed19094e940756936be4a17580048e76 ### `assembly-four-sections` -Inputs SHA-256: `e996105f32ead0a09138d8182dde67e23252c8dca26a009fc37fb038f953a345` +Inputs SHA-256: `93a5308fa74066923ec1fa76c687ea3e5b9b4b7792131cc4e79a8b9f724f683f` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | @@ -289,7 +289,7 @@ Inputs SHA-256: `c07ebcd45331d109c14dea3742a00af25cbcd18da56dc80847ad5fa589ac76c ### `sensitivity-assembly-large-last` -Inputs SHA-256: `bfb0fc5f1aad7c0558a227dd8cee2319fef9a9100de3c9a5ae95f3108d7a8e3d` +Inputs SHA-256: `119ec1d83cfd36e1c008dd0205d193d0a20beec1c52452ea2fbe68544c58e92a` | Pos | Kind | Artifact | Rank | Display | Baseline | Delivered | Retained | Candidate | Delivered | Retained | | ---: | --- | --- | ---: | ---: | --- | ---: | ---: | --- | ---: | ---: | diff --git a/release/upgrade-support.json b/release/upgrade-support.json index 0a3923ad32..db44f46713 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.5.1", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "1bcfbd3930a62ebaaf7f55dc4803464b03bdc18266dd8f0f14532b65872087af", - "rationale": "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 software-version-plus-sequence names directly; 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." + "persistence_sha256": "3570e87e9e2dfb90a2bc780cf65a11b79c660a4a726feb17420a68e7729a3f53", + "rationale": "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 software-version-plus-sequence names directly; 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." }, "cases": [], "automatic_sources": { diff --git a/src/powercontext/builtin/persistence/oceanbase/profile.py b/src/powercontext/builtin/persistence/oceanbase/profile.py index af690d88d2..c1b33d5720 100644 --- a/src/powercontext/builtin/persistence/oceanbase/profile.py +++ b/src/powercontext/builtin/persistence/oceanbase/profile.py @@ -16,7 +16,7 @@ from __future__ import annotations -from collections.abc import AsyncIterator, Sequence +from collections.abc import AsyncIterator, Callable, Sequence from contextlib import asynccontextmanager from dataclasses import dataclass from typing import Annotated, Literal @@ -238,6 +238,17 @@ async def attach( yield profile +def sibling_database_engines(config: OceanBaseConfig, database: str) -> tuple[AsyncEngine, Callable[[], AsyncEngine]]: + """Engines for another database of this tenant and for the tenant itself, with this deployment's settings. + + The second engine creates the database when it is missing; see ``ensure_database``. + """ + + _register_official_dialect() + url = _validate_oceanbase_url(config.url.get_secret_value()) + return _create_engine(config, url.set(database=database)), lambda: _create_engine(config, url.set(database="")) + + def _create_engine(config: OceanBaseConfig, url: URL) -> AsyncEngine: return create_async_engine( url, diff --git a/src/powercontext/builtin/persistence/seekdb/profile.py b/src/powercontext/builtin/persistence/seekdb/profile.py index 9ad17985b0..bb10f36d3d 100644 --- a/src/powercontext/builtin/persistence/seekdb/profile.py +++ b/src/powercontext/builtin/persistence/seekdb/profile.py @@ -17,7 +17,7 @@ from __future__ import annotations import asyncio -from collections.abc import AsyncIterator, Mapping +from collections.abc import AsyncIterator, Callable, Mapping from contextlib import asynccontextmanager, suppress from importlib import import_module from pathlib import Path @@ -291,6 +291,21 @@ def __init__(self, path: Path) -> None: ) +def sibling_database_engines( + config: SeekDBConfig, connection_options: Mapping[str, object], database: str +) -> tuple[AsyncEngine, Callable[[], AsyncEngine]]: + """Engines for another database of an open instance and for the instance itself. + + ``connection_options`` come from the profile that opened the instance. The second engine + creates the database when it is missing; see ``ensure_database``. + """ + + return ( + _create_engine(config, connection_options, database=database), + lambda: _create_engine(config, connection_options, database=""), + ) + + def _create_engine( config: SeekDBConfig, connection_options: Mapping[str, object], diff --git a/src/powercontext/builtin/plugins/executor.py b/src/powercontext/builtin/plugins/executor.py index 87716253f9..ba52f2f8c9 100644 --- a/src/powercontext/builtin/plugins/executor.py +++ b/src/powercontext/builtin/plugins/executor.py @@ -67,6 +67,14 @@ def run_plugin_worker( @asynccontextmanager async def open_plugin_database(config: DatabaseConfig): + async with open_plugin_profile(config) as profile: + yield profile.database + + +@asynccontextmanager +async def open_plugin_profile(config: DatabaseConfig): + """The opened profile; its seekdb connection options also reach the plugin's own database.""" + from powercontext.builtin.persistence.oceanbase.profile import OceanBaseConfig, OceanBaseProfile from powercontext.builtin.persistence.seekdb.profile import SeekDBProfile from powercontext.builtin.persistence.sqlite.profile import SQLiteConfig, SQLiteProfile @@ -79,7 +87,7 @@ async def open_plugin_database(config: DatabaseConfig): else: opened = SeekDBProfile.open(config, tables=()) async with opened as profile: - yield profile.database + yield profile async def execute_plugin( # noqa: C901 - one window from selection through acknowledgment @@ -95,8 +103,11 @@ async def execute_plugin( # noqa: C901 - one window from selection through ackn sources = SourceRepository(BUILTIN_SOURCE_REGISTRY) cursors = SourceCursorRepository() async with AsyncExitStack() as resources: + connection_options = None if database is None: - database = await resources.enter_async_context(open_plugin_database(spec.database)) + profile = await resources.enter_async_context(open_plugin_profile(spec.database)) + database = profile.database + connection_options = getattr(profile, "connection_options", None) from powercontext.builtin.authz.worker import open_worker_security security = await resources.enter_async_context(open_worker_security(spec.security, database)) @@ -176,7 +187,12 @@ async def complete(connection) -> None: from powercontext.builtin.plugins.storage import open_plugin_resources storage, models = await open_plugin_resources( - spec.database, spec.storage_root, manifest.name, spec.inference, plugin_resources + spec.database, + spec.storage_root, + manifest.name, + spec.inference, + plugin_resources, + connection_options=connection_options, ) context = PluginContext( name=manifest.name, diff --git a/src/powercontext/builtin/plugins/host.py b/src/powercontext/builtin/plugins/host.py index 984bcac8ff..caee5189e0 100644 --- a/src/powercontext/builtin/plugins/host.py +++ b/src/powercontext/builtin/plugins/host.py @@ -25,6 +25,7 @@ import contextvars import logging from contextlib import AsyncExitStack +from copy import deepcopy from dataclasses import dataclass from pathlib import Path from typing import Any @@ -37,7 +38,7 @@ from powercontext.builtin.artifacts.merge_models import ArtifactMergeConflictError from powercontext.builtin.persistence.errors import RepositoryNotFoundError from powercontext.builtin.persistence.sources import SourceRepository -from powercontext.builtin.plugins.executor import open_plugin_database +from powercontext.builtin.plugins.executor import open_plugin_profile from powercontext.builtin.plugins.families import register_plugin_family, register_source_binding, revision_metadata from powercontext.builtin.plugins.host_protocol import ( HostCancel, @@ -47,6 +48,7 @@ HostRequest, HostResponse, HostShutdown, + PipeChannel, PluginHostSpec, ) from powercontext.builtin.plugins.manifest import PluginConfigError, PluginManifest, load_plugin @@ -111,8 +113,8 @@ def run_plugin_host(connection: Any, spec: PluginHostSpec) -> None: class _Host: def __init__(self, connection: Any, spec: PluginHostSpec) -> None: self.connection = connection + self.channel: PipeChannel | None = None self.spec = spec - self.send_lock = asyncio.Lock() self.manifest = PluginManifest.model_validate(spec.manifest) self.family = self.manifest.spec.family self.access: Any = None @@ -122,10 +124,11 @@ def __init__(self, connection: Any, spec: PluginHostSpec) -> None: self.definitions: Any = None async def _send(self, message: object) -> None: - async with self.send_lock: - await asyncio.to_thread(self.connection.send, message) + assert self.channel is not None # noqa: S101 - opened before anything is sent + await self.channel.send(message) async def serve(self) -> None: + channel = self.channel = PipeChannel(self.connection, name="powercontext-plugin-host") async with AsyncExitStack() as resources: try: implemented = await self._start(resources) @@ -142,7 +145,7 @@ async def serve(self) -> None: tasks: dict[str, asyncio.Task[None]] = {} while True: try: - message = await asyncio.to_thread(self.connection.recv) + message = await channel.recv() except (EOFError, OSError): break if isinstance(message, HostShutdown): @@ -177,14 +180,20 @@ async def _start(self, resources: AsyncExitStack) -> tuple[str, ...]: register_plugin_family(family) for binding, scopes, source_types in spec.source_bindings: register_source_binding(binding, None if scopes is None else frozenset(scopes), frozenset(source_types)) - self.database = await resources.enter_async_context(open_plugin_database(spec.database)) + profile = await resources.enter_async_context(open_plugin_profile(spec.database)) + self.database = profile.database from powercontext.builtin.authz.worker import build_host_access self.access = build_host_access(spec.security, self.database) if spec.security is not None: self.deployment_id = spec.security.get("deployment_id") storage, models = await open_plugin_resources( - spec.database, spec.storage_root, self.manifest.name, spec.inference, resources + spec.database, + spec.storage_root, + self.manifest.name, + spec.inference, + resources, + connection_options=getattr(profile, "connection_options", None), ) if declaration.definitions: from powercontext.sources.definitions import SourceDefinitionRegistry @@ -352,7 +361,7 @@ async def _change(self, request: HostRequest) -> HostResponse: if operation == "create": target = payload.get("artifact_id") or uuid4().hex await self._authorize(scope_id, "create", None) - change = UserChange("create", target) + change = UserChange("create", target, submitted_content=deepcopy(payload["content"])) plugin_request: BaseModel = CreateRequest( scope_id=scope_id, artifact_id=target, content=payload["content"], caller=caller ) @@ -376,7 +385,12 @@ async def _change(self, request: HostRequest) -> HostResponse: await self._authorize(scope_id, "write", target) if operation == "update": await self._precheck(scope_id, target, payload["expected_revision"], None, "precondition") - change = UserChange("update", target, expected={target: (payload["expected_revision"], None)}) + change = UserChange( + "update", + target, + expected={target: (payload["expected_revision"], None)}, + submitted_content=deepcopy(payload["content"]), + ) plugin_request = UpdateRequest( scope_id=scope_id, artifact_id=target, @@ -478,10 +492,12 @@ def caller(self) -> Caller: principal = _CURRENT.get().request.caller return Caller(principal_id="local" if principal is None else f"{principal.type}:{principal.id}") - async def require(self, action: str, scope_id: str | None) -> None: + async def require(self, action: str, scope_id: str | None, *, artifact_id: str | None = None) -> None: call = _CURRENT.get() - if action in {"scope.read", "scope.contribute"} and scope_id is None: - raise ValueError("Scope permissions need a scope_id") # noqa: TRY003 + if action in {"scope.read", "scope.contribute", "artifact.write"} and scope_id is None: + raise ValueError("Scope and Artifact permissions need a scope_id") # noqa: TRY003 + if (action == "artifact.write") != (artifact_id is not None): + raise ValueError("artifact.write needs an artifact_id, and only artifact.write takes one") # noqa: TRY003 if self.access is None or call.request.caller is None: if action == "scope.contribute" and scope_id is not None: call.contribute_scopes.add(scope_id) @@ -492,7 +508,12 @@ async def require(self, action: str, scope_id: str | None) -> None: resource = ResourceRef.server() if self.deployment_id is None else ResourceRef.server(self.deployment_id) else: assert scope_id is not None # noqa: S101 - checked above for Scope actions - resource = ResourceRef.scope(scope_id) + # An Artifact check always names this plugin's family; a plugin cannot ask about another's. + resource = ( + ResourceRef.scope(scope_id) + if artifact_id is None + else ResourceRef.artifact(scope_id, family=self.family, artifact_id=artifact_id) + ) await self.access.bootstrap_static_scope(call.request.caller, scope_id, context=call.request.audit) try: await self.access.require(call.request.caller, AccessAction(action), resource, context=call.request.audit) @@ -501,6 +522,23 @@ async def require(self, action: str, scope_id: str | None) -> None: if action == "scope.contribute" and scope_id is not None: call.contribute_scopes.add(scope_id) + async def readable(self, scope_ids: tuple[str, ...]) -> set[str]: + """The Scopes among these that the caller may read, checked in one batch.""" + + call = _CURRENT.get() + if self.access is None or call.request.caller is None or not scope_ids: + return set(scope_ids) + from powercontext.builtin.authz import AccessAction, ResourceRef + + for scope_id in scope_ids: + await self.access.bootstrap_static_scope(call.request.caller, scope_id, context=call.request.audit) + decisions = await self.access.check_batch( + call.request.caller, + [(AccessAction.SCOPE_READ, ResourceRef.scope(scope_id)) for scope_id in scope_ids], + context=call.request.audit, + ) + return {scope_id for scope_id, decision in zip(scope_ids, decisions, strict=True) if decision.allowed} + def reads(self, scope_id: str) -> Any: return _CheckedReads(self, scope_id) @@ -622,11 +660,14 @@ async def update(self, scope_id: str, /, *, expected_version: int, title: str, s from powercontext.builtin.scope.models import ScopeMutation host = self._host + await host.require("server.admin", None) application = self._application() - (current,) = await application.list(scope_ids=(scope_id,)) + found = await application.list(scope_ids=(scope_id,)) + if not found: + raise RepositoryNotFoundError("scope", (scope_id,)) + (current,) = found if not self._own(current): raise AccessDenied("the Scope was not created by this plugin") # noqa: TRY003 - await host.require("server.admin", None) updated = await application.update( scope_id, ScopeMutation( @@ -641,17 +682,10 @@ async def update(self, scope_id: str, /, *, expected_version: int, title: str, s return self._scope(updated) async def list(self) -> tuple[PluginScope, ...]: - host = self._host - visible = [] - for descriptor in await self._application().list(): - if self._own(descriptor) and await _allowed(host, descriptor.scope_id): - visible.append(self._scope(descriptor)) - return tuple(visible) - - -async def _allowed(host: _Host, scope_id: str) -> bool: - try: - await host.require("scope.read", scope_id) - except AccessDenied: - return False - return True + from powercontext.builtin.scope.models import ScopeExternalReference + + owned = await self._application().list( + external_reference=ScopeExternalReference(kind=self._KIND, value=self._host.manifest.name) + ) + readable = await self._host.readable(tuple(descriptor.scope_id for descriptor in owned)) + return tuple(self._scope(descriptor) for descriptor in owned if descriptor.scope_id in readable) diff --git a/src/powercontext/builtin/plugins/host_protocol.py b/src/powercontext/builtin/plugins/host_protocol.py index b3363bb919..c8c4c0ac45 100644 --- a/src/powercontext/builtin/plugins/host_protocol.py +++ b/src/powercontext/builtin/plugins/host_protocol.py @@ -12,10 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Picklable messages between the Server and a plugin host process over a duplex Pipe.""" +"""Picklable messages between the Server and a plugin host process over a duplex Pipe, and the channel carrying them.""" from __future__ import annotations +import asyncio +import queue +import threading +from contextlib import suppress from dataclasses import dataclass, field from typing import Any, Literal @@ -110,3 +114,111 @@ class HostCancel: @dataclass(frozen=True) class HostHeartbeat: """Sent every second by a task on the host's event loop, so a blocked loop stops sending it.""" + + +class _Closed: + def __init__(self, error: BaseException | None = None) -> None: + self.error = error + + +_CLOSED = _Closed() +_CLOSE_WAIT_SECONDS = 5.0 + + +class PipeChannel: + """Carry messages over one end of a Pipe on two threads of its own. + + Blocking ``recv`` and ``send`` never borrow the event loop's default executor, which other host + processes and plugin code also use: a full executor must not delay responses or heartbeats. + Messages are sent in the order ``send`` is called. + """ + + def __init__(self, connection: Any, *, name: str) -> None: + self._connection = connection + self._loop = asyncio.get_running_loop() + self._incoming: asyncio.Queue[object] = asyncio.Queue() + self._outgoing: queue.SimpleQueue[tuple[object, asyncio.Future[None]] | None] = queue.SimpleQueue() + self._read_done = asyncio.Event() + self._write_done = asyncio.Event() + self._closed = False + threading.Thread(target=self._read, name=f"{name}-recv", daemon=True).start() + threading.Thread(target=self._write, name=f"{name}-send", daemon=True).start() + + async def recv(self) -> Any: + """The next message; ``EOFError`` once the other end is gone. + + A message that cannot be received, such as one that fails to unpickle, raises its error once; + later calls raise ``EOFError``. + """ + + message = await self._incoming.get() + if isinstance(message, _Closed): + self._incoming.put_nowait(_CLOSED) + if message.error is not None: + raise message.error + raise EOFError # noqa: TRY004 - the end of the stream, not a wrong argument type + return message + + async def send(self, message: object) -> None: + """Send a message; ``OSError`` when the Pipe is closed, or the error that sending raised.""" + + if self._closed: + raise OSError("the channel is closed") # noqa: TRY003 + future = self._loop.create_future() + self._outgoing.put((message, future)) + await future + + async def close(self) -> None: + """Stop sending and close the Pipe once both threads have stopped, so neither uses a closed handle. + + Messages already queued are sent first. If a thread is still running after a few seconds, the Pipe + is left open: its descriptor number cannot be reused while a thread may still write to it. + """ + + self._closed = True + self._outgoing.put(None) + try: + await asyncio.wait_for(asyncio.gather(self._read_done.wait(), self._write_done.wait()), _CLOSE_WAIT_SECONDS) + except TimeoutError: + return + self._connection.close() + + def _read(self) -> None: + try: + while True: + message = self._connection.recv() + self._call(self._incoming.put_nowait, message) + except (EOFError, OSError): + self._call(self._incoming.put_nowait, _CLOSED) + except BaseException as error: + # Ends the stream too, but recv raises it so the owner can report why. + self._call(self._incoming.put_nowait, _Closed(error)) + finally: + self._call(self._read_done.set) + + def _write(self) -> None: + try: + while (item := self._outgoing.get()) is not None: + message, future = item + try: + self._connection.send(message) + except Exception as error: + self._call(_settle, future, error) + else: + self._call(_settle, future, None) + finally: + self._call(self._write_done.set) + + def _call(self, callback: Any, *args: object) -> None: + # RuntimeError: the event loop has closed, so nobody is waiting any more. + with suppress(RuntimeError): + self._loop.call_soon_threadsafe(callback, *args) + + +def _settle(future: asyncio.Future[None], error: Exception | None) -> None: + if future.done(): + return + if error is None: + future.set_result(None) + else: + future.set_exception(error) diff --git a/src/powercontext/builtin/plugins/storage.py b/src/powercontext/builtin/plugins/storage.py index d1efc2f154..e4a8b82d92 100644 --- a/src/powercontext/builtin/plugins/storage.py +++ b/src/powercontext/builtin/plugins/storage.py @@ -17,14 +17,14 @@ from __future__ import annotations import asyncio -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from contextlib import AsyncExitStack from pathlib import Path from typing import Any, Literal, cast from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine -from powercontext.plugins import ChatMessage, ModelUnavailable +from powercontext.plugins import ChatMessage, ModelUnavailable, PluginStorage class SQLitePluginStorage: @@ -47,8 +47,75 @@ async def aclose(self) -> None: await self._engine.dispose() +class SQLPluginStorage: + """A database of the plugin's own on the deployment's OceanBase tenant or seekdb instance.""" + + def __init__( + self, + backend: Literal["oceanbase", "seekdb"], + database: str, + engine: AsyncEngine | None, + error: Exception | None, + ) -> None: + self.backend = backend + self.database = database + self._engine = engine + self._error = error + + def engine(self) -> AsyncEngine: + # A plugin that never uses its storage loads without the database; one that does gets the reason. + if self._engine is None: + raise RuntimeError(f"plugin storage database {self.database!r} is unavailable: {self._error}") # noqa: TRY003 + return self._engine + + async def aclose(self) -> None: + if self._engine is not None: + await self._engine.dispose() + + +def plugin_database_name(name: str) -> str: + return "powercontext_plugin_" + name.replace("-", "_") + + +async def sql_plugin_storage( + database: Any, connection_options: Mapping[str, object] | None, name: str +) -> SQLPluginStorage | None: + """Open the plugin's database with the deployment's own connection settings, creating it when missing.""" + + from powercontext.builtin.persistence.bootstrap import ensure_database, validate_database_name + from powercontext.builtin.persistence.errors import PersistenceError + from powercontext.builtin.persistence.oceanbase import profile as oceanbase + from powercontext.builtin.persistence.seekdb import profile as seekdb + + backend: Literal["oceanbase", "seekdb"] + if isinstance(database, oceanbase.OceanBaseConfig): + backend = "oceanbase" + elif isinstance(database, seekdb.SeekDBConfig) and connection_options is not None: + backend = "seekdb" + else: + return None + target = plugin_database_name(name) + try: + validate_database_name(target) + except ValueError as error: + # Plugin names may be 64 characters; the database name with its prefix may not. + return SQLPluginStorage(backend, target, None, error) + if backend == "oceanbase": + engine, instance_engine = oceanbase.sibling_database_engines(database, target) + else: + assert connection_options is not None # noqa: S101 - checked with the backend above + engine, instance_engine = seekdb.sibling_database_engines(database, connection_options, target) + try: + await ensure_database(engine, instance_engine, name=target) + except PersistenceError as error: + # Typically the login cannot create databases and the deployer has not created this one yet. + await engine.dispose() + return SQLPluginStorage(backend, target, None, error) + return SQLPluginStorage(backend, target, engine, None) + + def plugin_storage(database: Any, root: str | None, name: str) -> SQLitePluginStorage | None: - """Allocate the plugin's area on the deployment backend; other backends are not served yet.""" + """Allocate the plugin's SQLite file; OceanBase and seekdb storage is opened by ``sql_plugin_storage``.""" from powercontext.builtin.persistence.sqlite.profile import SQLiteConfig @@ -142,9 +209,19 @@ async def plugin_models(inference: Any, resources: AsyncExitStack) -> ServerMode async def open_plugin_resources( - database: Any, root: str | None, name: str, inference: Any, resources: AsyncExitStack -) -> tuple[SQLitePluginStorage | None, ServerModels | None]: - storage = plugin_storage(database, root, name) + database: Any, + root: str | None, + name: str, + inference: Any, + resources: AsyncExitStack, + *, + connection_options: Mapping[str, object] | None = None, +) -> tuple[PluginStorage | None, ServerModels | None]: + """``connection_options`` are those of the open core seekdb instance, which the plugin's database shares.""" + + storage: PluginStorage | None = plugin_storage(database, root, name) + if storage is None: + storage = await sql_plugin_storage(database, connection_options, name) if storage is not None: - resources.push_async_callback(storage.aclose) + resources.push_async_callback(cast(Any, storage).aclose) return storage, await plugin_models(inference, resources) diff --git a/src/powercontext/builtin/plugins/writer.py b/src/powercontext/builtin/plugins/writer.py index fac4bbc37e..eb933c9f98 100644 --- a/src/powercontext/builtin/plugins/writer.py +++ b/src/powercontext/builtin/plugins/writer.py @@ -26,7 +26,7 @@ import hashlib from collections.abc import Awaitable, Callable, Collection, Sequence from contextlib import asynccontextmanager -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from datetime import UTC, datetime from functools import partial from typing import Any, Literal, cast @@ -88,6 +88,8 @@ class UserChange: inputs: tuple[str, ...] = () # The caller's (revision, state_version) per Artifact, enforced against the rows the transaction writes. expected: dict[str, tuple[int, int | None]] = field(default_factory=dict) + # The content a create or update request carried, kept as evidence even when the plugin writes other content. + submitted_content: dict[str, JsonValue] | None = None _AGREED = { @@ -316,6 +318,12 @@ async def borrow(): super().__init__(owner, borrow) self._connection = connection + # Authorization inside the transaction reads and audits on its connection; a second connection + # would wait on this transaction's own locks. + context = owner.context + if context is not None and context.access is not None: + context = replace(context, access=context.access.with_connection(connection)) + self._context = context self._writes = 0 self._bytes = 0 self.closed = False @@ -352,10 +360,23 @@ def _admit(self, content: dict[str, JsonValue] | None = None, sources: Sequence[ async def _committed(self, plan, direct_source: SourceRef | None = None): owner = self._owner prepared = await owner.service.prepare_change(plan) - result = await owner.service.commit(self._connection, prepared, owner.context, direct_source=direct_source) - owner.records = tuple(_snapshot(record) for record in result.records) + result = await owner.service.commit(self._connection, prepared, self._context, direct_source=direct_source) + self._record_written(result.records) return result + def _record_written(self, records) -> None: + owner = self._owner + owner.records = tuple(_snapshot(record) for record in records) + self._governed(owner.records) + + def _governed(self, snapshots: Sequence[ArtifactSnapshot]) -> None: + """Later writes in this transaction are decided against the governance state it wrote itself.""" + + observed = self._owner.observed_governance + for snapshot in snapshots: + if snapshot.ref.artifact_id in observed: + observed[snapshot.ref.artifact_id] = snapshot.governance_generation + async def _commit(self, plan) -> ArtifactSnapshot: return self._written(_snapshot((await self._committed(plan)).primary)) @@ -404,7 +425,7 @@ async def _authorize_write(self, ref: ArtifactRef) -> None: """Writes that bypass the governance engine still need the caller's ``artifact.write``.""" owner = self._owner - await owner.service.security.authorize(self._connection, owner.scope_id, owner.context, "write", ref) + await owner.service.security.authorize(self._connection, owner.scope_id, self._context, "write", ref) def _written(self, snapshot: ArtifactSnapshot) -> ArtifactSnapshot: self._owner.written = snapshot @@ -427,6 +448,14 @@ async def put( body = owner.body(content) current = await self._record(self._connection, artifact_id) expected_revision = self._put_revision(artifact_id, current, expected_revision) + observed_governance = owner.observed_governance.get(artifact_id) + if ( + current is not None + and observed_governance is not None + and current.state.governance_generation != observed_governance + ): + # Forget, restore and merge can leave the revision unchanged, so the revision check misses them. + raise owner.service.errors.conflict("the Artifact governance changed after it was read") # noqa: TRY003 if change is not None: if (change.operation == "create") != (current is None): raise owner.service.errors.conflict( @@ -451,10 +480,13 @@ async def put( owner.scope_id, artifact_id, body, - owner.context, + self._context, expected_revision=None if current is None else (current.artifact.revision if expected_revision is None else expected_revision), + # The inspection reads the Artifact again; a governance change committed since the check above + # must fail there too, in the same validation as the revision. + expected_state_version=None if current is None else observed_governance, lineage=ArtifactLineage(sources=tuple(source_refs), artifacts=tuple(artifact_refs)), ) direct = None @@ -464,7 +496,7 @@ async def put( self._connection, owner, artifact_id, - content, + content if change.submitted_content is None else change.submitted_content, "artifact_create" if current is None else "artifact_replace", 1 if current is None else current.artifact.revision + 1, ) @@ -475,7 +507,7 @@ async def revert(self, artifact_id: str, /, *, to_revision: int) -> ArtifactChan self._agree("revert", artifact_id) owner = self._owner plan = await owner.service.inspect_restore( - self._connection, owner.scope_id, artifact_id, owner.context, operation="restore", revision=to_revision + self._connection, owner.scope_id, artifact_id, self._context, operation="restore", revision=to_revision ) return await self._commit_change(plan, artifact_id) @@ -504,7 +536,7 @@ async def set_lifecycle( self._connection, owner.scope_id, artifact_id, - owner.context, + self._context, expected_revision=current.artifact.revision, expected_state_version=current.state.governance_generation, ) @@ -512,7 +544,7 @@ async def set_lifecycle( if requested is ArtifactLifecycleState.ACTIVE: # Shared restoration also undoes the merges that froze an input, as one group. plan = await owner.service.inspect_restore( - self._connection, owner.scope_id, artifact_id, owner.context, operation="restore" + self._connection, owner.scope_id, artifact_id, self._context, operation="restore" ) return await self._commit_change(plan, artifact_id) await self._authorize_write(current.artifact.as_ref()) @@ -525,7 +557,9 @@ async def set_lifecycle( requested, replacement_artifact_id, ) - return ArtifactChange(artifact=_snapshot(await self._require(artifact_id))) + transitioned = _snapshot(await self._require(artifact_id)) + self._governed((transitioned,)) + return ArtifactChange(artifact=transitioned) async def merge( self, @@ -560,7 +594,7 @@ async def merge( into, reads, owner.body(content), - owner.context, + self._context, lineage=lineage, ) return await self._commit(plan) @@ -568,7 +602,7 @@ async def merge( async def _undo_plan(self, artifact_id: str): owner = self._owner return await owner.service.inspect_restore( - self._connection, owner.scope_id, artifact_id, owner.context, operation="undo_merge" + self._connection, owner.scope_id, artifact_id, self._context, operation="undo_merge" ) async def preview_undo_merge(self, artifact_id: str, /) -> UndoMergePreview: @@ -589,8 +623,8 @@ async def undo_merge(self, artifact_id: str, /) -> UndoMergePreview: self._agree("undo_merge", artifact_id) owner = self._owner prepared = await owner.service.prepare_change(await self._undo_plan(artifact_id)) - result = await owner.service.commit(self._connection, prepared, owner.context) - owner.records = tuple(_snapshot(record) for record in result.records) + result = await owner.service.commit(self._connection, prepared, self._context) + self._record_written(result.records) target = next((record for record in result.records if record.ref.artifact_id == artifact_id), None) if target is not None: self._written(_snapshot(target)) @@ -700,6 +734,8 @@ def __init__( self.states = ArtifactGovernanceRepository() self.sources = sources self.observed: dict[str, int] = {} + # The governance state version of each Artifact as first read outside the transaction. + self.observed_governance: dict[str, int] = {} # Restored and retired refs of the last lifecycle write, which user changes report back. self.outcome: tuple[tuple[ArtifactRef, ...], tuple[ArtifactRef, ...], tuple[str, ...]] = ((), (), ()) # The snapshot the agreed write committed, and every record it changed, which user changes return @@ -720,6 +756,7 @@ async def committed_read(): def _seen(self, snapshots: Sequence[ArtifactSnapshot]) -> None: for snapshot in snapshots: self.observed.setdefault(snapshot.ref.artifact_id, snapshot.ref.revision) + self.observed_governance.setdefault(snapshot.ref.artifact_id, snapshot.governance_generation) @property def family(self) -> str: diff --git a/src/powercontext/builtin/scope/application.py b/src/powercontext/builtin/scope/application.py index 4d75cdd518..c21a6d760c 100644 --- a/src/powercontext/builtin/scope/application.py +++ b/src/powercontext/builtin/scope/application.py @@ -44,6 +44,7 @@ ScopeDescriptorPage, ScopeDiscovery, ScopeDraft, + ScopeExternalReference, ScopeMutation, ScopeSelection, ) @@ -138,10 +139,13 @@ async def list( self, *, scope_ids: Sequence[str] | None = None, + external_reference: ScopeExternalReference | None = None, ) -> tuple[ScopeDescriptor, ...]: async with self._database.transaction() as connection: if scope_ids is not None: return await self._repository.get_many(connection, tuple(scope_ids)) + if external_reference is not None: + return await self._repository.with_external_reference(connection, external_reference) return await self._repository.list(connection) async def navigation(self, scope_ids): diff --git a/src/powercontext/builtin/scope/repository.py b/src/powercontext/builtin/scope/repository.py index 99579ee562..53a66e43e4 100644 --- a/src/powercontext/builtin/scope/repository.py +++ b/src/powercontext/builtin/scope/repository.py @@ -118,6 +118,32 @@ async def navigation(self, connection, scope_ids): async def list(self, connection: AsyncConnection, /) -> tuple[ScopeDescriptor, ...]: return await self._load(connection, _scope_projection(select(SCOPES_TABLE).order_by(SCOPES_TABLE.c.scope_id))) + async def with_external_reference( + self, connection: AsyncConnection, reference: ScopeExternalReference, / + ) -> tuple[ScopeDescriptor, ...]: + external = SCOPE_EXTERNAL_REFERENCES_TABLE + matching = ( + select(1) + .where( + external.c.scope_id == SCOPES_TABLE.c.scope_id, + external.c.kind == reference.kind, + external.c.value == reference.value, + ) + .correlate(SCOPES_TABLE) + .exists() + ) + found = await self._load( + connection, _scope_projection(select(SCOPES_TABLE).where(matching).order_by(SCOPES_TABLE.c.scope_id)) + ) + # OceanBase and seekdb compare these columns without regard to case or accents; a reference matches exactly. + return tuple( + descriptor + for descriptor in found + if any( + item.kind == reference.kind and item.value == reference.value for item in descriptor.external_references + ) + ) + async def discover( self, connection: AsyncConnection, diff --git a/src/powercontext/plugins.py b/src/powercontext/plugins.py index c49e9c1ff9..5132398ca3 100644 --- a/src/powercontext/plugins.py +++ b/src/powercontext/plugins.py @@ -432,15 +432,25 @@ def caller(self) -> Caller: return self._request_host().caller() async def require( - self, action: Literal["scope.read", "scope.contribute", "server.admin"], scope_id: str | None = None + self, + action: Literal["scope.read", "scope.contribute", "server.admin", "artifact.write"], + scope_id: str | None = None, + *, + artifact_id: str | None = None, ) -> None: - await self._request_host().require(action, scope_id) + """``artifact.write`` checks one Artifact of this plugin's family and needs ``scope_id`` and ``artifact_id``.""" + + await self._request_host().require(action, scope_id, artifact_id=artifact_id) async def allowed( - self, action: Literal["scope.read", "scope.contribute", "server.admin"], scope_id: str | None = None + self, + action: Literal["scope.read", "scope.contribute", "server.admin", "artifact.write"], + scope_id: str | None = None, + *, + artifact_id: str | None = None, ) -> bool: try: - await self.require(action, scope_id) + await self.require(action, scope_id, artifact_id=artifact_id) except AccessDenied: return False return True diff --git a/src/powercontext/server/dashboard/__init__.py b/src/powercontext/server/dashboard/__init__.py index 393bcd15ff..4211d95584 100644 --- a/src/powercontext/server/dashboard/__init__.py +++ b/src/powercontext/server/dashboard/__init__.py @@ -22,7 +22,13 @@ from starlette.types import Scope from typing_extensions import override -from powercontext.server.dashboard.plugin_pages import plugin_asset, plugin_client, plugin_forward, plugin_page +from powercontext.server.dashboard.plugin_pages import ( + plugin_artifacts, + plugin_asset, + plugin_client, + plugin_forward, + plugin_page, +) from powercontext.server.dashboard.session import save_session @@ -54,6 +60,17 @@ def mount_dashboard(app: FastAPI) -> None: include_in_schema=False, response_model=None, ) + for artifacts_path in ( + "/dashboard/plugins/{name}/artifacts/{scope_id}", + "/dashboard/plugins/{name}/artifacts/{scope_id}/{path:path}", + ): + app.add_api_route( + artifacts_path, + plugin_artifacts, + methods=["GET", "POST", "PUT"], + include_in_schema=False, + response_model=None, + ) app.add_api_route("/dashboard/plugins/{name}", plugin_page, include_in_schema=False, response_model=None) app.include_router(router, prefix="/dashboard", include_in_schema=False) app.add_api_route("/", lambda: RedirectResponse("/dashboard/home"), include_in_schema=False) diff --git a/src/powercontext/server/dashboard/plugin_pages.py b/src/powercontext/server/dashboard/plugin_pages.py index bfbd0a7f4c..eac7ab6d33 100644 --- a/src/powercontext/server/dashboard/plugin_pages.py +++ b/src/powercontext/server/dashboard/plugin_pages.py @@ -18,6 +18,8 @@ its own requests to the Server carry no credentials. The host page forwards the page's request messages to ``/dashboard/plugins/{name}/api/...`` with the session, only for this plugin's declared routes, and stops forwarding once the frame navigates away. +An Artifact plugin's page also reaches the generic Artifact API of its own family +through ``/dashboard/plugins/{name}/artifacts/{scope_id}/...``. """ from __future__ import annotations @@ -42,6 +44,8 @@ ".woff2": "font/woff2", } MAX_ASSET_BYTES = 5 * 1024 * 1024 +# Artifact content is limited to 256 KiB; a merge request also names its inputs. +MAX_ARTIFACT_REQUEST_BYTES = 1024 * 1024 CLIENT_SCRIPT = Path(__file__).parent / "static" / "plugin-client.js" # The frame may open external sites and submit forms; it never gets same-origin access. FRAME_SANDBOX = "allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads" @@ -155,12 +159,18 @@ async def plugin_page(request: Request, name: str) -> HTMLResponse: **entry, "src": f"/dashboard/plugins/{name}/ui/{pages.entry}", "api": f"/dashboard/plugins/{name}/api", + # Only Artifact plugins have a family whose generic API the page may call. + "artifacts": f"/dashboard/plugins/{name}/artifacts" if _family(manifest) else None, "sandbox": FRAME_SANDBOX, "routes": [{"method": route.method, "path": route.path} for route in manifest.spec.api.routes], } return render(request, ctx) +def _family(manifest: Any) -> str | None: + return getattr(manifest.spec, "family", None) + + def _same_origin(request: Request) -> bool: site = request.headers.get("sec-fetch-site") if site is not None: @@ -180,3 +190,55 @@ async def plugin_forward(name: str, path: str, request: Request) -> Response: if _loaded(request, name) is None: return Response(status_code=404) return await call_plugin_api(name, path, request) + + +async def plugin_artifacts(name: str, scope_id: str, request: Request, path: str = "") -> Response: + """Call the generic Artifact API of this plugin's family as the Dashboard session's principal. + + The page chooses the Scope and the path below the family; the family always comes from the + plugin's declaration. Authorization, version preconditions and evidence stay with the public + API, which this re-enters with the session's credentials. + """ + + import json + + from powercontext.server.dashboard.api import DashboardAPI, segment + + if not _same_origin(request) or request.headers.get("origin") == "null": + return Response(status_code=403) + loaded = _loaded(request, name) + family = None if loaded is None else _family(loaded[1]) + parts = path.split("/") if path else [] + if family is None or any(part in {"", ".", ".."} for part in parts): + return Response(status_code=404) + body = bytearray() + async for block in request.stream(): + body.extend(block) + if len(body) > MAX_ARTIFACT_REQUEST_BYTES: + return Response(status_code=413) + content = bytes(body) + target = f"/v1/scopes/{segment(scope_id)}/artifacts" + if parts or request.method != "POST": + target = "/".join((target, segment(family), *(segment(part) for part in parts))) + else: + # Creation names its family in the body; the page cannot create another family's Artifact. + try: + payload = json.loads(content) + except ValueError: + payload = None + if not isinstance(payload, dict): + return Response(status_code=422) + content = json.dumps({**payload, "family": family}).encode() + headers = {"Content-Type": "application/json"} if content else {} + if "if-match" in request.headers: + headers["If-Match"] = request.headers["if-match"] + api = DashboardAPI(request) + try: + # Every query pair is forwarded: a repeated key, such as several tags, is a list to the public API. + response = await api.client.request( + request.method, target, params=tuple(request.query_params.multi_items()), content=content, headers=headers + ) + finally: + await api.client.aclose() + kept = {key: value for key, value in response.headers.items() if key in {"content-type", "etag", "location"}} + return Response(response.content, status_code=response.status_code, headers=kept) diff --git a/src/powercontext/server/dashboard/static/plugin-client.js b/src/powercontext/server/dashboard/static/plugin-client.js index 4c9a37bf2d..5e21f35319 100644 --- a/src/powercontext/server/dashboard/static/plugin-client.js +++ b/src/powercontext/server/dashboard/static/plugin-client.js @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ -// The client a plugin page uses to call its plugin's routes. The page runs in a sandboxed -// frame without the Dashboard session; the Dashboard host page forwards each request. +// The client a plugin page uses to call its plugin's routes and the generic Artifact API of +// its plugin's family. The page runs in a sandboxed frame without the Dashboard session; the +// Dashboard host page forwards each request. (function () { "use strict"; let nextId = 0; @@ -37,12 +38,21 @@ limitations under the License. window.parent.postMessage({ type: "powercontext.ready" }, "*"); function request(method, path, options = {}) { + return send({ method, path }, options); + } + + // `path` follows /v1/scopes/{scopeId}/artifacts/{family}: "" lists or creates, "/{artifactId}" reads or + // edits, "/{artifactId}/forget" forgets, and so on. `scopeId` defaults to the page's current Scope. + function artifacts(method, path, options = {}) { + return send({ target: "artifacts", method, path, scopeId: options.scopeId, ifMatch: options.ifMatch }, options); + } + + function send(target, options) { const id = ++nextId; const message = { type: "powercontext.request", id, - method, - path, + ...target, query: options.query || {}, json: options.json, body: options.body, @@ -59,6 +69,8 @@ limitations under the License. ok: reply.status >= 200 && reply.status < 300, contentType: reply.contentType || "", filename: reply.filename || null, + etag: reply.etag || null, + location: reply.location || null, json: reply.json, blob: reply.blob, }); @@ -68,6 +80,6 @@ limitations under the License. } window.powercontextPluginClient = function () { - return { context: () => context, request }; + return { context: () => context, request, artifacts }; }; })(); diff --git a/src/powercontext/server/dashboard/templates/plugin.html b/src/powercontext/server/dashboard/templates/plugin.html index b4fd919470..66b53dc648 100644 --- a/src/powercontext/server/dashboard/templates/plugin.html +++ b/src/powercontext/server/dashboard/templates/plugin.html @@ -47,7 +47,10 @@ method: route.method, pattern: new RegExp('^' + escape(route.path).replace(/\{[A-Za-z_][A-Za-z0-9_]*\}/g, '[^/]+') + '$'), })); - const safePath = path => /^\/[A-Za-z0-9._~%!$&'()*+,;=:@\/-]*$/.test(path) && !/(^|\/)\.\.?(\/|$)/.test(path); + // Dot segments are refused in their percent-encoded forms too: the URL parser resolves both. + const safePath = path => /^\/[A-Za-z0-9._~%!$&'()*+,;=:@\/-]*$/.test(path) && !/(^|\/)(\.|%2e){1,2}(\/|$)/i.test(path); + // The resolved destination must still lie under the endpoint it was built from. + const within = (url, base) => url.origin === location.origin && (url.pathname === base || url.pathname.startsWith(base + '/')); const declared = (method, path) => safePath(path) && routes.some(route => route.method === method && route.pattern.test(path)); // The first load is the plugin page. Any later load may be another site, so forwarding stops. let loads = 0; @@ -74,12 +77,28 @@ const reply = fields => send({ type: 'powercontext.response', id: data.id, ...fields }); const method = String(data.method || 'GET').toUpperCase(); const path = String(data.path || ''); - if (!declared(method, path)) { reply({ status: 404, error: 'route_not_declared' }); return; } - const url = new URL(config.api + path, location.origin); + // A page reaches its plugin's declared routes, or the generic Artifact API of the plugin's own family. + const artifacts = data.target === 'artifacts'; + let url; + if (artifacts) { + const scopeId = String(data.scopeId || pageContext.scopeId || ''); + if (!config.artifacts || !scopeId || !['GET', 'POST', 'PUT'].includes(method) || (path && !safePath(path))) { + reply({ status: 404, error: 'route_not_declared' }); + return; + } + const base = config.artifacts + '/' + encodeURIComponent(scopeId); + url = new URL(base + path, location.origin); + if (!within(url, base)) { reply({ status: 404, error: 'route_not_declared' }); return; } + } else { + if (!declared(method, path)) { reply({ status: 404, error: 'route_not_declared' }); return; } + url = new URL(config.api + path, location.origin); + if (!within(url, config.api)) { reply({ status: 404, error: 'route_not_declared' }); return; } + } for (const [key, value] of Object.entries(data.query || {})) { for (const item of [].concat(value)) url.searchParams.append(key, String(item)); } const init = { method, credentials: 'same-origin', headers: {} }; + if (artifacts && data.ifMatch !== undefined) init.headers['If-Match'] = String(data.ifMatch); if (data.json !== undefined) { init.body = JSON.stringify(data.json); init.headers['Content-Type'] = 'application/json'; @@ -92,6 +111,10 @@ const contentType = response.headers.get('content-type') || ''; const disposition = response.headers.get('content-disposition') || ''; const result = { status: response.status, contentType, filename: (/filename="([^"]+)"/.exec(disposition) || [])[1] }; + if (artifacts) { + result.etag = response.headers.get('etag'); + result.location = response.headers.get('location'); + } if (response.status !== 204) { if (contentType.includes('application/json')) result.json = await response.json(); else result.blob = await response.blob(); diff --git a/src/powercontext/server/plugin_hosts.py b/src/powercontext/server/plugin_hosts.py index 5b256f9a7a..f21210afcf 100644 --- a/src/powercontext/server/plugin_hosts.py +++ b/src/powercontext/server/plugin_hosts.py @@ -43,6 +43,7 @@ HostRequest, HostResponse, HostShutdown, + PipeChannel, PluginHostSpec, ) @@ -90,7 +91,7 @@ class _HostProcess: def __init__(self, group: PluginHost) -> None: self.group = group self.process: Any = None - self.connection: Any = None + self.channel: PipeChannel | None = None self.ready = False # False once the process is being stopped; it takes no new calls. self.accepting = True @@ -100,7 +101,6 @@ def __init__(self, group: PluginHost) -> None: self.last_beat = self.started_at self.idle_since = self.started_at self.reason = "crash" - self._send_lock = asyncio.Lock() self._exited = asyncio.Event() async def run(self) -> None: @@ -110,13 +110,13 @@ async def run(self) -> None: self.process = context.Process( target=run_plugin_host, args=(child, group.spec), name=f"powercontext-plugin-host-{group.name}" ) - self.connection = parent try: await asyncio.to_thread(self.process.start) child.close() + channel = self.channel = PipeChannel(parent, name=f"powercontext-plugin-host-{group.name}") log_safely(logger, logging.INFO, f"Plugin host {group.name} started") while True: - message = await asyncio.to_thread(parent.recv) + message = await channel.recv() self.last_beat = time.monotonic() if isinstance(message, HostHeartbeat): continue @@ -139,9 +139,9 @@ async def run(self) -> None: except Exception as error: log_safely(logger, logging.WARNING, f"Plugin host {group.name} failed ({type(error).__name__})") finally: - await asyncio.shield(self._cleanup()) + await asyncio.shield(self._cleanup(parent)) - async def _cleanup(self) -> None: + async def _cleanup(self, connection: Any) -> None: self.accepting = self.ready = False for future in self.pending.values(): if not future.done(): @@ -149,15 +149,17 @@ async def _cleanup(self) -> None: self.pending.clear() if self.process is not None and self.process.pid is not None: await asyncio.to_thread(_stop_process, self.process) - self.connection.close() + if self.channel is None: + connection.close() + else: + await self.channel.close() self._exited.set() self.group.exited(self) async def send(self, message: object) -> None: - if self.connection is None: + if self.channel is None: raise OSError("the host process has not started") # noqa: TRY003 - async with self._send_lock: - await asyncio.to_thread(self.connection.send, message) + await self.channel.send(message) async def request(self, request: HostRequest, deadline: float) -> HostResponse: future: asyncio.Future[HostResponse] = asyncio.get_running_loop().create_future() diff --git a/tests/builtin/plugins/test_host_channel.py b/tests/builtin/plugins/test_host_channel.py new file mode 100644 index 0000000000..dc6acfd7f5 --- /dev/null +++ b/tests/builtin/plugins/test_host_channel.py @@ -0,0 +1,81 @@ +# 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. + +"""The Server and host processes exchange messages even while the default executor is full.""" + +import asyncio +import multiprocessing +import pickle +import threading +from concurrent.futures import ThreadPoolExecutor + +import pytest + +from powercontext.builtin.plugins.host_protocol import PipeChannel + + +def test_channel_carries_messages_in_order_while_the_default_executor_is_full(): + async def scenario(): + loop = asyncio.get_running_loop() + executor = ThreadPoolExecutor(max_workers=1) + loop.set_default_executor(executor) + release = threading.Event() + occupied = loop.run_in_executor(None, release.wait) + left, right = multiprocessing.Pipe(duplex=True) + server, host = PipeChannel(left, name="server"), PipeChannel(right, name="host") + try: + async with asyncio.timeout(5): + await asyncio.gather(*(server.send(index) for index in range(20))) + assert [await host.recv() for _ in range(20)] == list(range(20)) + await host.send("reply") + assert await server.recv() == "reply" + finally: + release.set() + await occupied + executor.shutdown() + + asyncio.run(scenario()) + + +def test_channel_reports_the_other_end_going_away_and_refuses_sends_once_closed(): + async def scenario(): + left, right = multiprocessing.Pipe(duplex=True) + channel = PipeChannel(left, name="server") + right.close() + async with asyncio.timeout(5): + with pytest.raises(EOFError): + await channel.recv() + with pytest.raises(EOFError): + await channel.recv() + await channel.close() + with pytest.raises(OSError, match="closed"): + await channel.send("late") + + asyncio.run(scenario()) + + +def test_channel_raises_a_message_that_cannot_be_received_then_reports_the_end(): + async def scenario(): + left, right = multiprocessing.Pipe(duplex=True) + channel = PipeChannel(left, name="server") + right.send_bytes(b"not a pickle") + async with asyncio.timeout(5): + with pytest.raises(pickle.UnpicklingError): + await channel.recv() + with pytest.raises(EOFError): + await channel.recv() + right.close() + await channel.close() + + asyncio.run(scenario()) diff --git a/tests/builtin/plugins/test_plugin_writer.py b/tests/builtin/plugins/test_plugin_writer.py index 4f010338bd..152af7acd2 100644 --- a/tests/builtin/plugins/test_plugin_writer.py +++ b/tests/builtin/plugins/test_plugin_writer.py @@ -16,6 +16,7 @@ import asyncio import json +import os from uuid import uuid4 import pytest @@ -262,6 +263,58 @@ async def scenario(): asyncio.run(scenario()) +@pytest.mark.parametrize("forget_after_inspection", [False, True], ids=["before-inspection", "after-inspection"]) +def test_a_forget_committed_during_put_rejects_the_stale_write(short_tmp_path, monkeypatch, forget_after_inspection): + if os.environ.get("POWERCONTEXT_TEST_MIGRATION_SEEKDB") != "1": + pytest.skip("real seekdb acceptance not enabled") + pytest.importorskip("pylibseekdb") + from powercontext.builtin.artifacts.merge_models import ArtifactMergeConflictError + from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile + from powercontext.builtin.persistence.tables import BUILTIN_TABLES + from powercontext.builtin.scope import ScopeApplication + + async def scenario(): + config = SeekDBConfig(path=short_tmp_path / "seekdb") + async with SeekDBProfile.open(config, tables=BUILTIN_TABLES) as profile: + database = profile.database + scope = ( + await ScopeApplication(database).create( + ScopeDraft(title="Concurrent forget", summary="Plugins", idempotency_key="concurrent-forget") + ) + ).scope_id + async with _writer(database, scope).transaction() as tx: + await tx.put("draft", content={"text": "original"}) + + stale = _writer(database, scope) + original = await stale.get("draft") + assert original is not None and original.lifecycle_state == "active" + inspect_change = stale.service.inspect_change + + async def inspect_around_forget(*args, **kwargs): + # Schedule a real second connection's commit after put's preliminary check, + # on either side of inspection. Both windows must reject stale content. + plan = await inspect_change(*args, **kwargs) if forget_after_inspection else None + async with _writer(database, scope).transaction() as other: + await other.set_lifecycle("draft", "deprecated") + if plan is not None: + return plan + return await inspect_change(*args, **kwargs) + + monkeypatch.setattr(stale.service, "inspect_change", inspect_around_forget) + with pytest.raises(ArtifactMergeConflictError): + async with stale.transaction() as tx: + await tx.put("draft", content={"text": "generated from the active draft"}) + + stored = await _writer(database, scope).get("draft") + assert stored is not None + assert stored.lifecycle_state == "deprecated" + assert stored.ref.revision == original.ref.revision == 1 + assert stored.content == original.content + assert stored.governance_generation == original.governance_generation + 1 + + asyncio.run(scenario()) + + def test_user_changes_complete_exactly_their_write_and_always_record_a_revision(runtime): from powercontext.builtin.plugins.writer import PluginContractError, UserChange @@ -295,6 +348,45 @@ async def scenario(): asyncio.run(scenario()) +def test_a_forget_that_lands_between_the_writers_check_and_its_inspection_conflicts(runtime): + from powercontext.builtin.artifacts.merge_models import ArtifactMergeConflictError + + async def scenario(): + async with open_builtin_contexts(runtime) as contexts: + database = contexts.database + scope = await _scope(contexts) + async with _writer(database, scope).transaction() as tx: + await tx.put("a", content={"text": "first"}) + + stale = _writer(database, scope) + observed = await stale.get("a") + service = stale.service + inspect = service.inspect_change + + async def forget_then_inspect(connection, scope_id, artifact_id, *args, **kwargs): + # Stands in for another connection's forget, committed after put compared the governance + # state and visible to this transaction's next read, as under READ COMMITTED. + plan = await service.inspect_forget( + connection, + scope_id, + artifact_id, + None, + expected_revision=observed.ref.revision, + expected_state_version=observed.governance_generation, + ) + await service.commit(connection, await service.prepare_change(plan), None) + return await inspect(connection, scope_id, artifact_id, *args, **kwargs) + + service.inspect_change = forget_then_inspect + with pytest.raises(ArtifactMergeConflictError): + async with stale.transaction() as tx: + await tx.put("a", content={"text": "derived from the active draft"}) + record = await current(database, "notes", scope, "a") + assert (record.revision, record.content.content) == (1, {"text": "first"}) + + asyncio.run(scenario()) + + def test_lifecycle_changes_report_the_target_and_its_group(runtime): async def scenario(): async with open_builtin_contexts(runtime) as contexts: diff --git a/tests/builtin/test_scope_application.py b/tests/builtin/test_scope_application.py index afb28e4873..a5391cdea4 100644 --- a/tests/builtin/test_scope_application.py +++ b/tests/builtin/test_scope_application.py @@ -15,6 +15,7 @@ from __future__ import annotations import asyncio +import os import re from contextlib import AsyncExitStack @@ -28,6 +29,7 @@ ScopeBindingKey, ScopeBindingNotFoundError, ScopeDraft, + ScopeExternalReference, ScopeIdempotencyConflictError, ScopeMutation, ScopeRelationshipError, @@ -375,3 +377,44 @@ async def scenario() -> None: await scopes.resolve_binding() asyncio.run(scenario()) + + +@pytest.mark.parametrize("backend", ["sqlite", "seekdb"]) +def test_scopes_listed_by_external_reference_match_kind_and_value_exactly(tmp_path, backend: str) -> None: + if backend == "seekdb": + # seekdb compares string columns without regard to case or accents by default. + if os.environ.get("POWERCONTEXT_TEST_MIGRATION_SEEKDB") != "1": + pytest.skip("real seekdb acceptance not enabled") + pytest.importorskip("pylibseekdb") + from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile + + opened = SeekDBProfile.open(SeekDBConfig(path=tmp_path / "seekdb"), tables=BUILTIN_TABLES) + else: + opened = SQLiteProfile.open(SQLiteConfig(), tables=BUILTIN_TABLES) + + async def scenario() -> None: + async with opened as profile: + scopes = ScopeApplication(profile.database) + + def draft(key: str, *references: tuple[str, str]) -> ScopeDraft: + return ScopeDraft( + title=key, + summary="Referenced", + idempotency_key=key, + external_references=tuple( + ScopeExternalReference(kind=kind, value=value) for kind, value in references + ), + ) + + owned = await scopes.create(draft("owned", ("plugin", "rooms"), ("ticket", "OPS-1"))) + await scopes.create(draft("prefix", ("plugin", "rooms-archive"))) + await scopes.create(draft("other-case", ("plugin", "ROOMS"))) + await scopes.create(draft("accented", ("plugin", "róoms"))) + await scopes.create(draft("other-kind", ("ticket", "rooms"))) + await scopes.create(draft("plain")) + + reference = ScopeExternalReference(kind="plugin", value="rooms") + assert await scopes.list(external_reference=reference) == (owned,) + assert await scopes.list(external_reference=ScopeExternalReference(kind="plugin", value="none")) == () + + asyncio.run(scenario()) diff --git a/tests/e2e/plugin_server.py b/tests/e2e/plugin_server.py index 7e9b10cc33..7f4e7013f8 100644 --- a/tests/e2e/plugin_server.py +++ b/tests/e2e/plugin_server.py @@ -34,7 +34,11 @@ @asynccontextmanager async def running_server( - directory: Path, plugins: Path | None = None, *, extra_env: Mapping[str, str | None] | None = None + directory: Path, + plugins: Path | None = None, + *, + extra_env: Mapping[str, str | None] | None = None, + startup_seconds: float = 60, ): """Start the Server; an ``extra_env`` value of ``None`` removes that default variable.""" with socket.socket() as sock: @@ -87,7 +91,7 @@ async def running_server( headers={"Authorization": f"Bearer {ADMIN_AUTHORIZATION_VALUE}"}, timeout=20, ) as client: - async with asyncio.timeout(60): + async with asyncio.timeout(startup_seconds): while True: assert process.returncode is None, (directory / "server.log").read_text() try: diff --git a/tests/e2e/test_plugin_access.py b/tests/e2e/test_plugin_access.py index 58a4123395..77e6e9bcbd 100644 --- a/tests/e2e/test_plugin_access.py +++ b/tests/e2e/test_plugin_access.py @@ -51,6 +51,10 @@ async def retire(self, request: ApiRequest): async with writer.transaction() as tx: await tx.set_lifecycle(request.path_params["artifact_id"], "retired") + async def accept(self, request: ApiRequest): + # A route that accepts a replacement for later checks the caller's authority over the Artifact now. + await self.ctx.require("artifact.write", request.scope_id, artifact_id=request.path_params["artifact_id"]) + async def bind(self, request: ApiRequest): writer = self.ctx.writer(request.scope_id) current = await writer.get(request.path_params["artifact_id"]) @@ -75,7 +79,7 @@ def _route(name): plugin = ArtifactPlugin( family="notes", setup=setup, - api=PluginApi(routes=(_route("tag"), _route("retire"), _route("bind"))), + api=PluginApi(routes=(_route("accept"), _route("tag"), _route("retire"), _route("bind"))), ) """ @@ -169,14 +173,14 @@ async def scenario(): # Another contributor cannot change Alice's note through a plugin route either. routes = f"/v1/plugins/notes/api/scopes/{shared}/notes/{note}" - for action in ("tag", "retire", "bind"): + for action in ("accept", "tag", "retire", "bind"): denied = await bob.post(f"{routes}/{action}") assert denied.status_code == 403, (action, denied.text) state = (await alice.get(f"{path}/governance")).json() assert state["lifecycle_state"] == "active" assert (await alice.get(f"{path}/tags")).json()["tags"] == [] - for action in ("tag", "bind", "retire"): + for action in ("accept", "tag", "bind", "retire"): allowed = await alice.post(f"{routes}/{action}") assert allowed.status_code == 204, (action, allowed.text) assert (await alice.get(f"{path}/governance")).json()["lifecycle_state"] == "retired" @@ -208,3 +212,107 @@ async def scenario(): assert response.json()["items"] == [] asyncio.run(scenario()) + + +ROOMS = """ +from pydantic import BaseModel + +from powercontext.plugins import ApiRequest, ArtifactPlugin, PluginApi, Rendering, Route + + +class Room(BaseModel): + title: str + + +class Rename(BaseModel): + title: str + version: int + + +class Rooms: + def __init__(self, ctx): + self.ctx = ctx + + async def render_artifact(self, request): + return Rendering(text="") + + async def create(self, request: ApiRequest): + title = request.body.title + scope = await self.ctx.scopes.create(title=title, summary="A room.", idempotency_key=title) + return scope.model_dump() + + async def list(self, request: ApiRequest): + return {"scope_ids": [scope.scope_id for scope in await self.ctx.scopes.list()]} + + async def rename(self, request: ApiRequest): + scope_id = request.path_params["scope_id"] + scope = await self.ctx.scopes.update( + scope_id, expected_version=request.body.version, title=request.body.title, summary="A room." + ) + return scope.model_dump() + + +async def setup(ctx): + return Rooms(ctx) + + +plugin = ArtifactPlugin( + family="rooms", + setup=setup, + api=PluginApi( + routes=( + Route(method="POST", path="/rooms", handler="create", access="authenticated", body="json", + request_model=Room), + Route(method="GET", path="/rooms", handler="list", access="authenticated"), + Route(method="POST", path="/rooms/{scope_id}/rename", handler="rename", access="authenticated", + body="json", request_model=Rename), + ) + ), +) +""" + + +def test_plugin_scopes_list_only_readable_own_scopes_and_update_checks_admin_first(tmp_path): + plugins = tmp_path / "plugins" + (plugins / "rooms").mkdir(parents=True) + (plugins / "rooms" / "plugin.py").write_text(ROOMS, encoding="utf-8") + identities = _identities(tmp_path) + + async def scenario(): + async with ( + running_server(tmp_path, plugins, extra_env=identities) as admin, + httpx.AsyncClient( + base_url=admin.base_url, headers={"Authorization": "Bearer alice-token"}, timeout=20 + ) as alice, + ): + api = "/v1/plugins/rooms/api/rooms" + created = [] + for title in ("east", "west"): + response = await admin.post(api, json={"title": title}) + assert response.status_code == 200, response.text + created.append(response.json()) + east, west = created + other = await create_scope(admin, "not-a-room") + await _grant(admin, "alice", east["scope_id"], "scope.viewer") + await _grant(admin, "alice", other, "scope.viewer") + + # Only this plugin's Scopes that the caller may read. + listed = await alice.get(api) + assert listed.status_code == 200, listed.text + assert listed.json()["scope_ids"] == [east["scope_id"]] + + # Changing a Scope needs server.admin before anything about the Scope is revealed. + rename = {"title": "renamed", "version": east["version"]} + for scope_id in (east["scope_id"], "missing-scope"): + denied = await alice.post(f"{api}/{scope_id}/rename", json=rename) + assert denied.status_code == 403, denied.text + missing = await admin.post(f"{api}/missing-scope/rename", json=rename) + assert missing.status_code == 404, missing.text + foreign = await admin.post(f"{api}/{other}/rename", json={"title": "renamed", "version": 1}) + assert foreign.status_code == 403, foreign.text + renamed = await admin.post(f"{api}/{east['scope_id']}/rename", json=rename) + assert renamed.status_code == 200, renamed.text + assert renamed.json()["title"] == "renamed" + assert west["scope_id"] not in listed.json()["scope_ids"] + + asyncio.run(scenario()) diff --git a/tests/e2e/test_plugin_change_evidence.py b/tests/e2e/test_plugin_change_evidence.py new file mode 100644 index 0000000000..da666d75ad --- /dev/null +++ b/tests/e2e/test_plugin_change_evidence.py @@ -0,0 +1,140 @@ +# 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. + +"""User changes keep what the caller submitted, and background writes respect a forget that came first.""" + +import asyncio +from pathlib import Path + +from tests.e2e.plugin_server import capture, create_scope, items, running_server, wait_for +from tests.plugin_support import write_plugin + +# One draft per Scope. Regeneration pauses at a gate after reading the draft, so the test can forget it meanwhile. +DRAFTS = """ +import asyncio +from pathlib import Path + +from powercontext.plugins import Rendering + +GATES = Path({gates!r}) + + +class Drafts: + def __init__(self, ctx): + self.ctx = ctx + + async def render_artifact(self, request): + return Rendering(text=request.artifact.content["text"]) + + async def generate(self, request, writer): + draft = writer.stable_id("draft") + current = await writer.get(draft) + if current is not None: + (GATES / "regenerate.waiting").touch() + while not (GATES / "regenerate.open").exists(): + await asyncio.sleep(0.05) + if current.lifecycle_state != "active": + (GATES / "skipped").touch() + async with writer.transaction(): + pass + return + async with writer.transaction() as tx: + for source in request.sources: + await tx.put(draft, content={{"text": source.projection["content"]}}, source_refs=[source.ref]) + + async def update_artifact(self, request, writer): + # The request describes a change; the plugin computes the content and keeps the draft's Sources. + current = await writer.get(request.artifact_id) + text = current.content["text"] + request.content["append"] + async with writer.transaction() as tx: + await tx.put(request.artifact_id, content={{"text": text}}, source_refs=current.lineage.sources) + + async def forget_artifact(self, request, writer): + async with writer.transaction() as tx: + await tx.set_lifecycle(request.artifact_id, "deprecated") + + +async def setup(ctx): + return Drafts(ctx) +""" + + +def _server(tmp_path: Path): + plugins = tmp_path / "plugins" + gates = tmp_path / "gates" + gates.mkdir() + write_plugin(plugins, "drafts", DRAFTS.format(gates=str(gates))) + return plugins, gates + + +async def _draft(client, scope: str) -> str: + await capture(client, scope, "first", "Restart after the backup") + found = await wait_for(lambda: items(client, scope, "drafts"), lambda value: len(value) == 1) + return f"/v1/scopes/{scope}/artifacts/drafts/{found[0]['artifact_id']}" + + +def test_an_edit_that_keeps_its_sources_commits_and_records_the_submitted_content(tmp_path: Path): + plugins, _ = _server(tmp_path) + + async def scenario(): + # The Server enforces access control, so the edit authorizes the kept Sources inside its transaction. + async with running_server(tmp_path, plugins) as client: + scope = await create_scope(client, "plugin-change-evidence") + draft = await _draft(client, scope) + etag = (await client.get(draft)).headers["ETag"] + submitted = {"append": " completes."} + edited = await client.put(draft, json={"content": submitted}, headers={"If-Match": etag}) + assert edited.status_code == 200, edited.text + body = edited.json() + assert (body["revision"], body["content"]) == (2, {"text": "Restart after the backup completes."}) + + assert {ref["source_id"] for ref in body["sources"]} > {"first"} + (evidence,) = (ref for ref in body["sources"] if ref["source_id"] != "first") + stored = await client.get(f"/v1/scopes/{scope}/sources/{evidence['source_type']}/{evidence['source_id']}") + assert stored.status_code == 200, stored.text + # The evidence is the request's content, not the content the plugin computed from it. + assert stored.json()["content"] == submitted, stored.text + + asyncio.run(scenario()) + + +def test_a_background_write_does_not_revise_a_draft_forgotten_after_it_was_read(tmp_path: Path): + plugins, gates = _server(tmp_path) + log = tmp_path / "server.log" + + async def scenario(): + async with running_server(tmp_path, plugins) as client: + scope = await create_scope(client, "plugin-forgotten-draft") + draft = await _draft(client, scope) + + async def reached(name): + await wait_for(lambda: asyncio.sleep(0, (gates / name).exists()), bool, seconds=120, log=log) + + # Regeneration reads the active draft, then the user forgets it before the write. + await capture(client, scope, "second", "Restart at any time") + await reached("regenerate.waiting") + state = (await client.get(f"{draft}/governance")).json() + forgotten = await client.post( + f"{draft}/forget", json={"revision": 1, "state_version": state["state_version"]} + ) + assert forgotten.status_code == 200, forgotten.text + (gates / "regenerate.open").touch() + + # Forgetting left the revision at 1, so only the governance check can reject the stale write. + # The retried invocation reads the forgotten draft and leaves it alone. + await reached("skipped") + state = (await client.get(f"{draft}/governance")).json() + assert (state["lifecycle_state"], state["artifact"]["revision"]) == ("deprecated", 1) + + asyncio.run(scenario()) diff --git a/tests/e2e/test_plugin_hosts.py b/tests/e2e/test_plugin_hosts.py index 20110b51b1..ae61428291 100644 --- a/tests/e2e/test_plugin_hosts.py +++ b/tests/e2e/test_plugin_hosts.py @@ -32,6 +32,11 @@ class Wait(BaseModel): seconds: float +class Gate(BaseModel): + started: str + release: str + + class Slow: async def render_artifact(self, request): return Rendering(text="") @@ -44,23 +49,38 @@ async def wait(self, request: ApiRequest): await asyncio.sleep(request.body.seconds) return {"pid": os.getpid()} + async def gate(self, request: ApiRequest): + # Record which host took the call, then hold it until the test releases every call. + with open(request.body.started, "a") as started: + started.write(f"{os.getpid()} ") + for _ in range(900): + if os.path.exists(request.body.release): + break + await asyncio.sleep(0.1) + return {"pid": os.getpid()} + async def block(self, request: ApiRequest): time.sleep(request.body.seconds) return {"pid": os.getpid()} + async def crowd(self, request: ApiRequest): + # Occupy every thread of the default executor for a while, as CPU work moved off the event loop would. + self.crowd = [asyncio.ensure_future(asyncio.to_thread(time.sleep, request.body.seconds)) for _ in range(64)] + return {"pid": os.getpid()} + async def setup(ctx): return Slow() -def route(path, handler, timeout): +def route(path, handler, timeout, model=Wait): return Route( method="POST", path=path, handler=handler, access="authenticated", body="json", - request_model=Wait, + request_model=model, timeout_seconds=timeout, ) @@ -70,7 +90,15 @@ def route(path, handler, timeout): setup=setup, change_timeout_seconds=1, host_processes=2, - api=PluginApi(routes=(route("/wait", "wait", 3), route("/hold", "wait", 30), route("/block", "block", 1))), + api=PluginApi( + routes=( + route("/wait", "wait", 3), + route("/hold", "wait", 30), + route("/block", "block", 1), + route("/crowd", "crowd", 3), + route("/gate", "gate", 120, Gate), + ) + ), ) """ @@ -121,9 +149,50 @@ async def call(path, seconds): restarted = await wait_for(lambda: call("/wait", 0), lambda response: response.status_code == 200, log=log) assert restarted.json()["pid"] != pid - # Sixteen long calls fill one host's eight slots, so a second host starts; the limit is two. - held = await asyncio.gather(*(call("/hold", 8) for _ in range(16))) - assert all(response.status_code == 200 for response in held), [response.text for response in held] - assert len({response.json()["pid"] for response in held}) == 2 + # Sixteen held calls fill one host's eight slots, so a second host starts; the limit is two. The calls + # stay held until both hosts have taken some, however long the second host takes to start. + started, release = tmp_path / "started.txt", tmp_path / "release" + gate = {"started": str(started), "release": str(release)} + held = [asyncio.create_task(client.post(f"{api}/gate", json=gate, timeout=150)) for _ in range(16)] + + async def hosts(): + return set(started.read_text().split()) if started.exists() else set() + + await wait_for(hosts, lambda value: len(value) == 2, log=log) + release.touch() + responses = await asyncio.gather(*held) + assert all(response.status_code == 200 for response in responses), [item.text for item in responses] + assert len({response.json()["pid"] for response in responses}) == 2 + + asyncio.run(scenario()) + + +def test_plugin_hosts_keep_answering_while_plugin_code_fills_the_default_executor(tmp_path): + plugins = tmp_path / "plugins" + (plugins / "slow").mkdir(parents=True) + (plugins / "slow" / "plugin.py").write_text(PLUGIN, encoding="utf-8") + log = tmp_path / "server.log" + + async def scenario(): + async with running_server(tmp_path, plugins) as client: + api = "/v1/plugins/slow/api" + + async def call(path, seconds): + return await client.post(f"{api}{path}", json={"seconds": seconds}, timeout=60) + + first = await wait_for(lambda: call("/wait", 0), lambda response: response.status_code == 200, log=log) + pid = first.json()["pid"] + crowded = await call("/crowd", 10) + assert crowded.status_code == 200, crowded.text + assert crowded.json()["pid"] == pid + + # Past the heartbeat timeout, the same host still answers within the route's time limit. + loop = asyncio.get_running_loop() + deadline = loop.time() + 8 + while loop.time() < deadline: + response = await call("/wait", 0) + assert response.status_code == 200, response.text + assert response.json()["pid"] == pid + await asyncio.sleep(0.5) asyncio.run(scenario()) diff --git a/tests/e2e/test_plugin_pages.py b/tests/e2e/test_plugin_pages.py index d9d03f5446..c2e25cbae9 100644 --- a/tests/e2e/test_plugin_pages.py +++ b/tests/e2e/test_plugin_pages.py @@ -16,10 +16,14 @@ import asyncio import json +import re +import shutil +import subprocess import httpx +import pytest -from tests.e2e.plugin_server import ADMIN_AUTHORIZATION_VALUE, running_server +from tests.e2e.plugin_server import ADMIN_AUTHORIZATION_VALUE, create_scope, running_server PLUGIN = """ from pydantic import BaseModel @@ -38,6 +42,18 @@ def __init__(self, ctx): async def render_artifact(self, request): return Rendering(text=request.artifact.content.get("text", "")) + async def create_artifact(self, request, writer): + async with writer.transaction() as tx: + await tx.put(request.artifact_id, content=request.content) + + async def update_artifact(self, request, writer): + async with writer.transaction() as tx: + await tx.put(request.artifact_id, content=request.content) + + async def forget_artifact(self, request, writer): + async with writer.transaction() as tx: + await tx.set_lifecycle(request.artifact_id, "deprecated") + async def echo(self, request: ApiRequest): return {"text": request.body.text} @@ -106,6 +122,10 @@ async def scenario(): f"{pages}/api/echo", json={"text": "x"}, headers={"Sec-Fetch-Site": "same-origin"} ) assert forwarded.status_code == 401 + unauthenticated = await anonymous.get( + f"{pages}/artifacts/any-scope", headers={"Sec-Fetch-Site": "same-origin"} + ) + assert unauthenticated.status_code == 401 session = {"powercontext_dashboard_token": ADMIN_AUTHORIZATION_VALUE} async with httpx.AsyncClient(base_url=client.base_url, cookies=session, timeout=20) as browser: @@ -128,9 +148,154 @@ async def scenario(): small = await browser.post(f"{pages}/api/upload", content=b"x" * 3000, headers=same_origin) assert small.json() == {"size": 3000} + # The page also reaches the generic Artifact API, always for its plugin's own family. + scope = await create_scope(client, "plugin-page-artifacts") + notes = f"{pages}/artifacts/{scope}" + created = await browser.post( + notes, json={"family": "experience", "content": {"text": "draft"}}, headers=same_origin + ) + assert created.status_code == 201, created.text + assert created.json()["family"] == "demo-notes" and created.headers["location"] + note = f"{notes}/{created.json()['artifact_id']}" + read = await browser.get(note, headers=same_origin) + assert read.status_code == 200 and read.json()["content"] == {"text": "draft"}, read.text + listed = await browser.get(notes, headers=same_origin) + assert [item["artifact_id"] for item in listed.json()["items"]] == [created.json()["artifact_id"]] + edit = {"content": {"text": "final"}} + edited = await browser.put(note, json=edit, headers={**same_origin, "If-Match": read.headers["etag"]}) + assert edited.status_code == 200 and edited.json()["revision"] == 2, edited.text + stale = await browser.put(note, json=edit, headers={**same_origin, "If-Match": read.headers["etag"]}) + assert stale.status_code == 412, stale.text + state = (await browser.get(f"{note}/governance", headers=same_origin)).json() + forgotten = await browser.post( + f"{note}/forget", json={"revision": 2, "state_version": state["state_version"]}, headers=same_origin + ) + assert forgotten.status_code == 200, forgotten.text + state = (await browser.get(f"{note}/governance", headers=same_origin)).json() + assert state["lifecycle_state"] == "deprecated" + # The same session and origin rules apply, and the path stays below the family. + for headers in ({"Sec-Fetch-Site": "cross-site"}, {"Origin": "null"}, {}): + assert (await browser.get(note, headers=headers)).status_code == 403 + assert (await browser.get(f"{notes}/%2e%2e/experience", headers=same_origin)).status_code == 404 + + # Repeated query parameters reach the public API as sent, so tag filters match as they do there. + tagged = {} + for name, tags in (("both", ["a", "b"]), ("only-a", ["a"]), ("only-b", ["b"])): + made = await browser.post(notes, json={"content": {"text": name}}, headers=same_origin) + assert made.status_code == 201, made.text + tagged[made.json()["artifact_id"]] = name + labels = f"{notes}/{made.json()['artifact_id']}/tags" + etag = (await browser.get(labels, headers=same_origin)).headers["etag"] + labelled = await browser.put(labels, json={"tags": tags}, headers={**same_origin, "If-Match": etag}) + assert labelled.status_code == 200, labelled.text + public = f"/v1/scopes/{scope}/artifacts/demo-notes" + for match, expected in (("all", {"both"}), ("any", {"both", "only-a", "only-b"})): + query = (("tag", "a"), ("tag", "b"), ("tag_match", match)) + forwarded = await browser.get(notes, params=query, headers=same_origin) + assert forwarded.status_code == 200, forwarded.text + assert {tagged[item["artifact_id"]] for item in forwarded.json()["items"]} == expected, match + assert forwarded.json() == (await client.get(public, params=query)).json() + # A repeated single-valued parameter is the public API's to judge, not silently reduced to one value. + repeated = (("limit", "1"), ("limit", "2")) + direct = await client.get(public, params=repeated) + assert ( + await browser.get(notes, params=repeated, headers=same_origin) + ).status_code == direct.status_code + # Plugins call the Server's generation model without seeing its address or credentials. completed = await client.post("/v1/plugins/demo/api/complete") assert completed.status_code == 200, completed.text assert completed.json()["answer"] asyncio.run(scenario()) + + +# Runs the host page's own script against a stub page: delivers the frame's messages and records what it fetches. +HOST_PAGE_HARNESS = """ +const fs = require('node:fs'); +const [script, messages] = [fs.readFileSync(process.argv[2], 'utf8'), JSON.parse(process.argv[3])]; +const replies = [], fetched = []; +const frame = { + contentWindow: { postMessage: message => replies.push(message) }, + isConnected: true, + parentElement: { removeAttribute() {} }, + addEventListener() {}, +}; +let listener; +globalThis.me = selector => + selector === undefined ? { run: body => body({}) } : selector === 'iframe' ? frame : { remove() {}, hidden: true }; +globalThis.document = { documentElement: { getAttribute: () => 'light' } }; +globalThis.location = new URL('http://dashboard.test/dashboard/plugins/demo'); +globalThis.window = { addEventListener: (type, handler) => { listener = handler; }, removeEventListener() {} }; +globalThis.fetch = async (url, init) => { + fetched.push([init.method, String(url)]); + return { status: 204, headers: { get: () => null } }; +}; +new Function(script)(); +(async () => { + for (const data of messages) await listener({ source: frame.contentWindow, data }); + console.log(JSON.stringify({ fetched, replies })); +})(); +""" + + +def test_host_page_forwards_only_destinations_inside_its_plugin(tmp_path): + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is needed to run the host page script") + plugins = tmp_path / "plugins" + (plugins / "demo" / "ui").mkdir(parents=True) + (plugins / "demo" / "plugin.py").write_text(PLUGIN, encoding="utf-8") + (plugins / "demo" / "ui" / "index.html").write_text(PAGE, encoding="utf-8") + + async def host_page() -> str: + environment = {"POWERCONTEXT_SERVER_DASHBOARD_ENABLED": "true"} + async with running_server(tmp_path, plugins, extra_env=environment) as client: + session = {"powercontext_dashboard_token": ADMIN_AUTHORIZATION_VALUE} + async with httpx.AsyncClient(base_url=client.base_url, cookies=session, timeout=20) as browser: + page = await browser.get("/dashboard/plugins/demo", params={"lang": "en"}) + assert page.status_code == 200, page.text + return page.text + + (script,) = re.findall(r"", asyncio.run(host_page()), re.S) + (tmp_path / "host-page.js").write_text(script, encoding="utf-8") + (tmp_path / "harness.js").write_text(HOST_PAGE_HARNESS, encoding="utf-8") + + def request(identity, **fields): + return {"type": "powercontext.request", "id": identity, **fields} + + def artifacts(identity, path, scope="scope-a", method="GET"): + return request(identity, target="artifacts", method=method, path=path, scopeId=scope) + + escapes = ( + # The URL parser resolves encoded dot segments, here into another plugin's forwarding endpoint. + artifacts(10, "/%2e%2e/%2e%2e/%2e%2e/other/artifacts/scope-a"), + artifacts(11, "/%2E%2E/%2e./.%2e/other/api/echo"), + artifacts(12, "/../../other/artifacts/scope-a"), + artifacts(13, "/note", scope=".."), + artifacts(14, "/note", method="DELETE"), + request(15, method="POST", path="/%2e%2e/%2e%2e/other/api/echo"), + request(16, method="POST", path="/undeclared"), + ) + allowed = ( + artifacts(1, ""), + artifacts(2, "/note-1/forget", method="POST"), + request(3, method="POST", path="/echo", json={"text": "x"}), + ) + completed = subprocess.run( + [node, str(tmp_path / "harness.js"), str(tmp_path / "host-page.js"), json.dumps([*escapes, *allowed])], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert completed.returncode == 0, completed.stderr + result = json.loads(completed.stdout) + base = "http://dashboard.test/dashboard/plugins/demo" + assert result["fetched"] == [ + ["GET", f"{base}/artifacts/scope-a"], + ["POST", f"{base}/artifacts/scope-a/note-1/forget"], + ["POST", f"{base}/api/echo"], + ] + refused = {reply["id"]: reply.get("error") for reply in result["replies"] if reply.get("status") == 404} + assert refused == {message["id"]: "route_not_declared" for message in escapes} diff --git a/tests/e2e/test_plugin_storage.py b/tests/e2e/test_plugin_storage.py new file mode 100644 index 0000000000..66558a13e1 --- /dev/null +++ b/tests/e2e/test_plugin_storage.py @@ -0,0 +1,176 @@ +# 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. + +"""A plugin's dedicated storage follows the Server's database backend, in the host process and in Workers.""" + +import asyncio +import json +import os +from uuid import uuid4 + +import pytest +from pydantic import SecretStr +from sqlalchemy import make_url, text + +from tests.e2e.plugin_server import capture, create_scope, running_server, wait_for +from tests.plugin_support import write_plugin + +LEDGER = """ +from sqlalchemy import text + +from powercontext.plugins import ApiRequest, PluginApi, Rendering, Route + + +class Ledger: + def __init__(self, ctx): + self.ctx = ctx + + async def record(self, entry, origin): + async with self.ctx.storage.engine().begin() as connection: + await connection.execute( + text("INSERT INTO entries (id, origin) VALUES (:id, :origin)"), {"id": entry, "origin": origin} + ) + + async def render_artifact(self, request): + return Rendering(text=request.artifact.content["text"]) + + async def generate(self, request, writer): + # Worker processes open the same storage as the host process. + for source in request.sources: + await self.record(source.ref.source_id, "worker") + async with writer.transaction() as tx: + for source in request.sources: + await tx.put(writer.stable_id(source.ref.source_id), content={"text": "x"}, source_refs=[source.ref]) + + async def add(self, request: ApiRequest): + await self.record(request.path_params["entry"], "host") + + async def entries(self, request: ApiRequest): + async with self.ctx.storage.engine().connect() as connection: + rows = (await connection.execute(text("SELECT id, origin FROM entries ORDER BY id"))).all() + return {"backend": self.ctx.storage.backend, "entries": [[row.id, row.origin] for row in rows]} + + +async def setup(ctx): + async with ctx.storage.engine().begin() as connection: + await connection.execute( + text("CREATE TABLE IF NOT EXISTS entries (id VARCHAR(64) PRIMARY KEY, origin VARCHAR(16) NOT NULL)") + ) + return Ledger(ctx) +""" + +API = """PluginApi(routes=( + Route(method="POST", path="/entries/{entry}", handler="add", access="authenticated"), + Route(method="GET", path="/entries", handler="entries", access="authenticated"), +))""" + + +async def _create_database(url: str, name: str) -> None: + from powercontext.builtin.persistence.bootstrap import ensure_database + from powercontext.builtin.persistence.oceanbase import OceanBaseConfig + from powercontext.builtin.persistence.oceanbase.profile import sibling_database_engines + + engine, tenant_engine = sibling_database_engines(OceanBaseConfig(url=SecretStr(url)), name) + try: + await ensure_database(engine, tenant_engine, name=name) + finally: + await engine.dispose() + + +def _migrate(url: str, evidence) -> None: + from powercontext.builtin.persistence.migrations.deployment import deployment_runner + from powercontext.builtin.persistence.oceanbase import OceanBaseConfig + from powercontext.server.settings import ServerSettings + + runner = deployment_runner( + ServerSettings(database=OceanBaseConfig(url=SecretStr(url))), + evidence_dir=evidence, + lock_coordination="single-host", + ) + plan = runner.plan(backup_policy="skip") + applied = runner.apply( + plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True, backup_policy="skip", accept_no_backup=True + ) + assert applied.state == "ready" + + +async def _drop_databases(url: str, *names: str) -> None: + from powercontext.builtin.persistence.oceanbase import OceanBaseConfig + from powercontext.builtin.persistence.oceanbase.profile import sibling_database_engines + + engine, tenant_engine = sibling_database_engines(OceanBaseConfig(url=SecretStr(url)), names[0]) + await engine.dispose() + tenant = tenant_engine() + try: + async with tenant.begin() as connection: + for name in names: + await connection.execute(text(f"DROP DATABASE IF EXISTS `{name}`")) + finally: + await tenant.dispose() + + +@pytest.mark.parametrize("backend", ["sqlite", "seekdb", "oceanbase"]) +def test_plugin_storage_is_shared_by_host_and_workers_and_survives_a_restart(tmp_path, backend): + environment = {} + # An embedded seekdb instance takes over a minute to start for the first time. + startup_seconds = 60 if backend == "sqlite" else 300 + name, url, databases = "ledger", "", () + if backend == "seekdb": + if os.environ.get("POWERCONTEXT_TEST_MIGRATION_SEEKDB") != "1": + pytest.skip("real seekdb acceptance not enabled") + pytest.importorskip("pylibseekdb") + environment["POWERCONTEXT_SERVER_DATABASE"] = json.dumps({"kind": "seekdb", "path": str(tmp_path / "seekdb")}) + if backend == "oceanbase": + tenant = os.environ.get("POWERCONTEXT_TEST_MIGRATION_OCEANBASE_URL") + if not tenant: + pytest.skip("real OceanBase acceptance not enabled") + # The tenant outlives the test, so the core database and the plugin's database get names of their own. + run = uuid4().hex[:8] + name = f"ledger-{run}" + databases = (f"pc_plugin_storage_{run}", f"powercontext_plugin_ledger_{run}") + url = make_url(tenant).set(database=databases[0]).render_as_string(hide_password=False) + environment["POWERCONTEXT_SERVER_DATABASE"] = json.dumps({"kind": "oceanbase", "url": url}) + plugins = tmp_path / "plugins" + directory = write_plugin(plugins, name, LEDGER) + entry = directory / "plugin.py" + # The helper's declaration takes literal fields only; the routes are appended to it here. + entry.write_text(entry.read_text(encoding="utf-8").replace(" setup=setup,", f" setup=setup,\n api={API},")) + log = tmp_path / "server.log" + + async def entries(client): + response = await client.get(f"/v1/plugins/{name}/api/entries") + assert response.status_code == 200, response.text + return response.json() + + async def scenario(): + async with running_server(tmp_path, plugins, extra_env=environment, startup_seconds=startup_seconds) as client: + added = await client.post(f"/v1/plugins/{name}/api/entries/from-route") + assert added.status_code in {200, 204}, added.text + scope = await create_scope(client, "plugin-storage") + await capture(client, scope, "from-source", "anything") + stored = await wait_for(lambda: entries(client), lambda value: len(value["entries"]) == 2, log=log) + assert stored == {"backend": backend, "entries": [["from-route", "host"], ["from-source", "worker"]]} + + async with running_server(tmp_path, plugins, extra_env=environment, startup_seconds=startup_seconds) as client: + assert (await entries(client))["entries"] == [["from-route", "host"], ["from-source", "worker"]] + + try: + if databases: + # A remote database is created and migrated explicitly; the Server creates only the plugin's. + asyncio.run(_create_database(url, databases[0])) + _migrate(url, tmp_path / "migration-evidence") + asyncio.run(scenario()) + finally: + if databases: + asyncio.run(_drop_databases(url, *databases)) diff --git a/tests/native/test_oceanbase_engine_recovery.py b/tests/native/test_oceanbase_engine_recovery.py index 5e9ae7da8d..85a6b3ab9f 100644 --- a/tests/native/test_oceanbase_engine_recovery.py +++ b/tests/native/test_oceanbase_engine_recovery.py @@ -175,7 +175,7 @@ def ping(connection, _identity, _guard): _apply(_full_server_runner(backend), policy="manual") resumed = _full_server_runner(backend, acknowledge_previous_run=token) result = _apply(resumed, policy="manual") - assert result.state == "ready" and result.revision == "v1_5_0_004" and result.readiness_scope == "server" + assert result.state == "ready" and result.revision == "v1_5_0_005" and result.readiness_scope == "server" assert result.backup_state == "user_confirmed" and result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" completed = json.loads(journal.read_text()) diff --git a/tests/native/test_personal_service_lifecycle.py b/tests/native/test_personal_service_lifecycle.py index 60dbfcecd2..bf3bdf21d2 100644 --- a/tests/native/test_personal_service_lifecycle.py +++ b/tests/native/test_personal_service_lifecycle.py @@ -402,7 +402,7 @@ def test_native_public_migration_switches_an_installed_130_service( if failure in {"startup", "switch"}: assert applied.exit_code == 1, applied.output assert result["error"] == "service_start_failed" - assert result["database_state"] == "ready" and result["revision"] == "v1_5_0_004" + assert result["database_state"] == "ready" and result["revision"] == "v1_5_0_005" assert adapter.manager_state() in {ManagerState.INACTIVE, ManagerState.FAILED} phase = "switching" if failure == "switch" else "start_failed" assert json.loads(controller.maintenance_path.read_text())["phase"] == phase