diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 8439510145..75e14c901b 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -335,6 +335,8 @@ jobs: if: matrix.suite == 'unit' env: PYTEST_ADDOPTS: --require-dsh-config-runtime --require-claude-code-python-floor + # Limit contention for tests that spawn subprocesses with fixed deadlines. + PYTEST_WORKERS: "8" run: | PYTHONPATH="$PWD/.github/scripts${PYTHONPATH:+:$PYTHONPATH}" \ make unit-test PYTEST_ARGS="-p pytest_ci_diagnostics -o faulthandler_timeout=600 --junitxml=$RUNNER_TEMP/pytest-diagnostics/unit.xml" @@ -366,6 +368,8 @@ jobs: if: matrix.suite == 'e2e' env: PYTEST_ADDOPTS: --ci-shard-index=${{ matrix.shard-index }} --ci-shard-count=${{ matrix.shard-count }} + # Keep deadline-sensitive SQLite and subprocess tests within the runner budget. + PYTEST_WORKERS: "8" run: | PYTHONPATH="$PWD/.github/scripts${PYTHONPATH:+:$PYTHONPATH}" \ make e2e-test-parallel PYTEST_ARGS="-p pytest_ci_diagnostics -o faulthandler_timeout=600 --junitxml=$RUNNER_TEMP/pytest-diagnostics/e2e.xml" diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index ac0e128811..63e5f65d9e 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1960,6 +1960,27 @@ "search_memory" ] }, + { + "id": "sqlite-memory-1-6-deedec9b-v1", + "serverCommit": "deedec9bcdf1272a4a6d2e0fea5db0b71b57d4ec", + "contractSha256": "419278292c9065144d081c7cb369b8ff2fcd4161c8c56052a97b5dcfa6b89d52", + "artifactSha256": "4aea81977845c40bd670a3a1207d0374ef151857d4592772369cf0fe603161bf", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ] + }, { "id": "sqlite-processing-status-2672c76a-v1", "serverCommit": "2672c76ac9bd25635e49a567f6963da614036b73", @@ -2001,5 +2022,26 @@ "remember_memory", "search_memory" ] + }, + { + "id": "sqlite-memory-1-6-0d1bfe33-v1", + "serverCommit": "0d1bfe33a3b894086b9c6e5c324b70f85df7cb73", + "contractSha256": "727649c606e096a92d88e56959e24e751df9398fd90175464b59f44b98cd40b6", + "artifactSha256": "0480c6c1cb945cc6908bca03b4c11b99903438da19f19f4f58bc53401b19af1d", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ] } ] diff --git a/desktop/src-tauri/src/transport/api.rs b/desktop/src-tauri/src/transport/api.rs index 8cacb3a510..f12fae2f3a 100644 --- a/desktop/src-tauri/src/transport/api.rs +++ b/desktop/src-tauri/src/transport/api.rs @@ -506,6 +506,7 @@ impl ServerApi { reason: None, expected_revision: None, description: None, + idempotency_key: None, }; let body = serde_json::to_value(request) .map_err(|_| ApiFailure::before(SafeError::InvalidInput))?; diff --git a/desktop/src-tauri/src/transport/operations.json b/desktop/src-tauri/src/transport/operations.json index 822b84492c..b1715f81b7 100644 --- a/desktop/src-tauri/src/transport/operations.json +++ b/desktop/src-tauri/src/transport/operations.json @@ -1,5 +1,5 @@ { - "contractSha256": "32a8aebe3ac5b5eb388e03e0b0e25fc95ea232b10b94caf16323bd369cd7bf69", + "contractSha256": "727649c606e096a92d88e56959e24e751df9398fd90175464b59f44b98cd40b6", "operations": { "get_liveness": { "method": "GET", diff --git a/desktop/src-tauri/src/transport/wire.rs b/desktop/src-tauri/src/transport/wire.rs index 5e4be72c05..445680ffbc 100644 --- a/desktop/src-tauri/src/transport/wire.rs +++ b/desktop/src-tauri/src/transport/wire.rs @@ -2315,6 +2315,16 @@ pub struct RememberMemoryRequest { skip_serializing_if = "Option::is_none" )] pub description: Option>, + /// Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key. + #[ts(optional)] + #[ts(type = "string | null")] + #[serde( + rename = "idempotency_key", + default, + with = "::serde_with::rust::double_option", + skip_serializing_if = "Option::is_none" + )] + pub idempotency_key: Option>, } impl RememberMemoryRequest { @@ -2327,6 +2337,7 @@ impl RememberMemoryRequest { reason: None, expected_revision: None, description: None, + idempotency_key: None, } } } diff --git a/desktop/ui/src/generated/api.d.ts b/desktop/ui/src/generated/api.d.ts index 7c8f0155c0..b9a517c3b3 100644 --- a/desktop/ui/src/generated/api.d.ts +++ b/desktop/ui/src/generated/api.d.ts @@ -1362,7 +1362,7 @@ export interface paths { put?: never; /** * Create Atomic Memory through the legacy remember input - * @description Create a standalone Atomic Memory and formal Owner. Omit expected_revision or pass null. Non-null legacy collection revision preconditions are unsupported before any write. Response records use true Atomic ArtifactRefs. + * @description Create a standalone Atomic Memory and formal Owner. Omit expected_revision or pass null. Non-null legacy collection revision preconditions are unsupported before any write. Response records use true Atomic ArtifactRefs. With idempotency_key, a retry of the same creation within 24 hours replays the original response, and reuse of the key for different content returns 409 idempotency_conflict with details.kind memory_idempotency_key. */ post: operations["remember_memory"]; delete?: never; @@ -5707,6 +5707,8 @@ export interface components { expected_revision?: number | null; /** @description Optional supplied single-line summary. When omitted, the Server stores a whitespace-collapsed text prefix of at most 200 Unicode characters, including a trailing ellipsis when truncated. Explicit writes do not invoke a generation model. */ description?: string | null; + /** @description Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key. */ + idempotency_key?: string | null; }; RetireMemoryEntryRequest: { scope_id: string; diff --git a/desktop/ui/src/generated/ipc.ts b/desktop/ui/src/generated/ipc.ts index b4045cf384..3fac183c74 100644 --- a/desktop/ui/src/generated/ipc.ts +++ b/desktop/ui/src/generated/ipc.ts @@ -346,7 +346,11 @@ text: string, reason?: string | null, expected_revision?: number | null, /** * Optional supplied single-line summary. When omitted, the Server stores a whitespace-collapsed text prefix of at most 200 Unicode characters, including a trailing ellipsis when truncated. Explicit writes do not invoke a generation model. */ -description?: string | null, }; +description?: string | null, +/** + * Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key. + */ +idempotency_key?: string | null, }; export type ResolvedUsagePeriod = { preset: StatsPeriod, start_date: string, end_date: string, timezone: Timezone, }; export type Role = "leader" | "standby"; export type ScopeDescriptor = { scope_id: string, title: string, summary: string, parent_scope_id?: string | null, context_references: Array, external_references: Array, version: number, }; diff --git a/desktop/ui/src/generated/operations.ts b/desktop/ui/src/generated/operations.ts index 725c378c6d..0e7aca0d83 100644 --- a/desktop/ui/src/generated/operations.ts +++ b/desktop/ui/src/generated/operations.ts @@ -15,7 +15,7 @@ */ // Generated from openapi/powercontext.yaml. Do not edit. -export const contractSha256 = "32a8aebe3ac5b5eb388e03e0b0e25fc95ea232b10b94caf16323bd369cd7bf69"; +export const contractSha256 = "727649c606e096a92d88e56959e24e751df9398fd90175464b59f44b98cd40b6"; export const operations = { "get_liveness": { "method": "GET", diff --git a/desktop/ui/tests/app.test.tsx b/desktop/ui/tests/app.test.tsx index 1ec07b938b..0183c19ac0 100644 --- a/desktop/ui/tests/app.test.tsx +++ b/desktop/ui/tests/app.test.tsx @@ -194,7 +194,16 @@ test.each(["stale_context", "forbidden"] as const)( , ); await user.click(screen.getByRole("button", { name: "Memories" })); - await user.click(await enterMemory(user, "Private input")); + await user.click( + await screen.findByRole("button", { name: "Record memory" }), + ); + // This regression exercises privacy invalidation, not per-keystroke editing. + fireEvent.change(screen.getByRole("textbox", { name: "Memory content" }), { + target: { value: "Private input" }, + }); + await user.click( + screen.getByRole("button", { name: "Save to current space" }), + ); expect(await screen.findByText("Exact private detail")).toBeTruthy(); expect( screen.getByRole("button", { name: "Cached private memory" }), @@ -208,7 +217,7 @@ test.each(["stale_context", "forbidden"] as const)( await user.click(panel.getByRole("button", { name: "Revision details" })); expect(panel.getByText(reference.artifact_id)).toBeTruthy(); - await user.type(search, "check access"); + fireEvent.change(search, { target: { value: "check access" } }); if (code === "forbidden") { expect( await screen.findByText(/this identity cannot perform/i), diff --git a/docs/en/docs/operate/database-migrations.md b/docs/en/docs/operate/database-migrations.md index 57ef3f12d2..6b76e51e22 100644 --- a/docs/en/docs/operate/database-migrations.md +++ b/docs/en/docs/operate/database-migrations.md @@ -97,6 +97,12 @@ Revision `v1_5_0_005` removes the previous Artifact plugin-framework storage and Revision `v1_5_0_006` adds `pc_source_runners` and `pc_source_collect_targets` for Source collection and drops the empty `pc_source_write_plugins`; it rewrites no records. While `pc_source_write_plugins` still holds records (after `source load --kind write`), the upgrade is refused with `unsupported_plugin_data` and the database stays unchanged. The previous version has no operation that removes these registrations, so such a database currently has no supported in-place upgrade path: keep using the previous version or move to a new database, and do not delete the records by hand to bypass the check. The previous Source management service's own SQLite is not migrated. See [Source plugins](../workflows/source-plugins.md). +On development builds with keyed Memory creation, both paths continue from `v1_6_0` to draft `000`. + +The cumulative draft `000` registers `pc_atomic_memory_idempotency`, the retry receipts for keyed `remember_memory` creations, with an index on their expiry time. Existing managed databases require explicit migration before Server startup; the migration creates an empty table and rewrites no existing data. A receipt stores SHA-256 digests of the key namespace and the created content, the bound Artifact revision and the creation state version; it stores neither the raw key, the principal ID nor the memory body. Receipts expire 24 hours after creation and are removed in bounded batches. See [Atomic Memory](../workflows/atomic-memory.md) for retry behavior. + +Rebuild development databases and migration plans that use an earlier `000` draft or the unpublished `v1_5_2_001` revision. + Revision `v1_4_1_006` registers `pc_source_write_plugins` for persisted Source write plugin declarations. Revision `v1_5_0_001` adds Artifact plugin registration fields, family schemas, search state and projections, index coverage and change tracking, and vector-space/index registrations. SQLite also registers portable vector @@ -175,12 +181,13 @@ literal mutable draft ID `000`. The registered revisions are: | `v1_5_0_005` | 1.5.0 | 5 | `v1_5_0_005` | Remove previous plugin-framework storage and add nullable Artifact metadata | | `v1_5_0_006` | 1.5.0 | 6 | `v1_5_0_006` | Source collection runner and target tables; remove the write plugin registry | | `v1_6_0` | 1.6.0 | — | `v1_6_0` | Independent prepare diagnostics | +| `000` | — | — | `000` | Keyed Memory creation receipts | -Both registered source paths reach `v1_6_0` after `v1_5_0_006`; only 1.3.0 is selected for CI upgrade acceptance: +Both registered source paths reach `000` after `v1_6_0`; only 1.3.0 is selected for CI upgrade acceptance: ```text -1.3.0: v1_3_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_0_005 -> v1_5_0_006 -> v1_6_0 -1.4.0: v1_4_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_0_005 -> v1_5_0_006 -> v1_6_0 +1.3.0: v1_3_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_0_005 -> v1_5_0_006 -> v1_6_0 -> 000 +1.4.0: v1_4_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_0_005 -> v1_5_0_006 -> v1_6_0 -> 000 ``` `status` and `plan` show `source_migration`, `target_migration` and `pending_migrations` diff --git a/docs/en/docs/operate/observability.md b/docs/en/docs/operate/observability.md index d6a69d90c9..8742dc2cc7 100644 --- a/docs/en/docs/operate/observability.md +++ b/docs/en/docs/operate/observability.md @@ -92,6 +92,11 @@ declaration bodies, or requested content. Its `unit` is the retained fact (`sour `evidence_mismatch`. Integrity causes are emitted at `WARNING`; expected historical gaps stay at `INFO` or `DEBUG`. Integrity causes such as `manifest_conflict` are alertable and distinct from an absent declaration. +The `atomic_memory.idempotency.cleanup_failed` event reports that a keyed `remember_memory` creation committed but +the bounded removal of expired retry keys that follows it failed. The creation and its response are unaffected, and a +later keyed creation retries the removal. It is emitted at `WARNING` with `operation` `remember_memory`, `unit` +`atomic-memory`, `outcome` `failure`, and `exception_type`; it never carries keys, principals, or memory content. + Server roles are `all` (API and supervisor), `api`, and `background`; child processes use `worker`. Explicit logging configuration without a deployment role uses `server`. JSON identity fields correspond to trace resource attributes `service.name`, `service.version`, `service.instance.id`, and `powercontext.service.role`. `service_version` is absent diff --git a/docs/en/docs/operate/troubleshoot.md b/docs/en/docs/operate/troubleshoot.md index 695bb1d938..d5cdb7716d 100644 --- a/docs/en/docs/operate/troubleshoot.md +++ b/docs/en/docs/operate/troubleshoot.md @@ -269,7 +269,7 @@ so the previous database remains available for recovery: ```bash obloader -D --csv \ - --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_context_prepare_diagnostics,pc_artifacts,pc_portable_restore_receipts,pc_source_cursors,pc_memory_source_windows,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_work_blocks,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_source_runners,pc_source_collect_targets,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_recall_effort_daily,pc_receipt_migration_review,pc_decision_observations,pc_lexical_projection_versions' \ + --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_context_prepare_diagnostics,pc_artifacts,pc_portable_restore_receipts,pc_source_cursors,pc_memory_source_windows,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_work_blocks,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_source_runners,pc_source_collect_targets,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_recall_effort_daily,pc_receipt_migration_review,pc_decision_observations,pc_lexical_projection_versions,pc_atomic_memory_idempotency' \ -f ``` diff --git a/docs/en/docs/workflows/atomic-memory.md b/docs/en/docs/workflows/atomic-memory.md index 2e2d0bf00b..a5afd7102e 100644 --- a/docs/en/docs/workflows/atomic-memory.md +++ b/docs/en/docs/workflows/atomic-memory.md @@ -52,6 +52,34 @@ Submit complete content to `PUT /v1/scopes/S/artifacts/atomic-memory/M`, sending Success creates the next content revision. Missing `If-Match` returns `428 precondition_required`; a stale value returns `412 revision_conflict`. Read and reconcile the content before submitting again. +## Retry remember_memory safely + +`POST /v1/memory/remember` (`remember_memory`) creates a new memory on every call. To retry a call whose response was +lost without creating a duplicate, send an `idempotency_key`: 1 to 256 printable ASCII characters other than space. +Generate a fresh unguessable key, such as a UUID, for each logical write, and reuse it only to retry that write: + +```json +{ + "scope_id": "S", + "kind": "preference", + "text": "Prefer short pull requests.", + "idempotency_key": "3f0c8f5e-7a51-4c1e-9a43-0f1e2b7d9c60" +} +``` + +Keys are scoped to the Scope and the authenticated principal; with access control disabled, all callers share one +namespace per Scope. Within 24 hours of the creation, a request with the same key and the same stored content returns +the original response: the same `ArtifactRef` of revision 1 and the state recorded at creation, even if the memory has +since been revised, forgotten or merged. Read current state through the Atomic Memory read operations. Content is the +same when the normalized `text`, `kind`, `description` (an omitted description equals the default derived from the +text) and content schema match; `reason` is not compared. The same key with different content returns +`409 idempotency_conflict` with `error.details.kind: "memory_idempotency_key"` and writes nothing; use a new key for +the new content. After 24 hours the key behaves as unused and creates a new memory. + +Each replay rechecks the caller's current authorization. The server stores only digests of the key namespace and +content, never the raw key or memory body. Neither the server, the Python SDK nor the MCP tool generates keys or +retries automatically, and `expected_revision` keeps its existing behavior. + ## Current state and forgetting `GET /v1/scopes/S/artifacts/atomic-memory/M/state` returns the current exact `artifact` reference, `state`, diff --git a/docs/en/rfcs/1437_source_artifact_rest_api.md b/docs/en/rfcs/1437_source_artifact_rest_api.md index 0c1906e191..3346284209 100644 --- a/docs/en/rfcs/1437_source_artifact_rest_api.md +++ b/docs/en/rfcs/1437_source_artifact_rest_api.md @@ -475,6 +475,12 @@ return `422` instead of being ignored. creates a new resource. After a client timeout, the caller must confirm the result from business context and cannot assume that retry is idempotent. +Explicit Atomic Memory creation through `remember_memory` is outside these operations and is the only Atomic Memory +creation path with an idempotency key. The "Idempotent explicit creation" section of +[RFC 1809](1809-atomic-memory.md) defines its optional `idempotency_key` request body field, namespace, request +digest, replay, and retention. That field does not apply to Source Create or Artifact Create, and no operation accepts +an `Idempotency-Key` header. Creating an Atomic Memory through Artifact Create remains non-idempotent. + ## Status and error model | Status | Scenario | @@ -510,6 +516,9 @@ The common error body is: Errors must not reveal whether a resource in another Scope exists. Permission and invisibility scenarios return `403` or `404` according to the common security policy. +For `remember_memory`, an idempotency key already bound to a different request returns `409` with the existing code +`idempotency_conflict` and `details.kind` set to `memory_idempotency_key`. No new error code is introduced for it. + ## OpenAPI contract `openapi/powercontext.yaml` is the sole source of truth for the HTTP contract. The principal schemas are: diff --git a/docs/en/rfcs/1809-atomic-memory.md b/docs/en/rfcs/1809-atomic-memory.md index 5787447722..801cad2a64 100644 --- a/docs/en/rfcs/1809-atomic-memory.md +++ b/docs/en/rfcs/1809-atomic-memory.md @@ -193,6 +193,163 @@ During restoration, the server checks current content versions, states, and merg transaction. A preview identifier adds validation against the preview; requests without one use current state. The checked conditions must still hold at commit, without overwriting intervening updates. +## Idempotent explicit creation + +`remember_memory` is the only Atomic Memory creation entry point that accepts an idempotency key. It lets a caller +that lost a response retry one explicit creation without creating a second memory. Requests without a key keep their +existing behavior: every successful call creates a new memory. Revision, forgetting, restoration, merging, extraction, +Source processing, and RFC 1437's generic Artifact Create accept no key. The server never deduplicates by content and +never retries on a caller's behalf. + +### Request field and namespace + +`RememberMemoryRequest` adds optional `idempotency_key`: 1 to 256 printable ASCII characters other than space, +matching `^[!-~]{1,256}$`. The server compares keys byte for byte without trimming, case folding, or other +normalization. Omitting the field or passing `null` means no key. A key that does not match the pattern is rejected +with `422` under the common request-validation policy before any lookup or write: `invalid_request`, or +`invalid_access_request` when enforced access control validates the request body first. + +A key is unique within one namespace: the operation `remember_memory`, `scope_id`, and the authenticated principal's +type and ID. When access control is disabled, the principal component is empty, so all callers of that deployment share +one namespace per Scope. The same key in another Scope, from another principal, or for another operation names an +independent write. The HTTP API, Python SDK, and MCP tool carry the field unchanged; none of them generates keys or +retries automatically. Callers generate a fresh unguessable key, such as a UUID, for each logical write and reuse it +only to retry that write. The MCP server instructions and the shared Skill reference give models the same guidance, +and tell them to use a new key after a conflict. The Dify `pc_remember` tool does not expose the field. + +The server stores only a SHA-256 digest of the namespace and key, never the raw key or the principal ID in clear. + +### Request digest + +The request digest identifies a logical write by the revision 1 content it produces. Version 1 is the lowercase +hexadecimal SHA-256 of the RFC 8785 serialization of a JSON object with exactly these four members, matching the +`AtomicMemoryContent` the writer would store: + +- `schema` is `powercontext.atomic-memory.v1`. +- `kind` is the submitted value, unchanged, as the writer stores it. +- `text` is the result of the writer's `normalize_text`: Unicode NFC, then removal of leading and trailing whitespace. +- `description` is the submitted value when present. When the field is omitted or `null`, it is the default + description the writer derives from the normalized text. + +The object has no `creation` member, because an explicit creation never carries merge metadata. Strings are hashed as +they would be stored: apart from `text`, no Unicode normalization is applied, so a helper that normalizes every string +must not compute this digest. Changing the member set or the behavior of `normalize_text` or of the default +description requires a new digest version. + +Omitting `description`, passing `null`, and passing exactly the default description therefore produce one digest, +because they store the same content. `reason` is not part of the written content and is ignored. `expected_revision` +must be omitted or `null`; a non-null value is rejected before lookup. `scope_id` and the principal belong to the +namespace, not the digest. + +The Source written for revision 1 records the command of the request that performed the creation. A retry whose text +differs only by normalization replays that creation and does not rewrite its Source. Each key record stores its digest +version. A new digest version applies only to new keys; the server keeps computing every version that can still appear +within the retention period. + +### Results + +| Lookup in the key's namespace | Result | +| --- | --- | +| No unexpired record | Create the memory as without a key, and bind the key in the same transaction. | +| Record with the same digest | Replay the original result. Prepare no Embedding and write nothing. | +| Record with a different digest | Return `409 idempotency_conflict` with details `{"kind": "memory_idempotency_key"}`. Write nothing. | + +A replay returns the same `MemoryMutationResponse` as the original creation: `changed: true` and one record with the +exact `ArtifactRef` of revision 1, its `kind` and `text`, `state: active`, the state version recorded at creation, and +`merged_into_id: null`. Content comes from the immutable revision 1, and the creation-time state comes from the key +record. A creation currently always yields revision 1, state version 0, and no merge target; the key record stores the +revision and state version so that a replay does not depend on that invariant. Later revision, forgetting, merging, +restoration, or retirement does not change the replay, and a replay never substitutes the current head. Callers read +current state through the Atomic Memory read operations. + +For a keyed creation, the original response is built through the same exact-revision read, so a revision committed +concurrently between creation and response changes neither result. Requests without a key keep their existing response +construction. The response carries no replay marker; a caller that must distinguish a replay compares the returned +identity with its own records. + +### Authorization + +The `scope.contribute` check runs before key lookup, as for any creation. A denied caller receives `403` without +learning whether the key exists. Because the principal is part of the namespace, another principal cannot hit or probe +a key. + +A replay reads revision 1 with the caller's current context through the same authorized exact-revision read as Get +Artifact Revision for the `atomic-memory` Family. If the caller can no longer read that memory, for example after its +access was revoked, the request returns that read's error under the common security policy: `403 forbidden` for a +denial, or `503 artifact_owner_pending` while ownership is not yet established. `404 artifact_not_found` occurs only if +revision 1 cannot be found, which does not happen in normal operation because revision 1 is immutable and is never +physically deleted. It neither discloses the record nor creates a new memory, and the key stays bound until it expires. + +A conflict discloses only that the caller's own key in that Scope was already used for different content. Other +operations also return `idempotency_conflict`, so callers identify this case by `details.kind`. + +### Atomicity and failures + +Request validation, authorization, writer validation, and digest computation finish before lookup. Lookup is one +primary-key read in its own read transaction and uses the database clock. Only a miss proceeds to the existing +preparation outside the write transaction, including Embedding generation. + +The write transaction first deletes the record for the same namespace only if its `expires_at` is not later than the +current database time, so a live key committed concurrently is never removed. It then inserts the key record, writes +the Sources, revision 1, governance state, Owner, and search and evidence projections as before, and commits everything +together. The key record holds the namespace digest, request digest and its version, +`scope_id`, `artifact_id`, revision, creation-time state version, `created_at`, and `expires_at`. It stores no memory +body. + +- A validation, authorization, or preparation failure, or cancellation before commit, leaves no key, Source, + Artifact, Owner, or projection. A retry with the key runs the creation again. +- A failure inside the write transaction rolls back the key with everything else. +- A response lost after commit, including a cancellation whose outcome the caller cannot observe, leaves the key bound. + A retry replays the committed result. +- Concurrent requests with one key race on the key record's primary key. The loser rolls back, rereads the key in a + new transaction, and returns the replay or conflict from the table above. If the reread finds no record, the + integrity error was unrelated and is returned unchanged. The loser's prepared Embedding is discarded. + +Uniqueness comes from the database constraint rather than an in-process lock, so it holds across connections, +processes, and Server instances on SQLite and on OceanBase/seekdb. + +### Retention and cleanup + +A key is retained for 24 hours from the database time at which its creating transaction inserts it. Replays do not +extend retention. A record whose `expires_at` is not later than the current database time is treated as absent: the +same key then starts a new creation and replaces the expired record inside that creation's transaction. A caller must +not expect a replay after 24 hours. + +After a keyed creation commits, the server deletes at most 32 expired records in a separate short transaction: one +range read on the `expires_at` index with a limit of 32, then one delete by primary key that rechecks expiry. Cleanup +failure does not change the creation result. Each keyed creation adds one record and removes up to 32 expired ones, so +an expired backlog shrinks while keyed writes continue. Requests without a key do not touch the table. No operation +scans the whole table: lookup and binding use the primary key, and cleanup uses the expiry index. + +### Storage and upgrade + +Key records live in the new table `pc_atomic_memory_idempotency`, with the namespace digest as the primary key and a +secondary index on `expires_at`. Fixed-width digests keep the key within MySQL-compatible index limits. A new revision +of the server-resource migration chain adds the table with SQLite and MySQL schemas, manifest resources, and SQLite +fingerprint. Published revisions do not change. + +At Server startup, an empty persistent SQLite or seekdb database is initialized through the full revision chain, +including the new revision. OceanBase requires an explicit `powercontext server db-migrate` job even for an empty +database. A managed database at an earlier revision makes Server startup fail with a migration-required error until +`powercontext server db-migrate apply` succeeds; startup never upgrades it implicitly. Only unmanaged storage, such as +in-memory SQLite, creates the table from the built-in table registry. Restarting or applying the upgrade again +preserves existing records. + +### Acceptance + +| Scenario | Expected result | +| --- | --- | +| Same key and digest | One Artifact and Source, plus one Owner when access control is enabled; every response equals the first. | +| Same key, different digest | `409 idempotency_conflict`; the original memory, Source, Owner, and projections are unchanged. | +| No key; one key in another Scope or from another principal; different keys | Independent creations. | +| `description` omitted, `null`, or equal to the default; text differing only by NFC or outer whitespace | One digest; replay. | +| Concurrent requests on separate connections or processes | Exactly one creation; the others replay or conflict by digest. | +| Failure or cancellation before commit; response lost after commit | No orphaned rows; a retry creates once or replays the commit. | +| Restart, then later revision, forgetting, merging, or retirement | The replay still returns revision 1 and the creation-time state. | +| Revoked access; another principal | No disclosure and no write: the exact-read error, or an independent namespace. | +| Retention boundary and expired-key reuse | Expired at `expires_at`; reuse creates a new memory; cleanup removes at most 32 indexed records per keyed write. | +| Fresh database; upgraded managed database | Real Server startup and `db-migrate` succeed; repeated startup or upgrade keeps records. | + ## Upgrade and compatibility Existing deployments upgrade offline under [RFC #1771](https://github.com/oceanbase/powercontext/pull/1771). Its unified @@ -231,7 +388,7 @@ Atomic identities and revisions: the new `ArtifactRef`. - `list` and `search` query Atomic Memory in the Scope using the new model's listing, state, and search semantics. - `remember` supports simple creation only, without legacy entry updates, collection revision appends, or evidence - referring to old objects. + referring to old objects. It accepts an optional idempotency key, as described in Idempotent explicit creation. - `flush` continues extraction into Atomic Memory using the preserved Source processing progress. All other legacy entry points explicitly stop accepting the old model. These include generic `family=memory` @@ -266,6 +423,8 @@ already migrated to Atomic Memory. revisions do not automatically roll back. - Old clients must update their references and calls. Five legacy server entry points still need adapters, while online reading and tracing of old collections end. +- Idempotent creation adds a key table and a fixed 24-hour retention period. A retry after expiry creates a second + memory, and a replay reports creation-time state rather than current state. # Rationale and alternatives @@ -289,6 +448,13 @@ retained history, correction, and undo to handle mistakes without requiring user each contradiction for users to resolve would accumulate maintenance work. The model updates current memories using time, with history and restoration supporting correction, without a separate unresolved-conflict workflow. +**Idempotency key on explicit creation only.** A lost `remember_memory` response is the case in which a caller cannot +tell whether its write happened. Content-based deduplication would merge writes the caller intended to keep separate, +and a cross-Family idempotency framework would have to define replay for revision, merge, and restoration, whose +results depend on current state. A digest over stored content treats requests that write the same memory as the same +request. Replaying revision 1 with its creation-time state keeps a retry's result independent of later changes; +replaying the current head would let a retry return content the caller never wrote. + # Prior art - [RFC 1345](1345_scope_organization_and_agent_integration.md) and [1549](1549_artifact_family_unification.md) provide @@ -309,8 +475,8 @@ time, with history and restoration supporting correction, without a separate unr and merged? This RFC defines Atomic Memory behavior; adoption and adaptation by other families remain separate decisions. Physical deletion of Atomic content history, automatic merging across Scopes, and whole-Scope snapshot rollback are -outside this proposal. Table schemas, API parameters, locking, and transaction implementation belong in the implementation -design. Migration follows RFC #1771. +outside this proposal. Apart from the idempotent creation protocol above, table schemas, API parameters, locking, and +transaction implementation belong in the implementation design. Migration follows RFC #1771. # Future possibilities diff --git a/docs/zh/docs/operate/database-migrations.md b/docs/zh/docs/operate/database-migrations.md index 26707c3262..fc1d166b59 100644 --- a/docs/zh/docs/operate/database-migrations.md +++ b/docs/zh/docs/operate/database-migrations.md @@ -80,6 +80,12 @@ payload 身份及待处理 intent。兼容的当前任务原样保留,不套 修订 `v1_5_0_006` 新增 Source 采集用的 `pc_source_runners` 和 `pc_source_collect_targets`,并删除空的 `pc_source_write_plugins`,不改写任何记录。`pc_source_write_plugins` 中仍有记录时(执行过 `source load --kind write`),升级以 `unsupported_plugin_data` 拒绝,数据库保持不变;旧版本没有删除这些登记的操作,所以这样的数据库目前没有受支持的原地升级路径,请继续使用旧版本或改用新的数据库,不要手工删除记录来绕过检查。旧 Source 管理服务自己的 SQLite 不迁移。详见 [Source 插件](../workflows/source-plugins.md)。 +支持带键 Memory 创建的开发版本中,两条路径均从 `v1_6_0` 继续迁移到草稿 `000`。 + +累计迁移草稿 `000` 登记 `pc_atomic_memory_idempotency`,即带键 `remember_memory` 创建的重试回执,并为过期时间建立索引。已有受管数据库必须在 Server 启动前显式迁移;迁移只创建空表,不重写任何既有数据。回执保存键命名空间与所创建内容的 SHA-256 摘要、所绑定的 Artifact revision 及创建时的 state version,不保存原始键、principal ID 或记忆正文。回执在创建 24 小时后过期,并按有界批次清理。重试行为参见 [Atomic Memory](../workflows/atomic-memory.md)。 + +使用早期草稿 `000` 或未发布修订 `v1_5_2_001` 的开发数据库和迁移计划需要重建。 + `v1_5_0_001` 增加 Artifact 插件注册字段、family schema、检索状态和投影、索引覆盖与变更跟踪,以及向量空间和索引登记。 SQLite 还登记可移植向量和 FTS 辅助结构。两条来源链均通过显式维护加入这些增量变更;历史修订资源与校验和保持不变。 根据已登记空间创建的原生向量表,必须通过精确布局检查才能纳入后续维护。上述登记不扩展受支持的来源版本, @@ -145,12 +151,13 @@ MySQL 兼容后端的结构反射支持 CHECK 表达式中的二元 `+`、`-`、 | `v1_5_0_005` | 1.5.0 | 第五步 | `v1_5_0_005` | 移除旧插件框架存储并新增可空的 Artifact 元数据 | | `v1_5_0_006` | 1.5.0 | 第六步 | `v1_5_0_006` | Source 采集的 runner 与目标表,移除 write 插件登记表 | | `v1_6_0` | 1.6.0 | — | `v1_6_0` | 独立上下文准备诊断 | +| `000` | — | — | `000` | 带键 Memory 创建回执 | -两条已登记来源路径都在 `v1_5_0_006` 之后到达 `v1_6_0`;CI 升级验收只选择 1.3.0: +两条已登记来源路径都在 `v1_6_0` 之后到达 `000`;CI 升级验收只选择 1.3.0: ```text -1.3.0: v1_3_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_0_005 -> v1_5_0_006 -> v1_6_0 -1.4.0: v1_4_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_0_005 -> v1_5_0_006 -> v1_6_0 +1.3.0: v1_3_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_0_005 -> v1_5_0_006 -> v1_6_0 -> 000 +1.4.0: v1_4_0_000 -> v1_4_1_001 -> v1_4_1_002 -> v1_4_1_003 -> v1_4_1_004 -> v1_4_1_005 -> v1_4_1_006 -> v1_5_0_001 -> v1_5_0_002 -> v1_5_0_003 -> v1_5_0_004 -> v1_5_0_005 -> v1_5_0_006 -> v1_6_0 -> 000 ``` `status` 和 `plan` 在原有机器字段之前显示 `source_migration`、`target_migration`、 diff --git a/docs/zh/docs/operate/observability.md b/docs/zh/docs/operate/observability.md index 134ead7300..eec643b70e 100644 --- a/docs/zh/docs/operate/observability.md +++ b/docs/zh/docs/operate/observability.md @@ -90,6 +90,10 @@ Code 专用诊断字段仅在 `code.*` events 中输出。 已登记的完整性原因以 `WARNING` 输出;可预期的历史缺口保持 `INFO` 或 `DEBUG`。`manifest_conflict` 这类完整性原因 可告警,并与“从未声明”区分开。 +`atomic_memory.idempotency.cleanup_failed` 事件表示带键的 `remember_memory` 创建已提交,但随后对过期重试键的 +有界清理失败。创建结果与响应不受影响,之后的带键创建会再次清理。该事件以 `WARNING` 输出,`operation` 为 +`remember_memory`,`unit` 为 `atomic-memory`,`outcome` 为 `failure`,并带 `exception_type`;不携带键、主体或记忆内容。 + Server role 为 `all`(API 与 supervisor)、`api` 或 `background`,child process 使用 `worker`。 显式配置 logging 但没有指定 deployment role 时使用 `server`。JSON identity 字段对应 trace resource attributes: `service.name`、`service.version`、`service.instance.id` 和 `powercontext.service.role`。 diff --git a/docs/zh/docs/operate/troubleshoot.md b/docs/zh/docs/operate/troubleshoot.md index b048884bba..0643ae558b 100644 --- a/docs/zh/docs/operate/troubleshoot.md +++ b/docs/zh/docs/operate/troubleshoot.md @@ -260,7 +260,7 @@ collation,但不会包含数据库 URL 或凭据。 ```bash obloader -D --csv \ - --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_context_prepare_diagnostics,pc_artifacts,pc_portable_restore_receipts,pc_source_cursors,pc_memory_source_windows,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_work_blocks,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_source_runners,pc_source_collect_targets,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_recall_effort_daily,pc_receipt_migration_review,pc_decision_observations,pc_lexical_projection_versions' \ + --table 'pc_scopes,pc_source_journal_heads,pc_sources,pc_context_prepare_diagnostics,pc_artifacts,pc_portable_restore_receipts,pc_source_cursors,pc_memory_source_windows,pc_artifact_processing_leases,pc_artifact_processing_binding_states,pc_artifact_processing_pending,pc_artifact_processing_auto_wave_targets,pc_artifact_processing_sequences,pc_artifact_processing_intents,pc_topic_memory_processing_targets,pc_artifact_processing_schema,pc_artifact_processing_migration_receipts,pc_topic_memory_work_budgets,pc_topic_memory_work_blocks,pc_topic_memory_retrieval_shape,pc_connector_checkpoints,pc_source_definition_manifests,pc_source_runners,pc_source_collect_targets,pc_external_skill_registrations,pc_skill_packages,pc_agent_skill_targets,pc_skill_publications,pc_model_usage_daily,pc_recall_token_daily,pc_recall_effort_daily,pc_receipt_migration_review,pc_decision_observations,pc_lexical_projection_versions,pc_atomic_memory_idempotency' \ -f ``` diff --git a/docs/zh/docs/workflows/atomic-memory.md b/docs/zh/docs/workflows/atomic-memory.md index dfa70ea51f..3923344cd1 100644 --- a/docs/zh/docs/workflows/atomic-memory.md +++ b/docs/zh/docs/workflows/atomic-memory.md @@ -50,6 +50,30 @@ Atomic Memory 将每条事实、偏好或决策保存为独立的 `atomic-memory 成功后正文产生下一条 revision。缺少 `If-Match` 返回 `428 precondition_required`, 过期返回 `412 revision_conflict`。重新读取并协调正文后再提交。 +## 安全重试 remember_memory + +`POST /v1/memory/remember`(`remember_memory`)每次调用都会创建一条新记忆。若响应丢失,需要重试而不产生重复记忆, +可发送 `idempotency_key`:1 到 256 个除空格外的可打印 ASCII 字符。每次逻辑写入生成一个新的、不可猜测的键(例如 UUID), +且只在重试该次写入时复用: + +```json +{ + "scope_id": "S", + "kind": "preference", + "text": "Prefer short pull requests.", + "idempotency_key": "3f0c8f5e-7a51-4c1e-9a43-0f1e2b7d9c60" +} +``` + +键的作用域是 Scope 与已认证的 principal;关闭访问控制时,所有调用方在同一 Scope 内共享一个命名空间。创建后 24 小时内, +相同键且存储内容相同的请求返回原始响应:同一 revision 1 的 `ArtifactRef` 与创建时记录的状态,即使该记忆随后被修订、遗忘或合并。 +当前状态请通过 Atomic Memory 读取操作获取。规范化后的 `text`、`kind`、`description`(省略时等同于由正文派生的默认描述) +及正文 schema 一致即视为内容相同;`reason` 不参与比较。相同键配不同内容返回 `409 idempotency_conflict`, +`error.details.kind` 为 `"memory_idempotency_key"`,且不写入任何数据;新内容请使用新键。24 小时后该键视为未使用,会创建新记忆。 + +每次重放都会重新检查调用方当前的授权。服务端只保存键命名空间与内容的摘要,不保存原始键或记忆正文。服务端、Python SDK +和 MCP 工具都不会自动生成键或自动重试;`expected_revision` 保持原有行为。 + ## 当前状态与遗忘 `GET /v1/scopes/S/artifacts/atomic-memory/M/state` 返回当前精确 `artifact` 引用、`state`、 diff --git a/docs/zh/rfcs/1437_source_artifact_rest_api.md b/docs/zh/rfcs/1437_source_artifact_rest_api.md index ab1cb259db..0fa1a9410c 100644 --- a/docs/zh/rfcs/1437_source_artifact_rest_api.md +++ b/docs/zh/rfcs/1437_source_artifact_rest_api.md @@ -451,6 +451,11 @@ Path 中已经确定的身份字段不在 body 中重复接收。Create Source `content_digest` 只覆盖 canonical `content`,不覆盖身份或 lineage。Source 和 Artifact Create 每次成功都创建新 资源;客户端超时后应先根据业务上下文确认结果,不能假定重试幂等。 +通过 `remember_memory` 显式创建 Atomic Memory 不属于上述操作,是唯一带幂等键的 Atomic Memory 创建路径。 +[RFC 1809](1809-atomic-memory.md) 的“幂等的显式创建”一节定义其可选 request body 字段 `idempotency_key`、 +命名空间、请求摘要、重放和保留期。该字段不适用于 Source Create 或 Artifact Create,任何操作都不接受 +`Idempotency-Key` header;通过 Artifact Create 创建 Atomic Memory 仍然不幂等。 + ## 状态和错误模型 | 状态码 | 场景 | @@ -485,6 +490,9 @@ Path 中已经确定的身份字段不在 body 中重复接收。Create Source 错误不得泄漏其他 Scope 的资源是否存在;权限不足与资源不可见按统一安全策略返回 `403` 或 `404`。 +对 `remember_memory`,幂等键已绑定到不同请求时,返回 `409` 和现有错误码 `idempotency_conflict`,并将 +`details.kind` 设为 `memory_idempotency_key`;不为此新增错误码。 + ## OpenAPI contract `openapi/powercontext.yaml` 是 HTTP 契约唯一事实来源。主要 schema: diff --git a/docs/zh/rfcs/1809-atomic-memory.md b/docs/zh/rfcs/1809-atomic-memory.md index 7fd6dfddc2..e20a8b9727 100644 --- a/docs/zh/rfcs/1809-atomic-memory.md +++ b/docs/zh/rfcs/1809-atomic-memory.md @@ -163,6 +163,136 @@ RFC 1718 针对完整 manifest 设置的集合容量限制不适用于新 Family 执行恢复时,服务端在写入事务内检查当前正文版本、状态和合并关系。带预览标识时,还要检查是否符合预览; 不带标识时,按当前状态处理。检查结果须在提交时仍然成立,不能覆盖期间发生的更新。 +## 幂等的显式创建 + +`remember_memory` 是唯一接受幂等键的 Atomic Memory 创建入口,供丢失响应的调用方重试同一次显式创建, +而不会产生第二条记忆。不带键的请求保持原有行为:每次成功调用都创建一条新记忆。修订、遗忘、恢复、合并、 +抽取、Source 处理以及 RFC 1437 的通用 Artifact Create 都不接受幂等键。服务端不按内容去重,也不替调用方 +自动重试。 + +### 请求字段与命名空间 + +`RememberMemoryRequest` 新增可选字段 `idempotency_key`:1 到 256 个除空格外的可打印 ASCII 字符,即匹配 +`^[!-~]{1,256}$`。服务端逐字节比较,不去除首尾空白、不折叠大小写,也不做其他规范化。省略该字段或传 +`null` 表示不带键。不符合格式的键在任何查找或写入之前,按公共请求校验策略以 `422` 拒绝:错误码为 +`invalid_request`;若启用访问控制并由鉴权步骤先校验请求体,则为 `invalid_access_request`。 + +键在一个命名空间内唯一:操作 `remember_memory`、`scope_id`,以及已认证主体的类型和 ID。未启用访问控制时, +主体部分为空,同一部署的所有调用方在每个 Scope 内共用一个命名空间。同一个键用在其他 Scope、来自其他主体 +或用于其他操作时,表示相互独立的写入。HTTP API、Python SDK 和 MCP 工具原样传递该字段,都不生成键,也不 +自动重试。调用方为每次逻辑写入生成新的、不可猜测的键(例如 UUID),只在重试这次写入时复用。MCP 服务说明和共享 Skill +参考向模型给出同样的指引,并要求遇到冲突后改用新键。Dify 的 `pc_remember` 工具不暴露该字段。 + +服务端只保存命名空间与键的 SHA-256 摘要,不保存原始键或明文主体 ID。 + +### 请求摘要 + +请求摘要用写入产生的第 1 版正文标识一次逻辑写入。第 1 版摘要是一个 JSON 对象按 RFC 8785 序列化后的 +SHA-256,以小写十六进制表示。该对象恰好包含以下四个成员,与写入方将要保存的 `AtomicMemoryContent` 一致: + +- `schema` 为 `powercontext.atomic-memory.v1`。 +- `kind` 取提交值,不做改动,与写入方保存的值一致。 +- `text` 取写入方 `normalize_text` 的结果:先做 Unicode NFC,再去除首尾空白。 +- `description` 有提交值时取提交值;省略或为 `null` 时,取写入方根据规范化正文生成的默认描述。 + +对象不含 `creation` 成员,因为显式创建从不携带合并元数据。字符串按将要保存的形式参与计算:除 `text` 外不做 +Unicode 规范化,因此不得使用会规范化所有字符串的辅助函数计算该摘要。成员集合、`normalize_text` 或默认描述 +的行为发生任何变化,都必须使用新的摘要版本。 + +因此,省略 `description`、传 `null`、传与默认描述完全相同的值,会保存相同正文,得到同一个摘要。`reason` +不属于写入正文,不参与摘要。`expected_revision` 必须省略或为 `null`;非 `null` 值在查找前即被拒绝。 +`scope_id` 和主体属于命名空间,不进入摘要。 + +第 1 版写入的 Source 记录执行创建的那次请求的命令。正文只在规范化上有差异的重试会重放该次创建,不改写 +其 Source。每条键记录保存其摘要版本;新的摘要版本只用于新键,服务端在保留期内继续支持计算所有可能出现 +的版本。 + +### 结果 + +| 在键的命名空间中查找 | 结果 | +| --- | --- | +| 没有未过期记录 | 按不带键的方式创建记忆,并在同一事务中绑定该键。 | +| 记录的摘要相同 | 重放原始结果;不准备 Embedding,不写入任何数据。 | +| 记录的摘要不同 | 返回 `409 idempotency_conflict`,details 为 `{"kind": "memory_idempotency_key"}`;不写入任何数据。 | + +重放返回与原始创建相同的 `MemoryMutationResponse`:`changed: true`,以及一条记录,包含第 1 版的精确 +`ArtifactRef`、其 `kind` 和 `text`、`state: active`、创建时记录的状态版本,以及 `merged_into_id: null`。 +正文来自不可变的第 1 版,创建时状态来自键记录。目前每次创建都产生第 1 版、状态版本 0 且没有合并目标; +键记录仍保存版本号和状态版本,使重放不依赖这一不变量。之后的修订、遗忘、合并、恢复或退役都不改变重放结果,重放 +也绝不以当前 head 替代。调用方通过 Atomic Memory 的读取操作获取当前状态。 + +对带键的创建,原始响应同样通过精确版本读取构造,因此在创建与响应之间并发提交的修订不会改变任一结果。 +不带键的请求保持原有的响应构造方式。响应不带重放标记;需要区分重放的调用方,应将返回的身份与自身记录比较。 + +### 鉴权 + +`scope.contribute` 检查在查找键之前执行,与普通创建相同。被拒绝的调用方收到 `403`,无从得知键是否存在。 +主体属于命名空间,因此其他主体既不会命中,也无法探测某个键。 + +重放以调用方当前上下文,经由与 `atomic-memory` Family 的 Get Artifact Revision 相同的鉴权精确版本读取, +读取第 1 版。若调用方已不能读取该记忆(例如访问权已被撤销),请求返回该读取在公共安全策略下的错误:拒绝访问时 +为 `403 forbidden`,所有权尚未建立时为 `503 artifact_owner_pending`。只有找不到第 1 版时才返回 +`404 artifact_not_found`;第 1 版不可变且不会被物理删除,正常运行中不会出现这种情况。它既不泄露记录,也不创建新记忆;该键在过期前保持绑定。 + +冲突只表明调用方自己在该 Scope 中的键已用于不同内容。其他操作也会返回 `idempotency_conflict`,调用方通过 +`details.kind` 识别这种情况。 + +### 原子性与失败处理 + +请求校验、鉴权、写入方校验和摘要计算都在查找之前完成。查找是一次主键读取,在独立的读事务中执行,并使用 +数据库时钟。只有未命中时,才进入写事务之外原有的准备步骤,包括生成 Embedding。 + +写事务先删除同一命名空间的记录,但仅当其 `expires_at` 不晚于当前数据库时间,因此不会删除并发提交的有效键; +再插入键记录;随后照常写入 Source、第 1 版、治理状态、 +Owner 以及检索和证据投影,并一起提交。键记录包含命名空间摘要、请求摘要及其版本、`scope_id`、 +`artifact_id`、版本号、创建时状态版本、`created_at` 和 `expires_at`,不保存记忆正文。 + +- 校验、鉴权或准备失败,或在提交前取消,不留下键、Source、Artifact、Owner 或投影;用该键重试会重新执行创建。 +- 写事务内的失败会把键与其他数据一起回滚。 +- 提交后响应丢失(包括调用方无法观察结果的取消)时,键保持绑定;重试会重放已提交的结果。 +- 使用同一键的并发请求在键记录的主键上竞争。失败方回滚后,在新事务中重新读取该键,并按上表返回重放或冲突。 + 若重新读取未找到记录,说明完整性错误与键无关,原样返回该错误。失败方已准备的 Embedding 被丢弃。 + +唯一性由数据库约束而非进程内锁保证,因此在 SQLite 和 OceanBase/seekdb 上,跨连接、跨进程和跨 Server +实例均成立。 + +### 保留与清理 + +键自创建事务插入它时的数据库时间起保留 24 小时,重放不延长保留期。若记录的 `expires_at` 不晚于当前数据库 +时间,即视为不存在:同一个键将开始一次新的创建,并在该次创建的事务中替换过期记录。调用方不应期望 24 小时 +之后还能重放。 + +带键的创建提交后,服务端在独立的短事务中最多删除 32 条过期记录:先在 `expires_at` 索引上做一次上限为 32 的 +范围读取,再按主键删除并复核过期条件。清理失败不影响创建结果。每次带键创建新增一条记录、最多删除 32 条 +过期记录,因此只要带键写入持续发生,过期积压就会减少。不带键的请求不访问该表。所有操作都不扫描全表:查找 +和绑定使用主键,清理使用过期时间索引。 + +### 存储与升级 + +键记录保存在新表 `pc_atomic_memory_idempotency` 中,以命名空间摘要为主键,并在 `expires_at` 上建立二级 +索引。定长摘要使主键满足 MySQL 兼容数据库的索引长度限制。服务端资源迁移链新增一个版本创建该表,包含 +SQLite 和 MySQL 结构、manifest 资源以及 SQLite 指纹;已发布的版本不作修改。 + +Server 启动时,空的持久化 SQLite 或 seekdb 数据库会执行完整的版本链完成初始化,其中包括新版本。OceanBase +即使是空库,也需要显式运行 `powercontext server db-migrate` 作业。处于更早版本的托管数据库会使 Server 启动 +失败并报告需要迁移,直到 `powercontext server db-migrate apply` 成功;启动过程不会隐式升级。只有非托管存储 +(例如内存 SQLite)会根据内置表注册创建该表。重启或重复执行升级都保留已有记录。 + +### 验收 + +| 场景 | 预期结果 | +| --- | --- | +| 相同键和摘要 | 只有一个 Artifact 和 Source,启用访问控制时另有一个 Owner;每次响应都与第一次相同。 | +| 相同键、不同摘要 | `409 idempotency_conflict`;原记忆、Source、Owner 和投影不变。 | +| 不带键;同一键用于其他 Scope 或来自其他主体;不同的键 | 各自独立创建。 | +| `description` 省略、为 `null` 或等于默认值;正文只在 NFC 或首尾空白上不同 | 摘要相同;重放。 | +| 在不同连接或进程上并发请求 | 只创建一次;其他请求按摘要重放或冲突。 | +| 提交前失败或取消;提交后响应丢失 | 没有孤立行;重试只创建一次,或重放已提交结果。 | +| 重启后,再经历修订、遗忘、合并或退役 | 重放仍返回第 1 版及创建时状态。 | +| 访问权被撤销;其他主体 | 不泄露、不写入:返回精确读取的错误,或属于独立命名空间。 | +| 保留期边界与过期键复用 | 在 `expires_at` 时过期;复用会创建新记忆;每次带键写入借助索引最多清理 32 条记录。 | +| 全新数据库;升级后的托管数据库 | 真实 Server 启动和 `db-migrate` 成功;重复启动或升级保留记录。 | + ## 升级与兼容 现有部署按照 [RFC #1771](https://github.com/oceanbase/powercontext/pull/1771) 停服升级。数据库结构变更、 @@ -190,7 +320,7 @@ server 仅保留 `memory.get/list/search/remember/flush` 五个旧入口的适 - `get` 可用旧集合 ID 和 entry ID 定位对应 Atomic 的当前 head;精确历史读取改用新的 `ArtifactRef`。 - `list` 和 `search` 查询 Scope 中的 Atomic Memory,采用新模型的列表、状态和检索语义。 -- `remember` 仅适配简单新增,不保留旧条目更新、集合追加版本或旧对象依据。 +- `remember` 仅适配简单新增,不保留旧条目更新、集合追加版本或旧对象依据;可选接受幂等键,见“幂等的显式创建”。 - `flush` 使用保留的 Source 处理进度,继续向 Atomic Memory 抽取。 其他旧入口明确停止支持,包括通用 `family=memory` 操作、旧标签目标及其 ETag、旧 access selector、集合 @@ -214,6 +344,7 @@ SDK 和 runtime 不保留旧 Memory 域模型、`MemoryCitation` 或其他旧 Me - 按时间自动处理冲突可能采纳有误的新内容,时间缺失时尤其依赖 Source 顺序;纠正通过后续演化、编辑或恢复完成。 - 撤销合并后,结果记忆上的后续修订退出正常检索;已经引用这些版本的其他制品不会自动回滚。 - 旧客户端需要调整引用和调用方式;五个旧服务入口仍需适配,旧集合在线读取和追溯不再提供。 +- 幂等创建增加一张键表和固定 24 小时的保留期。过期后重试会创建第二条记忆,重放报告的是创建时状态而非当前状态。 # 设计理由与替代方案 @@ -233,6 +364,11 @@ SDK 和 runtime 不保留旧 Memory 域模型、`MemoryCitation` 或其他旧 Me **冲突按时间自动处理。** 原子记忆持续大量产生,把每次矛盾留给用户判断会积累维护工作。模型按时间更新当前 记忆,历史与恢复能力承担纠错需要,不建立独立的待处理冲突流程。 +**只在显式创建上提供幂等键。** `remember_memory` 的响应丢失时,调用方无法判断写入是否发生。按内容去重会 +合并调用方有意分开的写入;跨 Family 的幂等框架则需要为修订、合并和恢复定义重放,而它们的结果依赖当前状态。 +按保存正文计算摘要,可以把写入同一条记忆的请求视为同一请求。重放第 1 版及其创建时状态,使重试结果不受之后 +变更的影响;重放当前 head 则可能让重试返回调用方从未写入的内容。 + # 先例 - [RFC 1345](1345_scope_organization_and_agent_integration.md) 和 [1549](1549_artifact_family_unification.md) @@ -251,8 +387,8 @@ SDK 和 runtime 不保留旧 Memory 域模型、`MemoryCitation` 或其他旧 Me - 其他制品是否也采用这四种状态?现有 `deprecated` 状态如何对应“遗忘”和“被合并”?Atomic Memory 的行为 在本提案中明确,其他制品是否统一及如何改造另行讨论。 -本提案不包含 Atomic 正文历史的物理删除、跨 Scope 自动合并或整个 Scope 的快照回滚。具体表结构、接口参数、 -锁与事务实现放在实现方案中;迁移遵守 RFC #1771。 +本提案不包含 Atomic 正文历史的物理删除、跨 Scope 自动合并或整个 Scope 的快照回滚。除上文幂等创建协议外,具体表结构、 +接口参数、锁与事务实现放在实现方案中;迁移遵守 RFC #1771。 # 后续可能性 diff --git a/evaluation/memory/prepared_context_budget/reports/budget-v1/run-manifest.json b/evaluation/memory/prepared_context_budget/reports/budget-v1/run-manifest.json index 6d10818c89..3c00db1862 100644 --- a/evaluation/memory/prepared_context_budget/reports/budget-v1/run-manifest.json +++ b/evaluation/memory/prepared_context_budget/reports/budget-v1/run-manifest.json @@ -1,6 +1,6 @@ { "schema_version": "powercontext.prepared-context-budget-report.v1", - "generated_at": "2026-11-12T16:23:47+00:00", + "generated_at": "2026-11-15T09:38:24+00:00", "command": [ "run.py", "--manifest", @@ -12,17 +12,17 @@ "manifest_sha256": "f66d20fde6356dee53d63790dbb4f5936f8979e51f1f01ee10452cde80068078", "definitions_path": "evaluation/memory/prepared_context_budget/fixtures/budget-v1-definitions.md", "definitions_sha256": "1892d202e9d5d9bda732912991609ecf68224ee096b48bd7269fa746bd3aa5ec", - "git_head": "9c2bfdc3d147c4f62b677a2301ff7e0ac07d43bd", - "git_worktree_dirty": false, + "git_head": "3e8a2ae20680e639677b5f01a88cc5828282772b", + "git_worktree_dirty": true, "source_sha256": { - "src/powercontext/builtin/runtime/prepared_context.py": "e3d77ee5a841f57d9af78ee1df7ef7b33ea492d88c46d4b81666ed47355ca53b", - "src/powercontext/builtin/runtime/prepared_text.py": "00d4bd578ec06db729be77965a044a69a799786b7ab6ec3bd8e16e1653788ef7", - "evaluation/memory/prepared_context_budget/arms.py": "d0e3fd2bf17cc3385f026064f0eddd25c192fc6165809b6567f0488a215e720f", + "src/powercontext/builtin/runtime/prepared_context.py": "a9168fbf8dbf0951d3688aaffb0c2a68a93b5fde8067a7166654b7d0ee24fe67", + "src/powercontext/builtin/runtime/prepared_text.py": "b9247f2b8376c7176050a02b7c594375e976a36e01487489f01640d2a294de13", + "evaluation/memory/prepared_context_budget/arms.py": "c4f6f6745c29fade0f664c97789c8f4937f63157b6fe30c6cfb93d682cec917a", "evaluation/memory/prepared_context_budget/experiment.py": "edd5949143c7b44533750d74a15acd295ca79deec4a5a2006e10eb58a06e28c5", "evaluation/memory/prepared_context_budget/manifest.py": "5d8d51f350ba8dd06a9a253c92cca0d45c5e42e08d5c9279b9af61a2a7268812", "evaluation/memory/prepared_context_budget/report.py": "252697fbb23fc16372340e18d0fde6252168c4f2e45d1908ecac9b612f314a0d", "evaluation/memory/prepared_context_budget/run.py": "9253c5fdfcf0e522f16a0dd036517f89aeb44e06a53296cb35b98292b5d93f0b" }, - "python": "3.13.13", - "platform": "macOS-27.2-arm64-arm-64bit-Mach-O" + "python": "3.12.3", + "platform": "Linux-6.5.0-26-generic-x86_64-with-glibc2.39" } diff --git a/evaluation/skills/skill-up/evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md b/evaluation/skills/skill-up/evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md index a52335ed93..3d31dd2057 100644 --- a/evaluation/skills/skill-up/evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md +++ b/evaluation/skills/skill-up/evals/fixtures/repos/powercontext-tool-contract/CLAUDE.md @@ -273,7 +273,7 @@ not replace those schemas or enforce their constraints. It contains no scenario ## mcp__powercontext__remember_memory - Required: `kind: string`, `scope_id: string`, `text: string`. -- Optional: `description: string | null`, `expected_revision: integer | null`, `reason: string | null`. +- Optional: `description: string | null`, `expected_revision: integer | null`, `idempotency_key: string | null`, `reason: string | null`. ## mcp__powercontext__replace_artifact diff --git a/evaluation/skills/skill-up/skill-lock.json b/evaluation/skills/skill-up/skill-lock.json index 36b3790195..be5a8d9b37 100644 --- a/evaluation/skills/skill-up/skill-lock.json +++ b/evaluation/skills/skill-up/skill-lock.json @@ -1,7 +1,7 @@ { "schema_version": 1, "source_path": "integrations/agent-plugin/powercontext/skills/powercontext-project-context", - "source_commit": "b0fa97214790b18c358e62044ac520c9154c5778", + "source_commit": "99988da5c448500b565fb2d399be1620a418d0cb", "files": { "SKILL.md": "f2667491e0107eca6a3ef308e423b62781adf29697349610eadbef88da724198", "agents/openai.yaml": "2500c7e1d329158214626d203c70e7e9975f6ce7273be7fd4e758cbe4320bdbb", @@ -11,8 +11,8 @@ "references/host.md": "f16d33081061ebe49416afe986fee249b68f3cf9cce419e3fd370d8363f24561", "references/http-boundaries.md": "c012a88b6fb96f5a2e9cfbb6d39a8c9ce897451c4ff3d10f38c7471340ace7e7", "references/review-publication.md": "8f97c758e0877e38a542afaeb2c6ec33ae7a17fce86210efb6cd0e0e14148393", - "references/scope-memory.md": "0cd17b1b3f174bb05ac177a4bf5c8bbfd5200f72f1c1eb913d656a40432d89e1", + "references/scope-memory.md": "da4eb36cdffe8492e1aee54d5e8d779e4231cff97fca1c1674ef033734985736", "references/work-handoff.md": "d258bca1efc9330f1137690f75fb1e34f2a260e0bd277d41580077ce1886e595" }, - "content_sha256": "9103438af6242271735cb1abe2b72d6408a496dc8188592636598bba85353efb" + "content_sha256": "870b7076c60b3933ff41800537d3f24c8a7593573f3bf51bcf7d2a0c7103fbda" } diff --git a/evaluation/skills/skill-up/vendor/powercontext-project-context/references/scope-memory.md b/evaluation/skills/skill-up/vendor/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/evaluation/skills/skill-up/vendor/powercontext-project-context/references/scope-memory.md +++ b/evaluation/skills/skill-up/vendor/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/evaluation/zcode_guidance/skill-lock.json b/evaluation/zcode_guidance/skill-lock.json index 9f1a5d78d8..9e78deda3f 100644 --- a/evaluation/zcode_guidance/skill-lock.json +++ b/evaluation/zcode_guidance/skill-lock.json @@ -1,7 +1,7 @@ { "schema_version": 1, "source_path": "integrations/agent-plugin/powercontext/skills/powercontext-project-context", - "source_commit": "b0fa97214790b18c358e62044ac520c9154c5778", + "source_commit": "99988da5c448500b565fb2d399be1620a418d0cb", "files": { "SKILL.md": "f2667491e0107eca6a3ef308e423b62781adf29697349610eadbef88da724198", "agents/openai.yaml": "2500c7e1d329158214626d203c70e7e9975f6ce7273be7fd4e758cbe4320bdbb", @@ -11,7 +11,7 @@ "references/host.md": "f16d33081061ebe49416afe986fee249b68f3cf9cce419e3fd370d8363f24561", "references/http-boundaries.md": "c012a88b6fb96f5a2e9cfbb6d39a8c9ce897451c4ff3d10f38c7471340ace7e7", "references/review-publication.md": "8f97c758e0877e38a542afaeb2c6ec33ae7a17fce86210efb6cd0e0e14148393", - "references/scope-memory.md": "0cd17b1b3f174bb05ac177a4bf5c8bbfd5200f72f1c1eb913d656a40432d89e1", + "references/scope-memory.md": "da4eb36cdffe8492e1aee54d5e8d779e4231cff97fca1c1674ef033734985736", "references/work-handoff.md": "d258bca1efc9330f1137690f75fb1e34f2a260e0bd277d41580077ce1886e595" } } diff --git a/integrations/agent-plugin/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/agent-plugin/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/agent-plugin/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/agent-plugin/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/claude-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/codex/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/codex/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/codex/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/codex/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/dify/plugin/powercontext_dify/contract.json b/integrations/dify/plugin/powercontext_dify/contract.json index db3eb2969f..aecbff38b4 100644 --- a/integrations/dify/plugin/powercontext_dify/contract.json +++ b/integrations/dify/plugin/powercontext_dify/contract.json @@ -4238,6 +4238,20 @@ "type": "null" } ] + }, + "idempotency_key": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[!-~]{1,256}$", + "description": "Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key." + }, + { + "type": "null" + } + ] } } }, diff --git a/integrations/dify/plugin/powercontext_dify/policy.py b/integrations/dify/plugin/powercontext_dify/policy.py index 587383686d..16c6c35b25 100644 --- a/integrations/dify/plugin/powercontext_dify/policy.py +++ b/integrations/dify/plugin/powercontext_dify/policy.py @@ -19,6 +19,8 @@ "scope_id", "tag_filter", "expected_revision", + # A Dify tool call cannot carry one logical write's key across its retries. + "idempotency_key", "max_bytes", "include_code", "include_reuse", diff --git a/integrations/dify/tests/test_plugin_contract.py b/integrations/dify/tests/test_plugin_contract.py index 16a3c67230..8876d38958 100644 --- a/integrations/dify/tests/test_plugin_contract.py +++ b/integrations/dify/tests/test_plugin_contract.py @@ -231,6 +231,7 @@ def test_sdk_registers_exact_catalog_and_json_text_inputs(registry): "scope_id", "tag_filter", "expected_revision", + "idempotency_key", "max_bytes", "include_code", "assembly", @@ -256,6 +257,7 @@ def test_sdk_registers_exact_catalog_and_json_text_inputs(registry): ("pc_prepare_context", {"query": "scope"}, "bootstrap_receipt_id", "receipt-1"), ("pc_search", {"query": "scope"}, "tag_filter", {"tags": ["private"]}), ("pc_remember", {"kind": "decision", "text": "Retain."}, "expected_revision", 1), + ("pc_remember", {"kind": "decision", "text": "Retain."}, "idempotency_key", "retry-1"), ], ) def test_server_controlled_parameters_are_rejected_at_the_sdk_boundary( diff --git a/integrations/dsh/plugins/powercontext/lib/index.js b/integrations/dsh/plugins/powercontext/lib/index.js index 58432c8f86..2a845c56d5 100644 --- a/integrations/dsh/plugins/powercontext/lib/index.js +++ b/integrations/dsh/plugins/powercontext/lib/index.js @@ -2403,6 +2403,7 @@ const PUBLIC_ERROR_CODES = new Set([ "scope_idempotency_conflict", "scope_binding_target_missing", "artifact_publication_conflict", + "idempotency_conflict", "connector_checkpoint_conflict", "generation_conflict", "external_skill_snapshot_unavailable", diff --git a/integrations/dsh/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/dsh/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/dsh/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/dsh/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/dsh/plugins/powercontext/src/diagnostics.ts b/integrations/dsh/plugins/powercontext/src/diagnostics.ts index 575d57040c..7a363a5cf1 100644 --- a/integrations/dsh/plugins/powercontext/src/diagnostics.ts +++ b/integrations/dsh/plugins/powercontext/src/diagnostics.ts @@ -48,6 +48,9 @@ const PUBLIC_ERROR_CODES = new Set([ 'invalid_cursor', 'cursor_expired', 'precondition_required', 'capacity_exceeded', 'source_conflict', 'candidate_conflict', 'artifact_conflict', 'candidate_terminal', 'scope_version_conflict', 'scope_idempotency_conflict', 'scope_binding_target_missing', 'artifact_publication_conflict', + // remember_memory returns it when an idempotency_key is reused for different content; + // the caller recovers by choosing a new key, so it must reach the caller as itself. + 'idempotency_conflict', 'connector_checkpoint_conflict', 'generation_conflict', 'external_skill_snapshot_unavailable', 'handoff_report_inconsistent', 'invalid_request', 'invalid_scope_relationship', 'invalid_source_ingestion', 'invalid_lifecycle', 'artifact_publication_unsupported', diff --git a/integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts b/integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts index e0be684775..0da93eb841 100644 --- a/integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts +++ b/integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts @@ -107,6 +107,8 @@ describe('published error code filter', () => { expect(publicErrorCode('cursor_expired')).toBe('cursor_expired') expect(publicErrorCode('precondition_required')).toBe('precondition_required') expect(publicErrorCode('capacity_exceeded')).toBe('capacity_exceeded') + // A reused remember_memory idempotency_key with different content needs a new key. + expect(publicErrorCode('idempotency_conflict')).toBe('idempotency_conflict') }) it('drops a code that is not published, so internal codes cannot cross the boundary', () => { diff --git a/integrations/hermes/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/hermes/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/hermes/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/hermes/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/kimi-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/kimi-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/kimi-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/kimi-code/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/minimax/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/minimax/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/minimax/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/minimax/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/openclaw/plugins/memory-powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/openclaw/plugins/memory-powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/openclaw/plugins/memory-powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/openclaw/plugins/memory-powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/opencode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/opencode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/opencode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/opencode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/pi/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/pi/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/pi/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/pi/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/workbuddy/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/workbuddy/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/workbuddy/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/workbuddy/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/integrations/zcode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md b/integrations/zcode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md index 455612c733..bd025d7206 100644 --- a/integrations/zcode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md +++ b/integrations/zcode/plugins/powercontext/skills/powercontext-project-context/references/scope-memory.md @@ -23,6 +23,8 @@ For `remember I prefer uv for Python`, use `kind: "preference"` and `text: "The `remember_memory` returns `records` with independent ArtifactRefs. Omit `expected_revision` or pass null; legacy collection revision preconditions are unsupported. +To retry a save whose response was lost, resend the same content with the same `idempotency_key`; the original records are returned and no duplicate is created. Generate a fresh unguessable key, such as a UUID, for each new save, never derive it from the text, and reuse it only for that save's retries. `idempotency_conflict` means the key already names different content: use a new key. + For a requested correction, call `get_artifact`, inspect its `artifact`, and pass its exact `etag` as `replace_artifact`'s `If-Match`. These MCP tools return `{artifact, etag, status_code}`; a conditional 304 has `artifact: null`. Historical `get_artifact_revision` reads return plain Artifact JSON without a current-head ETag. For Atomic content, write `schema`, `kind`, and `text`; `creation` is system-owned merge metadata and must be omitted. Do not replace a stale precondition silently or create a duplicate to bypass it. After a conflict, reread and proceed only if the requested correction still applies. For a requested removal from normal search, read `get_atomic_memory_state` and call `change_atomic_memory_lifecycle` with the exact ArtifactRef and state_version. This forgets the memory and preserves recoverable history. Use restoration previews/restorations for an explicitly requested recovery; a merged memory can affect its whole merge chain. Legacy `revise_memory_entry` and `retire_memory_entry` are not current MCP operations. Automatic hooks attempt bounded context and Source capture; neither substitutes for an explicit Memory save. diff --git a/openapi/powercontext.yaml b/openapi/powercontext.yaml index 188957c6d5..243868a67a 100644 --- a/openapi/powercontext.yaml +++ b/openapi/powercontext.yaml @@ -2717,7 +2717,7 @@ paths: tags: [memory] summary: Create Atomic Memory through the legacy remember input description: >- - Create a standalone Atomic Memory and formal Owner. Omit expected_revision or pass null. Non-null legacy collection revision preconditions are unsupported before any write. Response records use true Atomic ArtifactRefs. + Create a standalone Atomic Memory and formal Owner. Omit expected_revision or pass null. Non-null legacy collection revision preconditions are unsupported before any write. Response records use true Atomic ArtifactRefs. With idempotency_key, a retry of the same creation within 24 hours replays the original response, and reuse of the key for different content returns 409 idempotency_conflict with details.kind memory_idempotency_key. operationId: remember_memory x-powercontext-feature-contracts: [memory.explicit] x-powercontext-access: {action: scope.contribute, resource: {type: scope, scope-id-from: scope_id}} @@ -13302,6 +13302,15 @@ components: a whitespace-collapsed text prefix of at most 200 Unicode characters, including a trailing ellipsis when truncated. Explicit writes do not invoke a generation model. nullable: true + idempotency_key: + type: string + minLength: 1 + maxLength: 256 + pattern: ^[!-~]{1,256}$ + description: Optional retry key, unique per operation, Scope and authenticated principal. Generate + a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are + compared byte for byte and retained for 24 hours. Omit it or pass null for no key. + nullable: true RetireMemoryEntryRequest: type: object additionalProperties: false diff --git a/release/upgrade-support.json b/release/upgrade-support.json index ed77c25d97..62328c7cb9 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.6.1", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "554be8de77a031cb36c4f576cff33fac9df19a6bbf0f5bcff02fd9700a2dbbc6", - "rationale": "Revision v1_5_0_006 follows v1_5_0_005 on both registered source chains and all vector/Code profiles. It adds pc_source_runners (name, display name, registering principal type and identifier, nullable registration ID unique per principal, registration time, reported capabilities and digest, nullable last_seen_at) and pc_source_collect_targets (Scope and target identity, runner, capability, target key unique per Scope, runner and capability, parameters, enabled, configuration version, update audit, and runner-written status columns, including whether the last attempt left more to collect), and drops pc_source_write_plugins. The source_collection domain step refuses the upgrade while pc_source_write_plugins lists a plugin, so no loaded write plugin is lost silently; otherwise no existing record is rewritten. Earlier revision resources, frozen checksums and SQLite fingerprints are unchanged; the MySQL layout for the new tables is registered from the same SQLAlchemy DDL. Target checkpoints reuse pc_connector_checkpoints keyed by (scope_id, target_id) with a constant connector version; a commit for a collection target is validated against the target's runner, enabled state and configuration version in the transaction that writes the checkpoint and status. Portable bundles add source_runner (name, display name, registering principal and registration ID) and source_collect_target records; reported capabilities, last-seen time and target status restart empty. Revision v1_5_0_005 follows v1_5_0_004 on both registered source chains and all vector/Code profiles. It removes the storage of the previous Artifact plugin framework (family schemas, declarative search and vector index tables, and the plugin registration columns of pc_artifact_processing_binding_states) and adds the nullable pc_artifacts.metadata column, which records the plugin name and code digest of plugin-written revisions and stays NULL for built-in families. Its domain preflight refuses the upgrade while the previous framework still holds any registration, declaration or index row, and native maintenance refuses registered native vector spaces, so no data is dropped silently. Its readiness accepts directory-loaded 'plugin:' Processing bindings without durable registration and keeps the frozen built-in full-text checks; plugin families write no rows to pc_artifact_fts. Revision reads omit metadata so domain steps at earlier registered revisions still run. Portable Artifact revision records advance to schema version 3 with metadata, and version 2 records restore with metadata NULL. Earlier revision resources, fingerprints and checksums remain unchanged; local SQLite migration tests do not establish native seekDB/OceanBase or installed-release acceptance. Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. Unpublished Server schema changes accumulate in a shared 000 revision and its registered resources. Release preparation freezes this draft as v__ after declaring the target version. Development databases are disposable; only supported released-version upgrades are promised. Revision descriptors parse this format while preserving historical release sequences, legacy aliases and opaque custom IDs. The sequence field is null for frozen release names and 000; the draft has no software_version. Historical sequence and PR-based names remain readable. Dependency order still follows down_revision. This naming support changes no registered schema, frozen resource, persisted revision, plan identity or checksum. Software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. Gateway authorization adds the Scope-level gateway.user role and gateway.invoke action to the existing binding vocabulary. It does not change stored binding structure or migration resources: existing records retain their role and do not implicitly gain gateway.invoke; new grants use the existing binding persistence and resource validation. Existing upgrade support remains upgrade-required and is not certified by this digest refresh. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources. SQLite Topic Memory full-text helper version 2 assigns each Scope's helper rows to a hashed 2^32-rowid range above every rowid that version 1 assigned, so Topic replacement and search bound their FTS5 cursors to one Scope's range. Virtual table definitions, registered schema fingerprints, migration resources and authoritative active Topic rows are unchanged. Unmanaged initialization and the existing s1400 domain step rebuild version-1 helper rows from the active tables with exact identities and revisions; a managed database that still holds version-1 helper rows keeps the previous identity filters until the helper is rebuilt. bm25 statistics remain table-wide, so search hits, ordering and scores are unchanged. The standalone seekdb maintenance identity is derived from @@server_uuid and DATABASE() when ob_compatibility_mode is missing, NULL, or empty and VERSION() contains -OceanBase seekdb-. The db-migrate identity probe and the server-run tenant gate share one compatibility classifier; ORACLE and non-seekdb servers remain rejected. This is an admission-only change and does not alter registered table layouts, migration resources, persisted row encodings, or public interfaces. Source writes and text retrieval reuse parameterized SQL structures with fresh Scope, identity, revision, binding and increment values on every execution. Only the fixed built-in Content manifest construction and exact validated payload bytes reuse cached metadata; database registration and indexed-identity checks remain current, and callers receive deep copies. MySQL/OceanBase journal allocation retains SELECT FOR UPDATE; SQLite retains its write reservation. Concurrent Content captures coalesce already queued requests into bounded transactions, isolate individual failures after batch rollback, replay stable identities on cancellation and drain admitted callers during shutdown. No schema, migration, stored encoding, Source identity, journal ordering, processing counter semantics or upgrade support claims change. A Topic Memory window attempt whose publication loses the Topic head CAS to a concurrent replace or Dream records last_error_code head_conflict on its existing pc_topic_memory_work_budgets row, and the attempt ceiling and the next attempt's counter treat that one attempt as not spent. Provider request and token charges stay committed and are never refunded. No table layout, column, constraint, migration resource, revision checksum or row encoding changes; existing rows never carry head_conflict, so their counters and blocks keep their meaning. A binary without this change counts such an attempt as spent, which can only stop that frontier sooner. The Dashboard processing page reads the existing Source journal and Artifact lineage relation and marks only Sources with an exact Artifact citation. It introduces no new table or public JSON interface and does not reconstruct execution history, delivery or adoption. Source journal envelopes record an optional UTC saved_at timestamp for newly inserted records. This adds write metadata inside the existing powercontext-source-v1 payload, without changing registered tables, schema revisions, frozen migration resources or checksums. Historical envelopes and raw legacy payloads remain readable with unknown save time; replay does not invent a timestamp, and handoff receipt upgrades preserve the original timestamp. Source identity, material digests, journal positions and processing intent identities remain unchanged. This compatibility review does not establish installed-release upgrade acceptance; the upgrade-required policy and complete automatic matrix remain unchanged. Relocating access control from the Server package to the built-in runtime, removing the unused Source-cursor discovery query, and moving the code command out of the built-in Code package are code-organization changes. They change neither registered table layout nor migration data encodings: the generated table and index DDL for every persistence and access table is identical on the SQLite and MySQL dialects. Native MySQL schema recognition now requires the absence of core tables and columns removed by registered transitions before accepting a recovery prefix or completed revision. Independent extension tables and columns remain supported. This executes the existing v1_5_0_005 cleanup without changing frozen resources, revision checksums, stored encodings or the required installed-release acceptance matrix. Request-serving plugin hosts reconstruct authorization without requiring a background service identity; scheduled workers retain the explicit identity requirement. This changes only process-local authorization configuration, with no schema, migration, persisted encoding or upgrade support changes. OceanBase vector SQL parameters and literals serialize finite float32 arrays with orjson while retaining pyobvector dimension validation, reference readback and special-value handling. Vector column types and stored float32 values are unchanged. Source evidence bindings are inserted as a batch in the accepting Source transaction with the same exact identities and immutable declarations. Current Atomic Memory verification reads projection pages and vector presence while preserving authoritative content, state, tag, profile, evidence and vector-dimension checks under the existing snapshot contract. These changes introduce no schema revisions, registered migration resource changes, historical rewrites or new installed-release upgrade claims. The OceanBase and seekdb profiles gain a helper that builds engines for another database of the same tenant or instance with the deployment's connection settings; plugin hosts and Workers use it to open each plugin's own database. It reads and writes no core table and changes no schema, migration, persisted encoding or upgrade support. Migration refusal diagnostics now state that retained legacy plugin records have no supported in-place upgrade path; unloading or exporting does not clear them. This wording correction changes no schema, rejection criteria or data transformation. Native managed-schema compatibility compares required columns, indexes and normalized CHECK definitions without deep-copying unrelated extension tables. Validation remains read-only and preserves required-schema admission, caller-owned metadata and all registered schema, data and migration formats. The recurrence ledger exposes read-only queries over existing pc_recurrence_observation rows: observations_for_target returns one bucket, and event_counts_for_target aggregates its three event counts in SQL. Both filter by the indexed revision columns and by the signature hash plus its plaintext. They add no table, column, index, migration, stored encoding or write path, and existing ledger rows, upgrade acceptance cases and policy mode are unchanged. Complete Atomic Memory related enumeration admits a memory when the distinct candidate terms it contains meet the lexical threshold of the candidate's distinct terms, or number at least the minimum match count and cover the coverage fraction of the memory's own indexed words, so a long candidate reaches a short memory of the same fact; window siblings use the same rule. The per-row requirement is computed from the existing searchable text in SQL on SQLite, seekDB and OceanBase, and the native OceanBase path adds one MATCH block that applies whole-word coverage only to memories short enough to qualify below the candidate threshold. This threshold change leaves search, recovery probes, stored projections, registered schema resources and migrations unchanged. Plugin reloading can unregister, in the Server process, the Artifact access profile a plugin family registered when that plugin is removed or renames its family; built-in family profiles are never removed, and no table layout, migration resource, frozen checksum or persisted encoding changes. Atomic Memory evidence capture batches committed revisions in the existing transaction while preserving immutable first-writer histories, per-revision Source ownership and projection encoding. Historical Source reads join material and immutable bindings and batch retained manifests by exact definition version; a damaged ancillary manifest neutralizes only its own identity. Complete related vector recall validates all eligible projections and computes distances in one statement, rejecting invalid projections even outside the distance threshold. SQLite FTS query selection and impossible FTS recovery-probe short-circuiting change read execution only. No table, migration resource, stored encoding, journal order or installed-release upgrade support claim changes. Related hybrid ranks observe lexical results and complete vector validation in one SQL statement; page bodies and current authority remain separately admitted. Each backend prepares and decodes its rank query at one boundary; hybrid ranks retain RRF fusion when no lexical query can be formed. Single and batched active projection publication share current-tag loading under the caller transaction. Historical manifests use the same tolerant batch decoder for one or many identities. These read-execution changes preserve table layouts, stored formats, migrations and upgrade claims. Related hybrid ranks preserve the per-row lexical coverage rule of current related recall, including native full-text query blocks. No migration revision or persisted encoding changes. The 000 draft creates the private prepare diagnostic store with nullable Unicode query text included in the initial table definition. Earlier published resources and existing domain data remain unchanged. The public prepare response, public body-free Receipts, reuse and operational telemetry remain unchanged; diagnostics retain same-execution query and candidate/final text outside Source and Bootstrap storage, and capture adds no expiry or cleanup action. Schema transitions are additive and do not establish native installed-release acceptance. SQLite model-usage accounting classifies expiry during native-connection setup as an unapplied attempt, allowing the recorder to retry within its existing total write budget. No usage statement has executed at that boundary; indeterminate-commit handling and production deadlines remain unchanged. This changes no registered schema, migration resource, revision checksum, persisted row encoding, journal format, or declared upgrade support. Atomic Memory legacy recovery reads express lexical and semantic channel predicates in separate EXISTS query blocks within one scalar SQL statement. Scope and metadata eligibility, per-channel admission thresholds, invalid-vector precedence, bound-vector types and the consistent statement boundary are preserved. This changes read-query planning only: registered table layouts, projection formats, stored row encodings, migration resources, revision checksums and journal formats are unchanged. No migration or projection rebuild is required. The upgrade-required policy, registered source versions and full installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. OceanBase Experience, Atomic Memory and Topic Memory FULLTEXT initialization share the existing Topic Memory policy for transient native error 1205 during index creation. Each recovery attempt rechecks index existence before repeating only the derived-index DDL; subsequent projection refresh and capability validation still execute. Persistent conflicts and other errors remain failures, cancellation propagates, and the helper does not explicitly commit or roll back the caller or replay business writes. Native DDL transaction semantics are unchanged. Index definitions, registered table layouts, projection versions, stored row encodings, frozen migration resources, revision checksums and journal formats are unchanged. No migration or data conversion is required. Vector index initialization, the upgrade-required policy, registered source versions and all installed-release acceptance profiles are unchanged; this compatibility review does not certify installed-release upgrades. SQLite profile-owned cursors close a failed native statement on the existing database worker before propagating the original SQL error. This prevents cyclic exception collection from blocking the event loop while the same connection's worker waits for another writer. Cancellation retains the existing interrupt and transaction-cleanup path; this change adds no statement replay, retry, commit, rollback or lock-wait extension. Registered table layouts, stored row encodings, projection formats, migration resources, revision checksums and journal formats are unchanged. No migration or data conversion is required. The upgrade-required policy, source registrations and full installed-release acceptance matrix remain unchanged; this compatibility review does not certify installed-release upgrades. Release 1.6.0 freezes the cumulative 000 prepare-diagnostics migration as v1_6_0 after v1_5_0_006. Owned resource names, registrations and the persistence digest are synchronized; published revision identities and checksums remain unchanged. No historical query text is backfilled. This freeze preserves the upgrade-required policy and all twelve selected installed-release acceptance profiles; it does not itself certify upgrades. The Source collection revision introduced by PR #2639 after the 1.5.2 release is named v1_5_0_006 before publication. All 47 migration scripts and schema resources shipped in 1.5.2 remain byte-identical. The baseline validator is unchanged and rejects this rename against a base containing the former identity; this known CI failure is retained. Development databases and recovery plans using the former identity must be rebuilt; no runtime alias or installed-release upgrade certification is introduced. The Dashboard Topic Memory processing-status projection reads existing Scope-bound Source cursors, journal heads, targets, work budgets and retained block diagnostics without writing or repairing records or starting processing. It changes no table layout, persisted encoding, migration resource, frozen revision checksum or historical record. The upgrade-required policy and installed-release acceptance matrix remain unchanged; this review does not establish installed-release upgrade acceptance. PR #2728 adds a read-only `metadata` response projection to Content Sources; it changes no table, payload encoding, migration or stored format, so the recorded migration chain and persistence compatibility are unchanged. A manual Topic Memory replace links only the previous exact revision in Artifact lineage instead of copying the current revision's inherited references; existing lineage rows are left as stored, and no table, migration resource, stored encoding or upgrade support claim changes. Built-in Experience FTS search now passes its projection-level lexical admission decision to the decoder after verifying SQLite FTS-to-head projection equality and exact single-term coverage on OceanBase, and RecurrenceRepository adds the read-only verdicts_for_target query over existing pc_recurrence_observation rows using the existing revision index, signature hash and plaintext filters plus event != 'selected'; these read-only query changes alter no table layout, column, index, migration resource, frozen checksum, stored encoding or upgrade support declaration. PR #2745 adds deployment limit constants to `powercontext.limits` and a read-only discovery endpoint; it changes no table, payload encoding, migration or stored format, so the recorded migration chain and persistence compatibility are unchanged. Server startup adds best-effort, read-only guidance for widening an existing SQLite Processing capability declaration without changing its mode or bindings; incompatible configurations remain refused until the explicit offline Processing switch completes. Content Source writes enforce the configured character limit, with a 200,000-character default and a 1,000,000-character setting ceiling within the existing payload storage capacity. Neither change alters table layouts, migration resources, frozen checksums, stored encodings or the installed-release acceptance requirements. PR #2816 makes the per-Artifact and per-query tag limits configurable; it adds admission policy fields to the built-in runtime, widens the candidate response contract to the same ceiling, rejects over-limit proposals and revisions before they are stored, applies the query limit to embedded and plugin listings while preserving page sizes, and validates at the HTTP, plugin, Dream approval, merge and embedded-query boundaries without changing any table, payload encoding, migration or stored format. Historical Atomic Memory alias recall and its unpublished 000 projection are removed. The managed target returns to v1_6_0 on both registered source chains, with all published revision resources unchanged. Reconciliation and projection rebuilding use active memories only; authoritative merged records and lifecycle history remain unchanged. Development databases and maintenance plans created with the removed unpublished 000 must be rebuilt; this change provides no in-place downgrade or destructive cleanup of deployed databases. Installed-release acceptance requirements remain unchanged." + "persistence_sha256": "9e381ace9cde240d771237a758813a30e89f4305d2185b945c4d9bf0185bb550", + "rationale": "Revision v1_5_0_006 follows v1_5_0_005 on both registered source chains and all vector/Code profiles. It adds pc_source_runners (name, display name, registering principal type and identifier, nullable registration ID unique per principal, registration time, reported capabilities and digest, nullable last_seen_at) and pc_source_collect_targets (Scope and target identity, runner, capability, target key unique per Scope, runner and capability, parameters, enabled, configuration version, update audit, and runner-written status columns, including whether the last attempt left more to collect), and drops pc_source_write_plugins. The source_collection domain step refuses the upgrade while pc_source_write_plugins lists a plugin, so no loaded write plugin is lost silently; otherwise no existing record is rewritten. Earlier revision resources, frozen checksums and SQLite fingerprints are unchanged; the MySQL layout for the new tables is registered from the same SQLAlchemy DDL. Target checkpoints reuse pc_connector_checkpoints keyed by (scope_id, target_id) with a constant connector version; a commit for a collection target is validated against the target's runner, enabled state and configuration version in the transaction that writes the checkpoint and status. Portable bundles add source_runner (name, display name, registering principal and registration ID) and source_collect_target records; reported capabilities, last-seen time and target status restart empty. Revision v1_5_0_005 follows v1_5_0_004 on both registered source chains and all vector/Code profiles. It removes the storage of the previous Artifact plugin framework (family schemas, declarative search and vector index tables, and the plugin registration columns of pc_artifact_processing_binding_states) and adds the nullable pc_artifacts.metadata column, which records the plugin name and code digest of plugin-written revisions and stays NULL for built-in families. Its domain preflight refuses the upgrade while the previous framework still holds any registration, declaration or index row, and native maintenance refuses registered native vector spaces, so no data is dropped silently. Its readiness accepts directory-loaded 'plugin:' Processing bindings without durable registration and keeps the frozen built-in full-text checks; plugin families write no rows to pc_artifact_fts. Revision reads omit metadata so domain steps at earlier registered revisions still run. Portable Artifact revision records advance to schema version 3 with metadata, and version 2 records restore with metadata NULL. Earlier revision resources, fingerprints and checksums remain unchanged; local SQLite migration tests do not establish native seekDB/OceanBase or installed-release acceptance. Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. Unpublished Server schema changes accumulate in a shared 000 revision and its registered resources. Release preparation freezes this draft as v__ after declaring the target version. Development databases are disposable; only supported released-version upgrades are promised. Revision descriptors parse this format while preserving historical release sequences, legacy aliases and opaque custom IDs. The sequence field is null for frozen release names and 000; the draft has no software_version. Historical sequence and PR-based names remain readable. Dependency order still follows down_revision. This naming support changes no registered schema, frozen resource, persisted revision, plan identity or checksum. Software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. Gateway authorization adds the Scope-level gateway.user role and gateway.invoke action to the existing binding vocabulary. It does not change stored binding structure or migration resources: existing records retain their role and do not implicitly gain gateway.invoke; new grants use the existing binding persistence and resource validation. Existing upgrade support remains upgrade-required and is not certified by this digest refresh. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources. SQLite Topic Memory full-text helper version 2 assigns each Scope's helper rows to a hashed 2^32-rowid range above every rowid that version 1 assigned, so Topic replacement and search bound their FTS5 cursors to one Scope's range. Virtual table definitions, registered schema fingerprints, migration resources and authoritative active Topic rows are unchanged. Unmanaged initialization and the existing s1400 domain step rebuild version-1 helper rows from the active tables with exact identities and revisions; a managed database that still holds version-1 helper rows keeps the previous identity filters until the helper is rebuilt. bm25 statistics remain table-wide, so search hits, ordering and scores are unchanged. The standalone seekdb maintenance identity is derived from @@server_uuid and DATABASE() when ob_compatibility_mode is missing, NULL, or empty and VERSION() contains -OceanBase seekdb-. The db-migrate identity probe and the server-run tenant gate share one compatibility classifier; ORACLE and non-seekdb servers remain rejected. This is an admission-only change and does not alter registered table layouts, migration resources, persisted row encodings, or public interfaces. Source writes and text retrieval reuse parameterized SQL structures with fresh Scope, identity, revision, binding and increment values on every execution. Only the fixed built-in Content manifest construction and exact validated payload bytes reuse cached metadata; database registration and indexed-identity checks remain current, and callers receive deep copies. MySQL/OceanBase journal allocation retains SELECT FOR UPDATE; SQLite retains its write reservation. Concurrent Content captures coalesce already queued requests into bounded transactions, isolate individual failures after batch rollback, replay stable identities on cancellation and drain admitted callers during shutdown. No schema, migration, stored encoding, Source identity, journal ordering, processing counter semantics or upgrade support claims change. A Topic Memory window attempt whose publication loses the Topic head CAS to a concurrent replace or Dream records last_error_code head_conflict on its existing pc_topic_memory_work_budgets row, and the attempt ceiling and the next attempt's counter treat that one attempt as not spent. Provider request and token charges stay committed and are never refunded. No table layout, column, constraint, migration resource, revision checksum or row encoding changes; existing rows never carry head_conflict, so their counters and blocks keep their meaning. A binary without this change counts such an attempt as spent, which can only stop that frontier sooner. The Dashboard processing page reads the existing Source journal and Artifact lineage relation and marks only Sources with an exact Artifact citation. It introduces no new table or public JSON interface and does not reconstruct execution history, delivery or adoption. Source journal envelopes record an optional UTC saved_at timestamp for newly inserted records. This adds write metadata inside the existing powercontext-source-v1 payload, without changing registered tables, schema revisions, frozen migration resources or checksums. Historical envelopes and raw legacy payloads remain readable with unknown save time; replay does not invent a timestamp, and handoff receipt upgrades preserve the original timestamp. Source identity, material digests, journal positions and processing intent identities remain unchanged. This compatibility review does not establish installed-release upgrade acceptance; the upgrade-required policy and complete automatic matrix remain unchanged. Relocating access control from the Server package to the built-in runtime, removing the unused Source-cursor discovery query, and moving the code command out of the built-in Code package are code-organization changes. They change neither registered table layout nor migration data encodings: the generated table and index DDL for every persistence and access table is identical on the SQLite and MySQL dialects. Native MySQL schema recognition now requires the absence of core tables and columns removed by registered transitions before accepting a recovery prefix or completed revision. Independent extension tables and columns remain supported. This executes the existing v1_5_0_005 cleanup without changing frozen resources, revision checksums, stored encodings or the required installed-release acceptance matrix. Request-serving plugin hosts reconstruct authorization without requiring a background service identity; scheduled workers retain the explicit identity requirement. This changes only process-local authorization configuration, with no schema, migration, persisted encoding or upgrade support changes. OceanBase vector SQL parameters and literals serialize finite float32 arrays with orjson while retaining pyobvector dimension validation, reference readback and special-value handling. Vector column types and stored float32 values are unchanged. Source evidence bindings are inserted as a batch in the accepting Source transaction with the same exact identities and immutable declarations. Current Atomic Memory verification reads projection pages and vector presence while preserving authoritative content, state, tag, profile, evidence and vector-dimension checks under the existing snapshot contract. These changes introduce no schema revisions, registered migration resource changes, historical rewrites or new installed-release upgrade claims. The OceanBase and seekdb profiles gain a helper that builds engines for another database of the same tenant or instance with the deployment's connection settings; plugin hosts and Workers use it to open each plugin's own database. It reads and writes no core table and changes no schema, migration, persisted encoding or upgrade support. Migration refusal diagnostics now state that retained legacy plugin records have no supported in-place upgrade path; unloading or exporting does not clear them. This wording correction changes no schema, rejection criteria or data transformation. Native managed-schema compatibility compares required columns, indexes and normalized CHECK definitions without deep-copying unrelated extension tables. Validation remains read-only and preserves required-schema admission, caller-owned metadata and all registered schema, data and migration formats. The recurrence ledger exposes read-only queries over existing pc_recurrence_observation rows: observations_for_target returns one bucket, and event_counts_for_target aggregates its three event counts in SQL. Both filter by the indexed revision columns and by the signature hash plus its plaintext. They add no table, column, index, migration, stored encoding or write path, and existing ledger rows, upgrade acceptance cases and policy mode are unchanged. Complete Atomic Memory related enumeration admits a memory when the distinct candidate terms it contains meet the lexical threshold of the candidate's distinct terms, or number at least the minimum match count and cover the coverage fraction of the memory's own indexed words, so a long candidate reaches a short memory of the same fact; window siblings use the same rule. The per-row requirement is computed from the existing searchable text in SQL on SQLite, seekDB and OceanBase, and the native OceanBase path adds one MATCH block that applies whole-word coverage only to memories short enough to qualify below the candidate threshold. This threshold change leaves search, recovery probes, stored projections, registered schema resources and migrations unchanged. Plugin reloading can unregister, in the Server process, the Artifact access profile a plugin family registered when that plugin is removed or renames its family; built-in family profiles are never removed, and no table layout, migration resource, frozen checksum or persisted encoding changes. Atomic Memory evidence capture batches committed revisions in the existing transaction while preserving immutable first-writer histories, per-revision Source ownership and projection encoding. Historical Source reads join material and immutable bindings and batch retained manifests by exact definition version; a damaged ancillary manifest neutralizes only its own identity. Complete related vector recall validates all eligible projections and computes distances in one statement, rejecting invalid projections even outside the distance threshold. SQLite FTS query selection and impossible FTS recovery-probe short-circuiting change read execution only. No table, migration resource, stored encoding, journal order or installed-release upgrade support claim changes. Related hybrid ranks observe lexical results and complete vector validation in one SQL statement; page bodies and current authority remain separately admitted. Each backend prepares and decodes its rank query at one boundary; hybrid ranks retain RRF fusion when no lexical query can be formed. Single and batched active projection publication share current-tag loading under the caller transaction. Historical manifests use the same tolerant batch decoder for one or many identities. These read-execution changes preserve table layouts, stored formats, migrations and upgrade claims. Related hybrid ranks preserve the per-row lexical coverage rule of current related recall, including native full-text query blocks. No migration revision or persisted encoding changes. The 000 draft creates the private prepare diagnostic store with nullable Unicode query text included in the initial table definition. Earlier published resources and existing domain data remain unchanged. The public prepare response, public body-free Receipts, reuse and operational telemetry remain unchanged; diagnostics retain same-execution query and candidate/final text outside Source and Bootstrap storage, and capture adds no expiry or cleanup action. Schema transitions are additive and do not establish native installed-release acceptance. SQLite model-usage accounting classifies expiry during native-connection setup as an unapplied attempt, allowing the recorder to retry within its existing total write budget. No usage statement has executed at that boundary; indeterminate-commit handling and production deadlines remain unchanged. This changes no registered schema, migration resource, revision checksum, persisted row encoding, journal format, or declared upgrade support. Atomic Memory legacy recovery reads express lexical and semantic channel predicates in separate EXISTS query blocks within one scalar SQL statement. Scope and metadata eligibility, per-channel admission thresholds, invalid-vector precedence, bound-vector types and the consistent statement boundary are preserved. This changes read-query planning only: registered table layouts, projection formats, stored row encodings, migration resources, revision checksums and journal formats are unchanged. No migration or projection rebuild is required. The upgrade-required policy, registered source versions and full installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. OceanBase Experience, Atomic Memory and Topic Memory FULLTEXT initialization share the existing Topic Memory policy for transient native error 1205 during index creation. Each recovery attempt rechecks index existence before repeating only the derived-index DDL; subsequent projection refresh and capability validation still execute. Persistent conflicts and other errors remain failures, cancellation propagates, and the helper does not explicitly commit or roll back the caller or replay business writes. Native DDL transaction semantics are unchanged. Index definitions, registered table layouts, projection versions, stored row encodings, frozen migration resources, revision checksums and journal formats are unchanged. No migration or data conversion is required. Vector index initialization, the upgrade-required policy, registered source versions and all installed-release acceptance profiles are unchanged; this compatibility review does not certify installed-release upgrades. SQLite profile-owned cursors close a failed native statement on the existing database worker before propagating the original SQL error. This prevents cyclic exception collection from blocking the event loop while the same connection's worker waits for another writer. Cancellation retains the existing interrupt and transaction-cleanup path; this change adds no statement replay, retry, commit, rollback or lock-wait extension. Registered table layouts, stored row encodings, projection formats, migration resources, revision checksums and journal formats are unchanged. No migration or data conversion is required. The upgrade-required policy, source registrations and full installed-release acceptance matrix remain unchanged; this compatibility review does not certify installed-release upgrades. Release 1.6.0 freezes the cumulative 000 prepare-diagnostics migration as v1_6_0 after v1_5_0_006. Owned resource names, registrations and the persistence digest are synchronized; published revision identities and checksums remain unchanged. No historical query text is backfilled. This freeze preserves the upgrade-required policy and all twelve selected installed-release acceptance profiles; it does not itself certify upgrades. The Source collection revision introduced by PR #2639 after the 1.5.2 release is named v1_5_0_006 before publication. All 47 migration scripts and schema resources shipped in 1.5.2 remain byte-identical. The baseline validator is unchanged and rejects this rename against a base containing the former identity; this known CI failure is retained. Development databases and recovery plans using the former identity must be rebuilt; no runtime alias or installed-release upgrade certification is introduced. The Dashboard Topic Memory processing-status projection reads existing Scope-bound Source cursors, journal heads, targets, work budgets and retained block diagnostics without writing or repairing records or starting processing. It changes no table layout, persisted encoding, migration resource, frozen revision checksum or historical record. The upgrade-required policy and installed-release acceptance matrix remain unchanged; this review does not establish installed-release upgrade acceptance. PR #2728 adds a read-only `metadata` response projection to Content Sources; it changes no table, payload encoding, migration or stored format, so the recorded migration chain and persistence compatibility are unchanged. A manual Topic Memory replace links only the previous exact revision in Artifact lineage instead of copying the current revision's inherited references; existing lineage rows are left as stored, and no table, migration resource, stored encoding or upgrade support claim changes. Built-in Experience FTS search now passes its projection-level lexical admission decision to the decoder after verifying SQLite FTS-to-head projection equality and exact single-term coverage on OceanBase, and RecurrenceRepository adds the read-only verdicts_for_target query over existing pc_recurrence_observation rows using the existing revision index, signature hash and plaintext filters plus event != 'selected'; these read-only query changes alter no table layout, column, index, migration resource, frozen checksum, stored encoding or upgrade support declaration. PR #2745 adds deployment limit constants to `powercontext.limits` and a read-only discovery endpoint; it changes no table, payload encoding, migration or stored format, so the recorded migration chain and persistence compatibility are unchanged. Server startup adds best-effort, read-only guidance for widening an existing SQLite Processing capability declaration without changing its mode or bindings; incompatible configurations remain refused until the explicit offline Processing switch completes. Content Source writes enforce the configured character limit, with a 200,000-character default and a 1,000,000-character setting ceiling within the existing payload storage capacity. Neither change alters table layouts, migration resources, frozen checksums, stored encodings or the installed-release acceptance requirements. PR #2816 makes the per-Artifact and per-query tag limits configurable; it adds admission policy fields to the built-in runtime, widens the candidate response contract to the same ceiling, rejects over-limit proposals and revisions before they are stored, applies the query limit to embedded and plugin listings while preserving page sizes, and validates at the HTTP, plugin, Dream approval, merge and embedded-query boundaries without changing any table, payload encoding, migration or stored format. Historical Atomic Memory alias recall and its unpublished 000 projection are removed. The last frozen revision is v1_6_0 on both registered source chains, with all published revision resources unchanged. Reconciliation and projection rebuilding use active memories only; authoritative merged records and lifecycle history remain unchanged. Development databases and maintenance plans created with the removed unpublished 000 must be rebuilt; this change provides no in-place downgrade or destructive cleanup of deployed databases. Installed-release acceptance requirements remain unchanged. Draft 000 appends pc_atomic_memory_idempotency after the frozen v1_6_0 revision on both registered source paths. It creates an empty receipt table and an expiry index without rewriting existing data. Keyed Memory creation commits the receipt in the same transaction as the Memory. Existing revision resources and checksums stay intact, and the upgrade-required acceptance matrix continues to apply. Development databases stamped with the earlier incarnation of 000 require rebuilding before using this draft." }, "cases": [], "automatic_sources": { diff --git a/src/powercontext/builtin/artifacts/atomic_memory/service.py b/src/powercontext/builtin/artifacts/atomic_memory/service.py index 82a52444a3..7b1dca1e4e 100644 --- a/src/powercontext/builtin/artifacts/atomic_memory/service.py +++ b/src/powercontext/builtin/artifacts/atomic_memory/service.py @@ -518,6 +518,13 @@ async def inspect_change( ) ) + async def authorize_creates( + self, connection: AsyncConnection, scope_id: str, artifact_ids: Sequence[str], context: Any + ) -> None: + """Require the caller's current creation authority without inspecting any content.""" + refs = tuple(ArtifactRef(family="atomic-memory", artifact_id=value, revision=1) for value in artifact_ids) + await self.shared.security.authorize_creates(connection, scope_id, context, refs) + async def inspect_creates( self, connection: AsyncConnection, diff --git a/src/powercontext/builtin/persistence/atomic_memory_idempotency.py b/src/powercontext/builtin/persistence/atomic_memory_idempotency.py new file mode 100644 index 0000000000..3b7d9cc50e --- /dev/null +++ b/src/powercontext/builtin/persistence/atomic_memory_idempotency.py @@ -0,0 +1,197 @@ +# 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. + +"""Retry receipts for keyed ``remember_memory`` creations. + +A receipt binds one namespace (operation, Scope, principal and caller key) to the +digest of the revision 1 content its creation stored. Only SHA-256 digests are +persisted: never the raw key, the principal ID, or the memory body. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from datetime import timedelta +from hashlib import sha256 + +import rfc8785 +from sqlalchemy import delete, insert, select +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.artifacts.atomic_memory.models import AtomicMemoryContent +from powercontext.builtin.artifacts.atomic_memory.summary import default_description +from powercontext.builtin.artifacts.memory.canonical import canonical_error_code, normalize_text +from powercontext.builtin.artifacts.memory.errors import InvalidMemoryCandidateError +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.supervision import database_utc_now +from powercontext.builtin.persistence.tables import ATOMIC_MEMORY_IDEMPOTENCY_TABLE as TABLE + +KEY_PATTERN = re.compile(r"[!-~]{1,256}") +RETENTION = timedelta(hours=24) +CLEANUP_BATCH = 32 +DIGEST_VERSION = 1 +OPERATION = "remember_memory" + + +@dataclass(frozen=True, slots=True) +class MemoryIdempotencyKey: + """One keyed request: its namespace and the content it would store.""" + + namespace_digest: str + content: AtomicMemoryContent + + +@dataclass(frozen=True, slots=True) +class MemoryIdempotencyReceipt: + """The creation a key is bound to, with the state recorded at creation.""" + + artifact_id: str + revision: int + state_version: int + + +@dataclass(frozen=True, slots=True) +class _StoredReceipt: + digest_version: int + request_digest: str + receipt: MemoryIdempotencyReceipt + live: bool + + +def namespace_digest(scope_id: str, principal: tuple[str, str] | None, key: str) -> str: + """Digest the key's namespace; an absent principal shares one namespace per Scope.""" + + principal_type, principal_id = principal if principal is not None else ("", "") + return sha256(rfc8785.dumps([OPERATION, scope_id, principal_type, principal_id, key])).hexdigest() + + +def request_digest(content: AtomicMemoryContent, version: int = DIGEST_VERSION) -> str | None: + """Digest the revision 1 content the Atomic writer stores for this request. + + Only ``text`` is normalized, exactly as the writer normalizes it; other strings are + hashed as submitted. Returns ``None`` for a version this binary cannot compute. + """ + + if version != 1: + return None + try: + text = normalize_text(content.text) + except (TypeError, ValueError) as error: + raise InvalidMemoryCandidateError( + "canonical", str(error), canonical_code=canonical_error_code(error) + ) from error + return sha256( + rfc8785.dumps({ + "schema": content.schema_, + "kind": content.kind, + "text": text, + "description": content.description if content.description is not None else default_description(text), + }) + ).hexdigest() + + +class MemoryIdempotencyConflict(Exception): + """The key is bound to a creation of different content.""" + + +async def find_receipt(database: AsyncDatabase, key: MemoryIdempotencyKey) -> _StoredReceipt | None: + """Read the key's record, live or expired, in its own read transaction.""" + + async with database.transaction() as connection: + now = await database_utc_now(connection) + row = ( + await connection.execute( + select( + TABLE.c.digest_version, + TABLE.c.request_digest, + TABLE.c.artifact_id, + TABLE.c.revision, + TABLE.c.state_version, + TABLE.c.expires_at, + ).where(TABLE.c.namespace_digest == key.namespace_digest) + ) + ).one_or_none() + if row is None: + return None + return _StoredReceipt( + digest_version=int(row.digest_version), + request_digest=str(row.request_digest), + receipt=MemoryIdempotencyReceipt( + artifact_id=str(row.artifact_id), revision=int(row.revision), state_version=int(row.state_version) + ), + live=row.expires_at > now, + ) + + +def replay(stored: _StoredReceipt, key: MemoryIdempotencyKey) -> MemoryIdempotencyReceipt: + """Return the bound creation for the same content, or raise a conflict.""" + + if request_digest(key.content, stored.digest_version) != stored.request_digest: + raise MemoryIdempotencyConflict + return stored.receipt + + +async def bind_receipt( + connection: AsyncConnection, + key: MemoryIdempotencyKey, + scope_id: str, + receipt: MemoryIdempotencyReceipt, + *, + replace_expired: bool, +) -> None: + """Claim the key inside the creating transaction. + + An expired record is removed only when the lookup saw one, and only while it is still + expired, so a live key committed concurrently is never removed. A concurrent claim of + the same key fails on the primary key. + """ + + now = await database_utc_now(connection) + if replace_expired: + await connection.execute( + delete(TABLE).where(TABLE.c.namespace_digest == key.namespace_digest, TABLE.c.expires_at <= now) + ) + await connection.execute( + insert(TABLE).values( + namespace_digest=key.namespace_digest, + digest_version=DIGEST_VERSION, + request_digest=request_digest(key.content), + scope_id=scope_id, + artifact_id=receipt.artifact_id, + revision=receipt.revision, + state_version=receipt.state_version, + created_at=now, + expires_at=now + RETENTION, + ) + ) + + +async def remove_expired_receipts(database: AsyncDatabase) -> None: + """Delete at most one bounded batch of expired records through the expiry index.""" + + async with database.transaction() as connection: + now = await database_utc_now(connection) + expired = ( + await connection.scalars( + select(TABLE.c.namespace_digest) + .where(TABLE.c.expires_at <= now) + .order_by(TABLE.c.expires_at) + .limit(CLEANUP_BATCH) + ) + ).all() + if expired: + await connection.execute( + delete(TABLE).where(TABLE.c.namespace_digest.in_(expired), TABLE.c.expires_at <= now) + ) diff --git a/src/powercontext/builtin/persistence/family_management.py b/src/powercontext/builtin/persistence/family_management.py index 86c2665842..a5fc786c1a 100644 --- a/src/powercontext/builtin/persistence/family_management.py +++ b/src/powercontext/builtin/persistence/family_management.py @@ -547,6 +547,22 @@ async def prepare_creates( scope_id, tuple((artifact_id, content, None) for artifact_id, content in items), execution_context ) + async def authorize_creates(self, scope_id: str, artifact_ids: Sequence[str], *, execution_context=None) -> None: + """Check creation authority alone, for callers that may answer without preparing a write. + + Only an absent context skips the check; the domain policy decides trusted local and + untrusted contexts exactly as it does for an ordinary creation. + """ + from powercontext.builtin.runtime.atomic_memory import deferred_decision_audit + + if execution_context is None: + return + async with ( + deferred_decision_audit(execution_context), + self.application.database.transaction() as connection, + ): + await self.application.service.authorize_creates(connection, scope_id, artifact_ids, execution_context) + async def _prepare_commands(self, scope_id, items, context) -> tuple[AtomicMemoryManagementPrepared, ...]: """Inspect one write window, then prepare its projections outside the transaction.""" from powercontext.builtin.artifacts.atomic_memory.models import AtomicMemoryContent diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json b/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json index 319f4fa383..86cbad5121 100644 --- a/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json +++ b/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json @@ -60,6 +60,10 @@ "v1_6_0": [ "schemas/sqlite-v1_6_0.json", "schemas/mysql-v1_6_0.json" + ], + "000": [ + "schemas/sqlite-000.json", + "schemas/mysql-000.json" ] }, "sqlite_baselines": { @@ -107,6 +111,9 @@ ], "v1_6_0": [ "ecebbef5e9c33c1445a3686a1e6753b7e513c13db70ab8fe79483eceba1930c7" + ], + "000": [ + "acc189e30495cb354e09593213925bbd3057a3d9c6e4ed592ffd2cb8a6a030f7" ] }, "affected_objects": [ @@ -227,7 +234,8 @@ "pc_topic_memory_work_blocks", "pc_topic_memory_work_budgets", "pc_source_runners", - "pc_source_collect_targets" + "pc_source_collect_targets", + "pc_atomic_memory_idempotency" ], "readiness_scope": "server", "retained_objects": [ @@ -418,6 +426,11 @@ "source_collection", "portable_storage", "atomic_memory_evidence_projection" + ], + "000": [ + "source_collection", + "portable_storage", + "atomic_memory_evidence_projection" ] }, "retained_fingerprints": { @@ -442,7 +455,8 @@ "schemas/mysql-v1_5_0_004.json", "schemas/mysql-v1_5_0_005.json", "schemas/mysql-v1_6_0.json", - "schemas/mysql-v1_5_0_006.json" + "schemas/mysql-v1_5_0_006.json", + "schemas/mysql-000.json" ], "mysql_history": "mysql", "mysql_schema_extensions": { diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/000.py b/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/000.py new file mode 100644 index 0000000000..2fdf637058 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/000.py @@ -0,0 +1,24 @@ +# 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. + +"""Add keyed Memory creation receipts.""" + +from alembic import context + +revision = "000" +down_revision = "v1_6_0" + + +def upgrade() -> None: + context.config.attributes["execute_revision"](revision) diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-000.json b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-000.json new file mode 100644 index 0000000000..ce9e9b6e82 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-000.json @@ -0,0 +1,370 @@ +{ + "format": "powercontext.mysql-state-layouts.v1", + "revisions": { + "000": { + "statements": [ + "CREATE TABLE pc_atomic_memory_idempotency (\n\tnamespace_digest VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tdigest_version INTEGER NOT NULL, \n\trequest_digest VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tscope_id VARCHAR(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tartifact_id VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\trevision INTEGER NOT NULL, \n\tstate_version INTEGER NOT NULL, \n\tcreated_at DATETIME(6) NOT NULL, \n\texpires_at DATETIME(6) NOT NULL, \n\tPRIMARY KEY (namespace_digest), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_digest_version CHECK (digest_version > 0), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_revision CHECK (revision > 0), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_state_version CHECK (state_version >= 0)\n)", + "CREATE INDEX ix_pc_atomic_memory_idempotency_expires_at ON pc_atomic_memory_idempotency (expires_at)" + ], + "changes": [ + { + "pc_atomic_memory_idempotency": { + "columns": { + "namespace_digest": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "digest_version": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "request_digest": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "scope_id": { + "type": [ + "varchar", + [ + "256" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "artifact_id": { + "type": [ + "varchar", + [ + "128" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "revision": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "state_version": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "created_at": { + "type": [ + "datetime", + [ + "6" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "expires_at": { + "type": [ + "datetime", + [ + "6" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + } + }, + "primary_key": [ + [ + "namespace_digest", + null, + "asc" + ] + ], + "foreign_keys": [], + "checks": { + "ck_pc_atomic_memory_idempotency_digest_version": { + "expression": [ + "binary", + ">", + [ + "column", + "digest_version" + ], + [ + "number", + 0 + ] + ], + "enforced": true + }, + "ck_pc_atomic_memory_idempotency_revision": { + "expression": [ + "binary", + ">", + [ + "column", + "revision" + ], + [ + "number", + 0 + ] + ], + "enforced": true + }, + "ck_pc_atomic_memory_idempotency_state_version": { + "expression": [ + "binary", + ">=", + [ + "column", + "state_version" + ], + [ + "number", + 0 + ] + ], + "enforced": true + } + }, + "indexes": {} + } + }, + { + "pc_atomic_memory_idempotency": { + "columns": { + "namespace_digest": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "digest_version": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "request_digest": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "scope_id": { + "type": [ + "varchar", + [ + "256" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "artifact_id": { + "type": [ + "varchar", + [ + "128" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "revision": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "state_version": { + "type": [ + "int", + [] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "created_at": { + "type": [ + "datetime", + [ + "6" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "expires_at": { + "type": [ + "datetime", + [ + "6" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + } + }, + "primary_key": [ + [ + "namespace_digest", + null, + "asc" + ] + ], + "foreign_keys": [], + "checks": { + "ck_pc_atomic_memory_idempotency_digest_version": { + "expression": [ + "binary", + ">", + [ + "column", + "digest_version" + ], + [ + "number", + 0 + ] + ], + "enforced": true + }, + "ck_pc_atomic_memory_idempotency_revision": { + "expression": [ + "binary", + ">", + [ + "column", + "revision" + ], + [ + "number", + 0 + ] + ], + "enforced": true + }, + "ck_pc_atomic_memory_idempotency_state_version": { + "expression": [ + "binary", + ">=", + [ + "column", + "state_version" + ], + [ + "number", + 0 + ] + ], + "enforced": true + } + }, + "indexes": { + "ix_pc_atomic_memory_idempotency_expires_at": { + "columns": [ + [ + "expires_at", + null, + "asc" + ] + ], + "unique": false + } + } + } + } + ] + } + } +} diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-000.json b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-000.json new file mode 100644 index 0000000000..407b4d7e31 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-000.json @@ -0,0 +1,6 @@ +{ + "statements": [ + "CREATE TABLE pc_atomic_memory_idempotency (\n\tnamespace_digest VARCHAR(64) NOT NULL, \n\tdigest_version INTEGER NOT NULL, \n\trequest_digest VARCHAR(64) NOT NULL, \n\tscope_id VARCHAR(256) NOT NULL, \n\tartifact_id VARCHAR(128) NOT NULL, \n\trevision INTEGER NOT NULL, \n\tstate_version INTEGER NOT NULL, \n\tcreated_at DATETIME NOT NULL, \n\texpires_at DATETIME NOT NULL, \n\tPRIMARY KEY (namespace_digest), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_digest_version CHECK (digest_version > 0), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_revision CHECK (revision > 0), \n\tCONSTRAINT ck_pc_atomic_memory_idempotency_state_version CHECK (state_version >= 0)\n)", + "CREATE INDEX ix_pc_atomic_memory_idempotency_expires_at ON pc_atomic_memory_idempotency (expires_at)" + ] +} diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/versions/000.py b/src/powercontext/builtin/persistence/migrations/server_resources/versions/000.py new file mode 100644 index 0000000000..79308d13bd --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/versions/000.py @@ -0,0 +1,29 @@ +# 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. + +"""Add keyed Memory creation receipts.""" + +import json +from pathlib import Path + +from alembic import op + +revision = "000" +down_revision = "v1_6_0" + + +def upgrade(): + resource = Path(__file__).parents[1] / "schemas/sqlite-000.json" + for statement in json.loads(resource.read_text(encoding="utf-8"))["statements"]: + op.get_bind().exec_driver_sql(statement) diff --git a/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json b/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json index 06fb746fb9..ee17831d0e 100644 --- a/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json +++ b/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json @@ -59,6 +59,10 @@ "v1_6_0": [ "schemas/sqlite-v1_6_0.json", "schemas/mysql-v1_6_0.json" + ], + "000": [ + "schemas/sqlite-000.json", + "schemas/mysql-000.json" ] }, "sqlite_baselines": { @@ -106,6 +110,9 @@ ], "v1_6_0": [ "ecebbef5e9c33c1445a3686a1e6753b7e513c13db70ab8fe79483eceba1930c7" + ], + "000": [ + "acc189e30495cb354e09593213925bbd3057a3d9c6e4ed592ffd2cb8a6a030f7" ] }, "affected_objects": [ @@ -226,7 +233,8 @@ "pc_topic_memory_work_blocks", "pc_topic_memory_work_budgets", "pc_source_runners", - "pc_source_collect_targets" + "pc_source_collect_targets", + "pc_atomic_memory_idempotency" ], "readiness_scope": "server", "retained_objects": [ @@ -422,6 +430,11 @@ "source_collection", "portable_storage", "atomic_memory_evidence_projection" + ], + "000": [ + "source_collection", + "portable_storage", + "atomic_memory_evidence_projection" ] }, "retained_fingerprints": { @@ -446,7 +459,8 @@ "schemas/mysql-v1_5_0_004.json", "schemas/mysql-v1_5_0_005.json", "schemas/mysql-v1_6_0.json", - "schemas/mysql-v1_5_0_006.json" + "schemas/mysql-v1_5_0_006.json", + "schemas/mysql-000.json" ], "mysql_history": "mysql", "mysql_schema_extensions": { diff --git a/src/powercontext/builtin/persistence/records.py b/src/powercontext/builtin/persistence/records.py index f2c2a82043..3695d52089 100644 --- a/src/powercontext/builtin/persistence/records.py +++ b/src/powercontext/builtin/persistence/records.py @@ -16,6 +16,7 @@ from __future__ import annotations +import logging from collections.abc import Awaitable, Callable, Mapping, Sequence from contextlib import aclosing from datetime import UTC, datetime @@ -24,14 +25,28 @@ from uuid import uuid4 import rfc8785 -from pydantic import JsonValue, TypeAdapter, ValidationError +from pydantic import BaseModel, JsonValue, TypeAdapter, ValidationError from sqlalchemy import func, select +from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncConnection +from powercontext._logging import log_safely from powercontext.artifacts import Artifact, ArtifactRef, StableHandle from powercontext.builtin.artifacts.atomic_memory.errors import AtomicMemoryConflictError +from powercontext.builtin.artifacts.atomic_memory.models import AtomicMemoryContent from powercontext.builtin.persistence.artifact_handles import ArtifactHandleRepository from powercontext.builtin.persistence.artifacts import ArtifactRepository, with_artifact_content +from powercontext.builtin.persistence.atomic_memory_idempotency import ( + MemoryIdempotencyConflict, + MemoryIdempotencyKey, + MemoryIdempotencyReceipt, + bind_receipt, + find_receipt, + namespace_digest, + remove_expired_receipts, + replay, + request_digest, +) from powercontext.builtin.persistence.cursor_codec import SignedCursorCodec from powercontext.builtin.persistence.database import AsyncDatabase from powercontext.builtin.persistence.errors import ( @@ -109,6 +124,8 @@ from powercontext.limits import MAX_QUERY_TAG_LABELS from powercontext.sources import SourceMaterialization, SourceObservation, SourceRef +logger = logging.getLogger(__name__) + Clock = Callable[[], datetime] IdFactory = Callable[[str], str] @@ -429,18 +446,97 @@ async def create_atomic_memories( """Prepare all standalone additions, then commit their Sources and Owners together.""" if not contents: raise InvalidBaseAccessRequestError("entries", "must contain at least one memory") - writer = self._family_writers.get("atomic-memory") - if not isinstance(writer, AtomicMemoryManagementWriter): - raise BaseOperationNotSupportedError("artifact_family", "atomic-memory", "batch creation") + writer = self._atomic_creation_writer() commands = [] for content in contents: command = writer.validate_create(content) artifact_id = self._id_factory("atomic-memory") commands.append((artifact_id, command)) + prepared = await self._prepare_atomic_creations(writer, scope_id, commands, execution_context) + async with self._database.transaction() as connection: + return await self._commit_atomic_creations(connection, writer, scope_id, prepared) + + async def create_keyed_atomic_memory( + self, + scope_id: str, + content: dict[str, JsonValue], + *, + idempotency_key: str, + principal: tuple[str, str] | None, + execution_context=None, + ) -> MemoryIdempotencyReceipt: + """Create one memory bound to a retry key, or return the creation the key already names. + + Validation and the request digest finish before the key lookup. The caller's current + creation authority is required before the lookup, so a replay or a conflict is never + reported to a caller who may no longer create in the Scope. Only a miss prepares + projections; the key record commits in the same transaction as the creation. + """ + writer = self._atomic_creation_writer() + command = cast(AtomicMemoryContent, writer.validate_create(content)) + key = MemoryIdempotencyKey(namespace_digest(scope_id, principal, idempotency_key), command) + request_digest(command) + artifact_id = self._id_factory("atomic-memory") + await writer.authorize_creates(scope_id, (artifact_id,), execution_context=execution_context) + stored = await find_receipt(self._database, key) + if stored is not None and stored.live: + return _replay_receipt(stored, key, scope_id) + prepared = await self._prepare_atomic_creations(writer, scope_id, ((artifact_id, command),), execution_context) + receipt = MemoryIdempotencyReceipt(artifact_id=artifact_id, revision=1, state_version=0) + try: + async with self._database.transaction() as connection: + await bind_receipt(connection, key, scope_id, receipt, replace_expired=stored is not None) + (created,) = await self._commit_atomic_creations(connection, writer, scope_id, prepared) + if (created.artifact_id, created.revision) != (receipt.artifact_id, receipt.revision): + raise RuntimeError("an Atomic Memory creation did not produce revision 1") # noqa: TRY003 + except IntegrityError: + # A concurrent request committed the key first; its creation wins. + concurrent = await find_receipt(self._database, key) + if concurrent is None or not concurrent.live: + raise + return _replay_receipt(concurrent, key, scope_id) + try: + await remove_expired_receipts(self._database) + except Exception as error: + log_safely( + logger, + logging.WARNING, + "Expired memory idempotency keys were not removed", + extra={ + "event": "atomic_memory.idempotency.cleanup_failed", + "operation": "remember_memory", + "unit": "atomic-memory", + "outcome": "failure", + "exception_type": type(error).__name__, + }, + ) + return receipt + + def _atomic_creation_writer(self) -> AtomicMemoryManagementWriter: + writer = self._family_writers.get("atomic-memory") + if not isinstance(writer, AtomicMemoryManagementWriter): + raise BaseOperationNotSupportedError("artifact_family", "atomic-memory", "batch creation") + return writer + + async def _prepare_atomic_creations( + self, + writer: AtomicMemoryManagementWriter, + scope_id: str, + commands: Sequence[tuple[str, BaseModel]], + execution_context, + ) -> tuple[tuple[str, BaseModel, AtomicMemoryManagementPrepared], ...]: values = await writer.prepare_creates(scope_id, commands, execution_context=execution_context) - prepared = tuple( + return tuple( (artifact_id, command, value) for (artifact_id, command), value in zip(commands, values, strict=True) ) + + async def _commit_atomic_creations( + self, + connection: AsyncConnection, + writer: AtomicMemoryManagementWriter, + scope_id: str, + prepared: tuple[tuple[str, BaseModel, AtomicMemoryManagementPrepared], ...], + ) -> tuple[ArtifactCreated, ...]: source_values = [] for artifact_id, command, _ in prepared: payload = cast(dict[str, JsonValue], command.model_dump(mode="json", by_alias=True, exclude_none=True)) @@ -463,27 +559,24 @@ async def create_atomic_memories( ), ) ) - created = [] - async with self._database.transaction() as connection: - stored_sources = await self._sources.add_many_with_status(connection, scope_id, source_values) - stored_values = tuple(stored for stored, _ in stored_sources) - source_read_set = await self._sources.preload( - connection, - scope_id, - tuple(stored.ref for stored in stored_values), - known=stored_values, - ) - artifacts = await writer.create_many( - connection, - scope_id, - tuple( - (artifact_id, value, stored.ref) - for (artifact_id, _, value), stored in zip(prepared, stored_values, strict=True) - ), - source_read_set=source_read_set, - ) - created.extend(_artifact_created(scope_id, artifact) for artifact in artifacts) - return tuple(created) + stored_sources = await self._sources.add_many_with_status(connection, scope_id, source_values) + stored_values = tuple(stored for stored, _ in stored_sources) + source_read_set = await self._sources.preload( + connection, + scope_id, + tuple(stored.ref for stored in stored_values), + known=stored_values, + ) + artifacts = await writer.create_many( + connection, + scope_id, + tuple( + (artifact_id, value, stored.ref) + for (artifact_id, _, value), stored in zip(prepared, stored_values, strict=True) + ), + source_read_set=source_read_set, + ) + return tuple(_artifact_created(scope_id, artifact) for artifact in artifacts) async def get_artifact( self, scope_id: str, family: str, artifact_id: str, /, *, execution_context=None @@ -955,6 +1048,13 @@ def _artifact_record( ) +def _replay_receipt(stored, key: MemoryIdempotencyKey, scope_id: str) -> MemoryIdempotencyReceipt: + try: + return replay(stored, key) + except MemoryIdempotencyConflict: + raise BaseValueConflictError("memory_idempotency_key", scope_id) from None + + def _artifact_created(scope_id: str, artifact: Artifact[Any]) -> ArtifactCreated: return ArtifactCreated( scope_id=scope_id, diff --git a/src/powercontext/builtin/persistence/tables.py b/src/powercontext/builtin/persistence/tables.py index 95ccb69986..19d158e6db 100644 --- a/src/powercontext/builtin/persistence/tables.py +++ b/src/powercontext/builtin/persistence/tables.py @@ -1137,6 +1137,26 @@ def _instant_type(): ) +# Keyed remember_memory receipts. Only digests of the namespace and request are +# stored; expired rows are disposable and cleaned through the expiry index. +ATOMIC_MEMORY_IDEMPOTENCY_TABLE = Table( + "pc_atomic_memory_idempotency", + SHARED_METADATA, + Column("namespace_digest", identity_string(64), primary_key=True), + Column("digest_version", Integer, nullable=False), + Column("request_digest", identity_string(64), nullable=False), + Column("scope_id", identity_string(MAX_SCOPE_ID_LENGTH), nullable=False), + Column("artifact_id", identity_string(MAX_ARTIFACT_ID_LENGTH), nullable=False), + Column("revision", Integer, nullable=False), + Column("state_version", Integer, nullable=False), + Column("created_at", DateTime(timezone=False).with_variant(DATETIME(fsp=6), "mysql"), nullable=False), + Column("expires_at", DateTime(timezone=False).with_variant(DATETIME(fsp=6), "mysql"), nullable=False), + CheckConstraint("digest_version > 0", name="ck_pc_atomic_memory_idempotency_digest_version"), + CheckConstraint("revision > 0", name="ck_pc_atomic_memory_idempotency_revision"), + CheckConstraint("state_version >= 0", name="ck_pc_atomic_memory_idempotency_state_version"), + Index("ix_pc_atomic_memory_idempotency_expires_at", "expires_at"), +) + SHARED_TABLES = ( SOURCE_JOURNAL_HEADS_TABLE, SOURCES_TABLE, @@ -1172,6 +1192,7 @@ def _instant_type(): SKILL_PACKAGES_TABLE, AGENT_SKILL_TARGETS_TABLE, SKILL_PUBLICATIONS_TABLE, + ATOMIC_MEMORY_IDEMPOTENCY_TABLE, ) diff --git a/src/powercontext/builtin/records.py b/src/powercontext/builtin/records.py index 2dc5f0da27..0d9d552fe9 100644 --- a/src/powercontext/builtin/records.py +++ b/src/powercontext/builtin/records.py @@ -314,6 +314,16 @@ async def create_atomic_memories( self, scope_id: str, contents: tuple[dict[str, JsonValue], ...], *, execution_context: Any = None ) -> tuple[ArtifactCreated, ...]: ... + async def create_keyed_atomic_memory( + self, + scope_id: str, + content: dict[str, JsonValue], + *, + idempotency_key: str, + principal: tuple[str, str] | None, + execution_context: Any = None, + ) -> Any: ... + async def bind_artifact_handle( self, scope_id: str, diff --git a/src/powercontext/builtin/runtime/application.py b/src/powercontext/builtin/runtime/application.py index 1ff3a7683e..2f950a1d14 100644 --- a/src/powercontext/builtin/runtime/application.py +++ b/src/powercontext/builtin/runtime/application.py @@ -43,6 +43,8 @@ from powercontext.builtin.artifacts.atomic_memory.models import ( AtomicMemoryContent, AtomicMemoryMutationResult, + AtomicMemoryRecord, + AtomicMemoryState, ) from powercontext.builtin.artifacts.experience import ( EXPERIENCE_INCUBATION_WINDOW_LIMIT, @@ -161,11 +163,13 @@ ArtifactGovernance, ArtifactLifecycleState, ) +from powercontext.builtin.persistence.atomic_memory_idempotency import KEY_PATTERN as IDEMPOTENCY_KEY_PATTERN from powercontext.builtin.persistence.bootstrap_receipts import ( BootstrapReceiptRepository, StoredBootstrapReceipt, ) from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.errors import RepositoryNotFoundError from powercontext.builtin.persistence.skill_publications import SkillPublication from powercontext.builtin.processing_diagnostics import observe_processing_failure from powercontext.builtin.publication import ArtifactPublicationApplication @@ -176,6 +180,7 @@ ArtifactRevisionPage, ArtifactWrite, BaseValueConflictError, + BaseValueNotFoundError, InvalidBaseAccessRequestError, LogicalArtifactRecord, RecordService, @@ -4124,13 +4129,21 @@ async def search(self, query: str, *, _trace: bool = True, **kwargs): }) return result - async def create(self, contents: Sequence[AtomicMemoryContent], /, *, context=None) -> AtomicMemoryMutationResult: - """Create explicit Atomic Memories in one all-or-nothing batch.""" + async def create( + self, contents: Sequence[AtomicMemoryContent], /, *, idempotency_key: str | None = None, context=None + ) -> AtomicMemoryMutationResult: + """Create explicit Atomic Memories in one all-or-nothing batch. + + With ``idempotency_key``, exactly one memory is created per key namespace; a retry + of the same content returns revision 1 with the state recorded at its creation. + """ values = tuple(content.model_dump(mode="json", by_alias=True, exclude_none=True) for content in contents) async with self._runtime._scoped_operation( self.scope_id, embedding_purpose=ModelUsagePurpose.MEMORY_INDEXING, ): + if idempotency_key is not None: + return await self._create_keyed(values, idempotency_key, context) created = await self._runtime._records().create_atomic_memories( self.scope_id, values, execution_context=context ) @@ -4139,6 +4152,36 @@ async def create(self, contents: Sequence[AtomicMemoryContent], /, *, context=No changed=True, records=records, primary_artifact_id=records[0].artifact.artifact_id ) + async def _create_keyed(self, values, idempotency_key: str, context) -> AtomicMemoryMutationResult: + if len(values) != 1: + raise InvalidBaseAccessRequestError("idempotency_key", "applies to exactly one memory") + if not IDEMPOTENCY_KEY_PATTERN.fullmatch(idempotency_key): + raise InvalidBaseAccessRequestError( + "idempotency_key", "must be 1 to 256 printable ASCII characters, no spaces" + ) + # Without an access service every caller shares the Scope's one key namespace, + # whatever principal the context happens to name. + principal = None if context is None or context.access is None else context.principal + receipt = await self._runtime._records().create_keyed_atomic_memory( + self.scope_id, + values[0], + idempotency_key=idempotency_key, + principal=None if principal is None else (principal.type, principal.id), + execution_context=context, + ) + # Both a new creation and a replay read the exact revision with the caller's + # current authorization, so a concurrent later revision changes neither result. + try: + exact = await self._scoped.get(receipt.artifact_id, revision=receipt.revision, context=context) + except RepositoryNotFoundError: + raise BaseValueNotFoundError( + "artifact", (self.scope_id, "atomic-memory", receipt.artifact_id, receipt.revision) + ) from None + record = AtomicMemoryRecord( + artifact=exact.artifact, state=AtomicMemoryState(state_version=receipt.state_version) + ) + return AtomicMemoryMutationResult(changed=True, records=(record,), primary_artifact_id=receipt.artifact_id) + async def flush(self, /, *, limit: int | None = None, context=None) -> MemoryFlushResult: """Process the next scoped Source window into Atomic Memory.""" return await self._runtime._flush_sources(self.scope_id, limit=limit, context=context) diff --git a/src/powercontext/http/_generated/models.py b/src/powercontext/http/_generated/models.py index c89d5922c2..efac92e172 100644 --- a/src/powercontext/http/_generated/models.py +++ b/src/powercontext/http/_generated/models.py @@ -3276,6 +3276,15 @@ class RememberMemoryRequest(BaseModel): pattern="^[^\\r\\n\\u0085\\u2028\\u2029]*\\S[^\\r\\n\\u0085\\u2028\\u2029]*$", ), ] = None + idempotency_key: Annotated[ + StrictStr | None, + Field( + description="Optional retry key, unique per operation, Scope and authenticated principal. Generate a fresh unguessable value for each logical write and reuse it only to retry that write. Keys are compared byte for byte and retained for 24 hours. Omit it or pass null for no key.", + max_length=256, + min_length=1, + pattern="^[!-~]{1,256}$", + ), + ] = None class RetireMemoryEntryRequest(BaseModel): diff --git a/src/powercontext/http/_generated/schema.py b/src/powercontext/http/_generated/schema.py index 955d7aac9b..8d52417343 100644 --- a/src/powercontext/http/_generated/schema.py +++ b/src/powercontext/http/_generated/schema.py @@ -3428,7 +3428,13 @@ "or pass null. Non-null legacy " "collection revision preconditions are " "unsupported before any write. Response " - "records use true Atomic ArtifactRefs.", + "records use true Atomic ArtifactRefs. " + "With idempotency_key, a retry of the " + "same creation within 24 hours replays " + "the original response, and reuse of " + "the key for different content returns " + "409 idempotency_conflict with " + "details.kind memory_idempotency_key.", "operationId": "remember_memory", "requestBody": { "content": {"application/json": {"schema": {"$ref": "#/components/schemas/RememberMemoryRequest"}}}, @@ -14601,6 +14607,59 @@ "model.", "nullable": True, }, + "idempotency_key": { + "type": "string", + "maxLength": 256, + "minLength": 1, + "pattern": "^[!-~]{1,256}$", + "description": "Optional " + "retry " + "key, " + "unique " + "per " + "operation, " + "Scope " + "and " + "authenticated " + "principal. " + "Generate " + "a " + "fresh " + "unguessable " + "value " + "for " + "each " + "logical " + "write " + "and " + "reuse " + "it " + "only " + "to " + "retry " + "that " + "write. " + "Keys " + "are " + "compared " + "byte " + "for " + "byte " + "and " + "retained " + "for " + "24 " + "hours. " + "Omit " + "it " + "or " + "pass " + "null " + "for " + "no " + "key.", + "nullable": True, + }, }, "additionalProperties": False, "type": "object", diff --git a/src/powercontext/server/app.py b/src/powercontext/server/app.py index 1f9613298f..0d8bdb89b0 100644 --- a/src/powercontext/server/app.py +++ b/src/powercontext/server/app.py @@ -4657,6 +4657,7 @@ async def remember_memory( raise BaseOperationNotSupportedError("artifact_family", "memory", "collection revision precondition") result = await _scoped_atomic_memory(application, request.scope_id).create( (AtomicMemoryContent(kind=request.kind, text=request.text, description=request.description),), + idempotency_key=request.idempotency_key, context=_atomic_execution_context(http_request, REMEMBER_MEMORY.operation_id), ) return mapping.mutation_response(result) diff --git a/src/powercontext/server/mcp.py b/src/powercontext/server/mcp.py index 8def57693c..18887f2d2c 100644 --- a/src/powercontext/server/mcp.py +++ b/src/powercontext/server/mcp.py @@ -135,7 +135,10 @@ Never treat an Atomic revision as an old collection revision. Legacy citation revise/retire, collection capacity, and collection changes are unsupported. For an explicit future save (remember this / 记住这个供以后使用), call remember_memory with expected_revision omitted or -null and verify its Atomic records. A non-null legacy collection revision precondition is unsupported. Use merge_atomic_memories, +null and verify its Atomic records. A non-null legacy collection revision precondition is unsupported. +To retry a save whose outcome is unknown, resend the same content with the same idempotency_key. Generate a fresh +unguessable key, such as a UUID, for each new save and reuse it only for that save's retries; after +idempotency_conflict, use a new key. Use merge_atomic_memories, change_atomic_memory_lifecycle and restoration previews/restorations only for explicitly requested state changes; current revision and state_version inputs must come from reads. Automatic Source capture is not an explicit Memory write, and enabled hooks do not establish successful recall or persistence. diff --git a/tests/builtin/persistence/test_atomic_description_vector_layout.py b/tests/builtin/persistence/test_atomic_description_vector_layout.py index be869bf83b..7fa08c1097 100644 --- a/tests/builtin/persistence/test_atomic_description_vector_layout.py +++ b/tests/builtin/persistence/test_atomic_description_vector_layout.py @@ -43,7 +43,7 @@ def test_managed_sqlite_vector_schema_includes_registered_nullable_description(t database = tmp_path / "vector.db" runner = SQLiteMigrationRunner(database, bundle, configuration=configuration) result = runner.apply(plan_id=runner.plan().plan_id, accepted=True, maintenance_confirmed=True) - assert result.revision == "v1_6_0" + assert result.revision == "000" with closing(sqlite3.connect(database)) as connection: columns = {row[1]: row for row in connection.execute("PRAGMA table_info(pc_atomic_memory_current)")} assert columns["description"][2:4] == ("VARCHAR(200)", 0) @@ -156,7 +156,7 @@ def test_description_upgrade_preserves_registered_owner_recovery_and_evidence(tm upgraded = SQLiteMigrationRunner(database, current, configuration=configuration) plan = upgraded.plan() assert plan.source_revision == "v1_4_1_004" - assert plan.target_revision == "v1_6_0" + assert plan.target_revision == "000" assert plan.revisions == ( "v1_4_1_005", "v1_4_1_006", @@ -167,6 +167,7 @@ def test_description_upgrade_preserves_registered_owner_recovery_and_evidence(tm "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ) assert plan.domain_steps == ( "artifact_storage", @@ -176,7 +177,7 @@ def test_description_upgrade_preserves_registered_owner_recovery_and_evidence(tm "source_collection", ) assert upgraded.evidence_path.read_bytes() == original_evidence_bytes - assert upgraded.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True).revision == "v1_6_0" + assert upgraded.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True).revision == "000" assert upgraded.verify().state == "ready" evidence = json.loads(upgraded.evidence_path.read_text(encoding="utf-8")) for revision, checksum in original_evidence["release_checksums"].items(): diff --git a/tests/builtin/persistence/test_atomic_evidence_upgrade_history.py b/tests/builtin/persistence/test_atomic_evidence_upgrade_history.py index 5415e7e2b9..e605f7fd3a 100644 --- a/tests/builtin/persistence/test_atomic_evidence_upgrade_history.py +++ b/tests/builtin/persistence/test_atomic_evidence_upgrade_history.py @@ -170,6 +170,7 @@ def test_evidence_upgrade_accepts_upstream_history_and_preserves_data(tmp_path, "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ) assert plan.domain_steps == ( "artifact_storage", @@ -202,6 +203,7 @@ def test_evidence_upgrade_accepts_upstream_history_and_preserves_data(tmp_path, "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", } ready = reopened.plan() assert ready.state == "ready" @@ -255,7 +257,7 @@ def test_evidence_projection_upgrade_preserves_registered_evidence_revision(tmp_ before = old.evidence_path.read_bytes() upgraded = SQLiteMigrationRunner(database, current, configuration=config) plan = upgraded.plan() - assert plan.revisions == (PROJECTION_REVISION, "v1_5_0_004", "v1_5_0_005", "v1_5_0_006", "v1_6_0") + assert plan.revisions == (PROJECTION_REVISION, "v1_5_0_004", "v1_5_0_005", "v1_5_0_006", "v1_6_0", "000") assert plan.domain_steps == ("atomic_memory_evidence_projection", "plugin_artifacts", "source_collection") assert old.evidence_path.read_bytes() == before assert upgraded.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True).revision == current.head diff --git a/tests/builtin/persistence/test_diagnostic_query_migration.py b/tests/builtin/persistence/test_diagnostic_query_migration.py index c923b5e49d..af0c19756b 100644 --- a/tests/builtin/persistence/test_diagnostic_query_migration.py +++ b/tests/builtin/persistence/test_diagnostic_query_migration.py @@ -39,8 +39,8 @@ def test_diagnostic_upgrade_creates_query_column_and_preserves_published_data(tm current = server_bundle() assert all(current.checksums[key] == value for key, value in previous.checksums.items()) upgraded = SQLiteMigrationRunner(database, current, configuration=config) - assert upgraded.plan().revisions == ("v1_5_0_006", "v1_6_0") - assert apply(upgraded).revision == "v1_6_0" + assert upgraded.plan().revisions == ("v1_5_0_006", "v1_6_0", "000") + assert apply(upgraded).revision == "000" assert upgraded.verify().state == "ready" and not apply(upgraded).changed query = "查询原文保留 😀\n" with closing(sqlite3.connect(database)) as connection, connection: diff --git a/tests/builtin/persistence/test_full_server_migrations.py b/tests/builtin/persistence/test_full_server_migrations.py index ef25e8c968..0161efb2a5 100644 --- a/tests/builtin/persistence/test_full_server_migrations.py +++ b/tests/builtin/persistence/test_full_server_migrations.py @@ -73,7 +73,7 @@ def dump(path): def test_complete_upgrade_preserves_history_backup_and_repeated_apply(source): before = dump(source.database) plan = source.plan() - assert plan.source_revision == "s1300" and plan.target_revision == "v1_6_0" + assert plan.source_revision == "s1300" and plan.target_revision == "000" assert plan.revisions == ( "s1400", "s1401", @@ -88,6 +88,7 @@ def test_complete_upgrade_preserves_history_backup_and_repeated_apply(source): "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ) assert dump(source.database) == before result = apply(source) diff --git a/tests/builtin/persistence/test_mysql_initialization_preflight.py b/tests/builtin/persistence/test_mysql_initialization_preflight.py index a5f06e436a..8d9acc3bb6 100644 --- a/tests/builtin/persistence/test_mysql_initialization_preflight.py +++ b/tests/builtin/persistence/test_mysql_initialization_preflight.py @@ -261,6 +261,7 @@ def test_evidence_recovery_resumes_before_final_schema_marker(tmp_path, monkeypa "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ) assert (database.read_bytes(), journal.path.read_bytes()) == before diff --git a/tests/builtin/persistence/test_mysql_migration_runner.py b/tests/builtin/persistence/test_mysql_migration_runner.py index 522f94703b..0c6613634a 100644 --- a/tests/builtin/persistence/test_mysql_migration_runner.py +++ b/tests/builtin/persistence/test_mysql_migration_runner.py @@ -476,7 +476,7 @@ def seed(connection, _identity, _guard): assert recovery.state == "recovery_required" and recovery.source_revision == PREVIOUS token = (recovery.coordination or {}).get("pending_run_id") resumed = _full_server_runner(backend, acknowledge_previous_run=token) - assert _apply(resumed, policy="skip").revision == "v1_6_0" + assert _apply(resumed, policy="skip").revision == "000" assert resumed.verify().state == "ready" def inspect(connection, _identity, _guard): @@ -769,7 +769,7 @@ def test_oceanbase_server_upgrade_with_separate_code_cache_preserves_history( ) assert runner.plan(backup_policy="manual").source_revision == "s1300" result = _apply(runner, policy="manual") - assert result.readiness_scope == "server" and result.revision == "v1_6_0" + assert result.readiness_scope == "server" and result.revision == "000" assert runner.verify().state == "ready" prepare_server_storage(settings) assert not _apply(runner, policy="manual").changed @@ -900,7 +900,7 @@ def inspect_history(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_history) == ("v1_6_0", "dedicated", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("000", "dedicated", b'{"history":"unchanged"}') (main_path,) = backend.evidence_directory.glob("*/maintenance.json") evidence = json.loads(main_path.read_text()) @@ -910,7 +910,7 @@ def inspect_history(connection, identity, guard): for inspect in (runner.plan, runner.verify, runner.apply): with pytest.raises(MigrationError, match="checksum_conflict"): inspect() - assert backend.connections().run(inspect_history) == ("v1_6_0", "dedicated", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("000", "dedicated", b'{"history":"unchanged"}') assert { path: path.read_bytes() for path in backend.evidence_directory.rglob("maintenance.json") } == original_evidence @@ -977,7 +977,7 @@ def inspect_history(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_history) == ("v1_6_0", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("000", b'{"history":"unchanged"}') def test_mysql_registered_projection_repair_preserves_authority_and_revision(backend: _BackendTarget) -> None: @@ -1045,7 +1045,11 @@ def inspect_content(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_content) == ("v1_6_0", content, "Preserve immutable nebula evidence.") + assert backend.connections().run(inspect_content) == ( + "000", + content, + "Preserve immutable nebula evidence.", + ) @pytest.mark.parametrize("origin", ("empty", "released")) @@ -1209,7 +1213,7 @@ def test_mysql_full_server_interruption_preserves_history_and_original_maintenan _load_full_server_baseline(backend) runner = _full_server_runner(backend) original = runner.plan(backup_policy="manual") - assert original.source_revision == "s1300" and original.target_revision == "v1_6_0" + assert original.source_revision == "s1300" and original.target_revision == "000" _interrupt_after_ddl(runner, interruption) journals = list(backend.evidence_directory.rglob("maintenance.json")) assert len(journals) == 1 @@ -1231,7 +1235,7 @@ def test_mysql_full_server_interruption_preserves_history_and_original_maintenan result = _apply(resumed, policy="manual") - assert result.readiness_scope == "server" and result.revision == "v1_6_0" + assert result.readiness_scope == "server" and result.revision == "000" assert result.backup_state == "user_confirmed" assert result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" @@ -1311,7 +1315,7 @@ def client_active(connection: Connection | None, _identity: BackendIdentity, _gu # interruption. An arbitrary remote failure cannot be acknowledged blindly. resumed = _full_server_runner(backend, acknowledge_previous_run=token) result = _apply(resumed, policy="manual") - assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "v1_6_0" + assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "000" assert result.backup_state == "user_confirmed" and result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" completed = json.loads(journals[0].read_text(encoding="utf-8")) diff --git a/tests/builtin/persistence/test_plugin_storage_migration.py b/tests/builtin/persistence/test_plugin_storage_migration.py index 09bbcb1312..b9174ee7f0 100644 --- a/tests/builtin/persistence/test_plugin_storage_migration.py +++ b/tests/builtin/persistence/test_plugin_storage_migration.py @@ -159,9 +159,9 @@ def test_upgrade_refuses_retained_plugin_data_and_drops_only_empty_storage(tmp_p with closing(sqlite3.connect(database)) as connection, connection: connection.execute("DELETE FROM pc_artifact_family_schemas") plan = upgraded.plan() - assert plan.revisions == ("v1_5_0_005", "v1_5_0_006", "v1_6_0") + assert plan.revisions == ("v1_5_0_005", "v1_5_0_006", "v1_6_0", "000") assert plan.domain_steps == ("plugin_artifacts", "source_collection") - assert apply(upgraded).revision == "v1_6_0" + assert apply(upgraded).revision == "000" assert upgraded.verify().state == "ready" with closing(sqlite3.connect(database)) as connection: tables = {row[0] for row in connection.execute("SELECT name FROM sqlite_schema WHERE type='table'")} @@ -187,7 +187,7 @@ def test_upgrade_refuses_loaded_source_write_plugins_and_adds_collection_tables( with closing(sqlite3.connect(database)) as connection, connection: connection.execute("DELETE FROM pc_source_write_plugins") - assert apply(upgraded).revision == "v1_6_0" + assert apply(upgraded).revision == "000" with closing(sqlite3.connect(database)) as connection: tables = {row[0] for row in connection.execute("SELECT name FROM sqlite_schema WHERE type='table'")} assert "pc_source_write_plugins" not in tables diff --git a/tests/builtin/persistence/test_portable_storage_migration.py b/tests/builtin/persistence/test_portable_storage_migration.py index 174a838959..b0c50d168e 100644 --- a/tests/builtin/persistence/test_portable_storage_migration.py +++ b/tests/builtin/persistence/test_portable_storage_migration.py @@ -19,6 +19,7 @@ import shutil import sqlite3 from contextlib import closing +from pathlib import Path import pytest @@ -54,7 +55,7 @@ def previous_bundle(directory, embedding, *, through="s1401"): shutil.copytree(current.directory, directory, ignore=shutil.ignore_patterns("__pycache__")) manifest_path = directory / "manifest.json" manifest = json.loads(manifest_path.read_text()) - revisions = list(manifest["revision_resources"]) + revisions = current.revisions # Prune every revision after the requested previous head so the fixture # keeps describing the same earlier registration as later revisions are appended. created = set() @@ -68,9 +69,8 @@ def previous_bundle(directory, embedding, *, through="s1401"): path.unlink(missing_ok=True) if resource in manifest["mysql_state_layouts"]: manifest["mysql_state_layouts"].remove(resource) - for version in (directory / "versions").glob(f"{revision}_*.py"): - version.unlink() - (directory / "versions" / f"{revision}.py").unlink(missing_ok=True) + script = current.script.get_revision(revision) + (directory / Path(script.path).relative_to(current.snapshot_directory)).unlink() (directory / "mysql" / "versions" / f"{revision}.py").unlink(missing_ok=True) del manifest["sqlite_fingerprints"][revision] del manifest["domain_readiness"][revision] @@ -134,8 +134,9 @@ def test_registered_s1401_upgrade_preserves_completed_evidence_and_matches_fresh "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ) - assert apply(upgraded).revision == "v1_6_0" + assert apply(upgraded).revision == "000" assert upgraded.verify().state == "ready" assert not apply(upgraded).changed fresh = SQLiteMigrationRunner(tmp_path / "fresh.db", bundle, configuration=config) @@ -204,6 +205,7 @@ def test_release_upgrade_preserves_data_and_adds_collection_runners(tmp_path, ve "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ) if include_owner else ( @@ -217,9 +219,10 @@ def test_release_upgrade_preserves_data_and_adds_collection_runners(tmp_path, ve "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ) ) - assert apply(upgraded).revision == "v1_6_0" + assert apply(upgraded).revision == "000" capabilities = b'[{"error":null,"name":"tickets","version":"1.0.0"}]' with closing(sqlite3.connect(database)) as connection, connection: assert connection.execute("SELECT title FROM pc_scopes").fetchall() == [("preserved",)] diff --git a/tests/builtin/persistence/test_release140_server_migrations.py b/tests/builtin/persistence/test_release140_server_migrations.py index 3c5045f831..b787643133 100644 --- a/tests/builtin/persistence/test_release140_server_migrations.py +++ b/tests/builtin/persistence/test_release140_server_migrations.py @@ -160,6 +160,7 @@ def test_registered_sources_choose_distinct_lineages(tmp_path, release, expected "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ) @@ -373,7 +374,7 @@ def connect(): finally: engine.dispose() - assert _apply(runner).revision == "v1_6_0" + assert _apply(runner).revision == "000" assert runner.verify().state == "ready" assert not _apply(runner).changed app = create_server_app( diff --git a/tests/e2e/test_atomic_memory_description_upgrade.py b/tests/e2e/test_atomic_memory_description_upgrade.py index 3c27fb53a4..00712493ed 100644 --- a/tests/e2e/test_atomic_memory_description_upgrade.py +++ b/tests/e2e/test_atomic_memory_description_upgrade.py @@ -85,9 +85,9 @@ def test_nonempty_released_memory_upgrades_without_rewriting_history(tmp_path, r ) result = _apply(runner) - assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "v1_6_0" + assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "000" verified = runner.verify() - assert verified.state == "ready" and verified.readiness_scope == "server" and verified.revision == "v1_6_0" + assert verified.state == "ready" and verified.readiness_scope == "server" and verified.revision == "000" assert not _apply(runner).changed with closing(sqlite3.connect(runner.database)) as connection: assert ( diff --git a/tests/e2e/test_remember_memory_idempotency.py b/tests/e2e/test_remember_memory_idempotency.py new file mode 100644 index 0000000000..3001df6bff --- /dev/null +++ b/tests/e2e/test_remember_memory_idempotency.py @@ -0,0 +1,657 @@ +# 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. + +"""Keyed remember_memory retries create one memory and replay its original result.""" + +from __future__ import annotations + +import asyncio +import json +import multiprocessing +import sqlite3 +from contextlib import asynccontextmanager, closing +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import httpx +import pytest + +from powercontext.builtin.artifacts.atomic_memory import AtomicMemoryContent +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.persistence.family_management import AtomicMemoryManagementWriter +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.records import BaseValueConflictError, InvalidBaseAccessRequestError +from powercontext.builtin.runtime import BuiltinConfig, RuntimeConfig, open_builtin_runtime +from powercontext.builtin.scope import ScopeDraft +from powercontext.client import PowerContextClient +from powercontext.http import RememberMemoryRequest +from powercontext.server.authentication import AuthenticationResult, ProviderReadiness +from powercontext.server.factory import create_server_app +from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings +from tests.e2e.server_storage import prepare_server_database + +ADMIN = PrincipalRef(type="service", id="admin") + + +@pytest.mark.parametrize("source_release", [None, "1.4.0"]) +def test_keyed_creation_after_prepare_diagnostics_upgrade(tmp_path: Path, source_release) -> None: + """Both registered histories upgrade from the Prepare diagnostics checkpoint before keyed writes.""" + import shutil + + from powercontext.builtin.persistence.migrations import MigrationBundle, SQLiteMigrationRunner + from powercontext.builtin.persistence.migrations.deployment import server_bundle + from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest + + database = tmp_path / "source-collection.db" + bundle = server_bundle(source_release=source_release) + configuration = {"processing_manifest": canonical_processing_manifest(BuiltinConfig()), "embedding_enabled": False} + previous_directory = tmp_path / "prepare-diagnostics-bundle" + shutil.copytree(bundle.snapshot_directory, previous_directory) + revision = bundle.script.get_revision("000") + (previous_directory / Path(revision.path).relative_to(bundle.snapshot_directory)).unlink() + manifest_path = previous_directory / "manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + for field in ("revision_resources", "sqlite_fingerprints", "domain_readiness"): + del manifest[field]["000"] + manifest["mysql_state_layouts"].remove("schemas/mysql-000.json") + manifest["affected_objects"].remove("pc_atomic_memory_idempotency") + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + previous = SQLiteMigrationRunner(database, MigrationBundle(previous_directory), configuration=configuration) + previous.apply( + plan_id=previous.plan(backup_policy="skip").plan_id, + backup_policy="skip", + accepted=True, + maintenance_confirmed=True, + accept_no_backup=True, + ) + with closing(sqlite3.connect(database)) as connection, connection: + connection.execute( + "INSERT INTO pc_source_runners " + "(runner,display_name,principal_type,principal_id,registered_at,capabilities,capabilities_digest) " + "VALUES ('preserved','Preserved runner','service','runner','2026-01-01 00:00:00',?,?)", + (b"[]", "0" * 64), + ) + + runner = SQLiteMigrationRunner(database, bundle, configuration=configuration) + plan = runner.plan(backup_policy="skip") + assert plan.source_revision == "v1_6_0" + assert plan.revisions == ("000",) + runner.apply( + plan_id=plan.plan_id, + backup_policy="skip", + accepted=True, + maintenance_confirmed=True, + accept_no_backup=True, + ) + assert runner.verify().state == "ready" + assert not runner.apply().changed + with closing(sqlite3.connect(database)) as connection: + assert connection.execute( + "SELECT name FROM sqlite_schema WHERE type='table' AND name IN " + "('pc_atomic_memory_idempotency','pc_atomic_memory_alias')" + ).fetchall() == [("pc_atomic_memory_idempotency",)] + assert connection.execute("SELECT runner,capabilities FROM pc_source_runners").fetchall() == [ + ("preserved", b"[]") + ] + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + created = await _remember(client, scope_id, "Keep the Source runner", "after-upgrade") + assert created.status_code == 200, created.text + replayed = await _remember(client, scope_id, "Keep the Source runner", "after-upgrade") + assert replayed.status_code == 200, replayed.text + assert replayed.json() == created.json() + assert _memories(database) == 1 + + asyncio.run(scenario()) + + +def _settings(database: Path, **options) -> ServerSettings: + return ServerSettings( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"), + mcp=McpConfig(enabled=False), + metrics=MetricsConfig(enabled=False), + **options, + ) + + +@asynccontextmanager +async def _open(database: Path): + app = create_server_app(settings=_settings(database)) + async with ( + app.router.lifespan_context(app), + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client, + ): + yield client + + +async def _default_scope(client: httpx.AsyncClient) -> str: + sdk = PowerContextClient("http://testserver", http_client=client, trust_transport_security=True) + return (await sdk.get_default_scope()).scope_id + + +def _count(database: Path, sql: str, *parameters) -> int: + with closing(sqlite3.connect(database)) as connection: + return connection.execute(sql, parameters).fetchone()[0] + + +def _memories(database: Path) -> int: + return _count(database, "SELECT COUNT(DISTINCT artifact_id) FROM pc_artifacts WHERE family = 'atomic-memory'") + + +def _sources(database: Path) -> int: + return _count(database, "SELECT COUNT(*) FROM pc_sources") + + +async def _remember(client: httpx.AsyncClient, scope_id: str, text: str, key: str | None = None, **fields): + body = {"scope_id": scope_id, "kind": "preference", "text": text, **fields} + if key is not None: + body["idempotency_key"] = key + return await client.post("/v1/memory/remember", json=body) + + +def test_keyed_retry_replays_original_creation(tmp_path: Path) -> None: + database = tmp_path / "replay.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + key = f"retry-{uuid4()}" + first = await _remember(client, scope_id, "Cafe\N{COMBINING ACUTE ACCENT} order is oat milk", key) + assert first.status_code == 200, first.text + created = first.json() + assert created["changed"] is True + record = created["records"][0] + assert record["artifact"]["revision"] == 1 + assert (record["state"], record["state_version"], record["merged_into_id"]) == ("active", 0, None) + memories, sources = _memories(database), _sources(database) + + # Equivalent stored content replays: NFC, outer whitespace, the default description, and reason. + retries: tuple[tuple[str, dict[str, str | None]], ...] = ( + ("Cafe\N{COMBINING ACUTE ACCENT} order is oat milk", {}), + (" Café order is oat milk \n", {}), + ("Café order is oat milk", {"description": None}), + ("Café order is oat milk", {"description": "Café order is oat milk"}), + ("Café order is oat milk", {"reason": "retry after a lost response"}), + ) + for text, retry in retries: + replayed = await _remember(client, scope_id, text, key, **retry) + assert replayed.status_code == 200, replayed.text + assert replayed.json() == created + sdk = PowerContextClient("http://testserver", http_client=client, trust_transport_security=True) + through_sdk = await sdk.remember_memory( + RememberMemoryRequest( + scope_id=scope_id, kind="preference", text="Café order is oat milk", idempotency_key=key + ) + ) + assert through_sdk.model_dump(mode="json") == created + assert (_memories(database), _sources(database)) == (memories, sources) + + # Keys are independent of each other, and requests without a key keep creating. + other = await _remember(client, scope_id, "Café order is oat milk", f"retry-{uuid4()}") + assert other.json()["records"][0]["artifact"]["artifact_id"] != record["artifact"]["artifact_id"] + for _ in range(2): + unkeyed = await _remember(client, scope_id, "Café order is oat milk") + assert unkeyed.status_code == 200, unkeyed.text + # A keyed creation answers exactly as an unkeyed creation of the same content. + unkeyed_record = unkeyed.json()["records"][0] + assert {**unkeyed_record, "artifact": None} == {**record, "artifact": None} + assert unkeyed_record["artifact"].keys() == record["artifact"].keys() + assert _memories(database) == memories + 3 + + with closing(sqlite3.connect(database)) as connection: + rows = connection.execute("SELECT * FROM pc_atomic_memory_idempotency").fetchall() + assert len(rows) == 2 + assert not any(key in str(value) for row in rows for value in row) + + asyncio.run(scenario()) + + +def test_replay_returns_creation_state_after_the_memory_changes(tmp_path: Path) -> None: + database = tmp_path / "state.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + first = await _remember(client, scope_id, "Deploy on Tuesdays", "deploy-day") + assert first.status_code == 200, first.text + record = first.json()["records"][0] + forgotten = await client.post( + "/v1/atomic-memory/lifecycle", + json={ + "scope_id": scope_id, + "target": {"artifact": record["artifact"], "state_version": record["state_version"]}, + "state": "forgotten", + }, + ) + assert forgotten.status_code == 200, forgotten.text + replayed = await _remember(client, scope_id, "Deploy on Tuesdays", "deploy-day") + assert replayed.status_code == 200, replayed.text + assert replayed.json() == first.json() + assert _memories(database) == 1 + + asyncio.run(scenario()) + + +def test_reused_key_with_different_content_conflicts_without_writing(tmp_path: Path) -> None: + database = tmp_path / "conflict.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + first = await _remember(client, scope_id, "Use pnpm", "tooling") + assert first.status_code == 200, first.text + memories, sources = _memories(database), _sources(database) + for text, fields in ( + ("Use npm", {}), + ("Use pnpm", {"kind": "fact"}), + ("Use pnpm", {"description": "Package manager choice"}), + ): + conflict = await _remember(client, scope_id, text, "tooling", **fields) + assert conflict.status_code == 409, conflict.text + error = conflict.json()["error"] + assert error["code"] == "idempotency_conflict" + assert error["details"] == {"kind": "memory_idempotency_key"} + assert (_memories(database), _sources(database)) == (memories, sources) + replayed = await _remember(client, scope_id, "Use pnpm", "tooling") + assert replayed.json() == first.json() + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("key", ["", "has space", "tab\tkey", "é", "k" * 257]) +def test_invalid_key_is_rejected_before_any_write(tmp_path: Path, key: str) -> None: + database = tmp_path / "invalid.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + before = _sources(database) + rejected = await _remember(client, scope_id, "Never stored", key) + assert rejected.status_code == 422, rejected.text + assert rejected.json()["error"]["code"] == "invalid_request" + assert (_memories(database), _sources(database)) == (0, before) + + asyncio.run(scenario()) + + +def test_in_process_create_applies_the_same_key_rule() -> None: + async def scenario() -> None: + async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime: + assert runtime.scopes is not None and runtime.atomic_memory is not None + scope = await runtime.scopes.create(ScopeDraft(title="Keys", summary="SDK keys", idempotency_key="keys")) + memory = runtime.atomic_memory.for_scope(scope.scope_id) + content = (AtomicMemoryContent(kind="preference", text="Use pnpm"),) + for key in ("", "has space", "é", "k" * 257): + with pytest.raises(InvalidBaseAccessRequestError): + await memory.create(content, idempotency_key=key) + assert (await memory.list()).items == () + first = await memory.create(content, idempotency_key="sdk-1") + assert await memory.create(content, idempotency_key="sdk-1") == first + + asyncio.run(scenario()) + + +def test_in_process_keys_share_one_namespace_without_access_control() -> None: + """A context that names a principal but carries no access service does not split the namespace.""" + from powercontext.artifacts.search import ArtifactSearchExecutionContext + + async def scenario() -> None: + async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime: + assert runtime.scopes is not None and runtime.atomic_memory is not None + scope = await runtime.scopes.create(ScopeDraft(title="Keys", summary="SDK keys", idempotency_key="keys")) + memory = runtime.atomic_memory.for_scope(scope.scope_id) + content = (AtomicMemoryContent(kind="preference", text="Use pnpm"),) + named = ArtifactSearchExecutionContext(principal=PrincipalRef(type="user", id="alice"), trusted_local=True) + + first = await memory.create(content, idempotency_key="shared") + assert await memory.create(content, idempotency_key="shared", context=named) == first + assert len((await memory.list()).items) == 1 + with pytest.raises(BaseValueConflictError): + other = (AtomicMemoryContent(kind="preference", text="Use npm"),) + await memory.create(other, idempotency_key="shared", context=named) + + asyncio.run(scenario()) + + +def test_keyed_request_keeps_expected_revision_rejection(tmp_path: Path) -> None: + database = tmp_path / "expected.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + unkeyed = await _remember(client, scope_id, "Never stored", expected_revision=1) + keyed = await _remember(client, scope_id, "Never stored", "precondition", expected_revision=1) + assert unkeyed.status_code != 200 + assert (keyed.status_code, keyed.json()["error"]["code"]) == ( + unkeyed.status_code, + unkeyed.json()["error"]["code"], + ) + assert _memories(database) == 0 + assert _count(database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency") == 0 + + asyncio.run(scenario()) + + +def test_expired_key_starts_a_new_creation_and_cleanup_is_bounded(tmp_path: Path) -> None: + database = tmp_path / "expiry.db" + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + first = await _remember(client, scope_id, "Prefer short PRs", "expiring") + assert first.status_code == 200, first.text + live = await _remember(client, scope_id, "Prefer squash merges", "still-live") + assert live.status_code == 200, live.text + with closing(sqlite3.connect(database)) as connection: + expiring = connection.execute( + "SELECT * FROM pc_atomic_memory_idempotency WHERE artifact_id = ?", + (first.json()["records"][0]["artifact"]["artifact_id"],), + ).fetchone() + connection.execute("UPDATE pc_atomic_memory_idempotency SET expires_at = '2000-01-01 00:00:00.000000'") + connection.execute( + "UPDATE pc_atomic_memory_idempotency SET expires_at = '2999-01-01 00:00:00.000000' WHERE artifact_id = ?", + (live.json()["records"][0]["artifact"]["artifact_id"],), + ) + for index in range(40): + connection.execute( + "INSERT INTO pc_atomic_memory_idempotency VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + (f"{index:064x}", *expiring[1:7], "2000-01-01 00:00:00.000000", "2000-01-01 00:00:00.000000"), + ) + connection.commit() + expired_before = _count( + database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency WHERE expires_at < '2001-01-01 00:00:00'" + ) + + recreated = await _remember(client, scope_id, "Prefer short PRs", "expiring") + assert recreated.status_code == 200, recreated.text + recreated_id = recreated.json()["records"][0]["artifact"]["artifact_id"] + assert recreated_id != first.json()["records"][0]["artifact"]["artifact_id"] + assert (await _remember(client, scope_id, "Prefer short PRs", "expiring")).json() == recreated.json() + assert (await _remember(client, scope_id, "Prefer squash merges", "still-live")).json() == live.json() + + expired_after = _count( + database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency WHERE expires_at < '2001-01-01 00:00:00'" + ) + assert expired_before == 41 + # The recreation replaced its own expired key, and its cleanup removed part of the + # other backlog: a bounded batch, not a full scan. + assert 0 < expired_after < expired_before - 1 + assert ( + _count( + database, + "SELECT COUNT(*) FROM pc_atomic_memory_idempotency WHERE expires_at > '2001-01-01 00:00:00'", + ) + == 2 + ) + + asyncio.run(scenario()) + + +def test_concurrent_keyed_requests_create_exactly_once(tmp_path: Path, monkeypatch) -> None: + database = tmp_path / "race.db" + original = AtomicMemoryManagementWriter.prepare_creates + + async def scenario() -> None: + async with _open(database) as client: + scope_id = await _default_scope(client) + barrier = asyncio.Barrier(3) + + async def prepare_together(self, *args, **kwargs): + # Every request has missed the lookup before any of them writes. + await barrier.wait() + return await original(self, *args, **kwargs) + + monkeypatch.setattr(AtomicMemoryManagementWriter, "prepare_creates", prepare_together) + responses = await asyncio.gather(*(_remember(client, scope_id, "Race once", "race") for _ in range(3))) + assert [response.status_code for response in responses] == [200, 200, 200], [r.text for r in responses] + assert responses[0].json() == responses[1].json() == responses[2].json() + assert _memories(database) == 1 + assert _count(database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency") == 1 + + asyncio.run(scenario()) + + +def _remember_in_process(database: str, scope_id: str, text: str, barrier, results) -> None: + async def run() -> None: + original = AtomicMemoryManagementWriter.prepare_creates + + async def prepare_together(self, *args, **kwargs): + await asyncio.to_thread(barrier.wait, 120) + return await original(self, *args, **kwargs) + + AtomicMemoryManagementWriter.prepare_creates = prepare_together + async with _open(Path(database)) as client: + response = await _remember(client, scope_id, text, "cross-process") + results.put((response.status_code, response.json())) + + asyncio.run(run()) + + +@pytest.mark.parametrize("texts", [("Same body",) * 3, ("Body A", "Body B", "Body A")], ids=["same", "mixed"]) +def test_keyed_requests_from_separate_processes_create_exactly_once(tmp_path: Path, texts) -> None: + database = tmp_path / "processes.db" + + async def prepare() -> str: + async with _open(database) as client: + return await _default_scope(client) + + scope_id = asyncio.run(prepare()) + context = multiprocessing.get_context("spawn") + barrier = context.Barrier(len(texts)) + results = context.Queue() + workers = [ + context.Process(target=_remember_in_process, args=(str(database), scope_id, text, barrier, results)) + for text in texts + ] + for worker in workers: + worker.start() + outcomes = [results.get(timeout=300) for _ in workers] + for worker in workers: + worker.join(timeout=60) + assert worker.exitcode == 0 + assert _memories(database) == 1 + succeeded = [body for status, body in outcomes if status == 200] + assert succeeded and all(body == succeeded[0] for body in succeeded) + winner = succeeded[0]["records"][0]["text"] + assert len(succeeded) == texts.count(winner) + conflicts = [body for status, body in outcomes if status != 200] + assert len(conflicts) == len(texts) - texts.count(winner) + assert all(body["error"]["details"] == {"kind": "memory_idempotency_key"} for body in conflicts) + + +class _Authentication: + async def authenticate(self, request): + identity = request.headers.get("authorization", "Bearer admin").removeprefix("Bearer ") + return AuthenticationResult(subject=ADMIN if identity == "admin" else PrincipalRef(type="user", id=identity)) + + async def readiness(self): + return ProviderReadiness(ready=True) + + +async def _grant(client: httpx.AsyncClient, scope_id: str, principal: str) -> dict[str, Any]: + response = await client.post( + "/v1/access/bindings/create", + json={ + "subject": {"type": "user", "id": principal}, + "resource": {"type": "scope", "scope_id": scope_id}, + "role": "scope.contributor", + "idempotency_key": f"{principal}-contributor", + }, + ) + assert response.status_code == 201, response.text + return response.json() + + +def test_access_controlled_keys_are_per_principal_and_replays_reauthorize(tmp_path: Path) -> None: + database = tmp_path / "access.db" + + async def scenario() -> None: + server_settings = _settings( + database, + runtime=RuntimeConfig(artifact_processing_families=()), + access=AccessControlConfig(mode="enforced", deployment_id="idempotency"), + ) + await asyncio.to_thread(prepare_server_database, server_settings) + async with open_builtin_access_control( + server_settings.database, bootstrap_administrators=(ADMIN,), deployment_id="idempotency" + ) as access: + app = create_server_app( + settings=server_settings, + authentication_provider=_Authentication(), + access_control=access, + scheduler_path=tmp_path / "scheduler.db", + ) + async with ( + app.router.lifespan_context(app), + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, + ): + created = await client.post( + "/v1/scopes", json={"title": "Keys", "summary": "Idempotent writes", "idempotency_key": "keys"} + ) + assert created.status_code == 201, created.text + scope_id = created.json()["scope_id"] + alice_grant = await _grant(client, scope_id, "alice") + await _grant(client, scope_id, "bob") + alice = {"Authorization": "Bearer alice"} + bob = {"Authorization": "Bearer bob"} + body = {"scope_id": scope_id, "kind": "note", "text": "Private plan", "idempotency_key": "shared"} + + first = await client.post("/v1/memory/remember", json=body, headers=alice) + assert first.status_code == 200, first.text + again = await client.post("/v1/memory/remember", json=body, headers=alice) + assert again.json() == first.json() + other = await client.post("/v1/memory/remember", json=body, headers=bob) + assert other.status_code == 200, other.text + assert other.json()["records"][0]["artifact"] != first.json()["records"][0]["artifact"] + + invalid = await client.post( + "/v1/memory/remember", json={**body, "idempotency_key": "bad key"}, headers=alice + ) + assert invalid.status_code == 422 + assert invalid.json()["error"]["code"] in {"invalid_request", "invalid_access_request"} + + revoked = await client.post( + "/v1/access/bindings/revoke", + json={ + "binding_id": alice_grant["binding_id"], + "expected_version": alice_grant["version"], + "idempotency_key": "revoke-alice", + }, + ) + assert revoked.status_code == 200, revoked.text + denied = await client.post("/v1/memory/remember", json=body, headers=alice) + assert denied.status_code == 403 + assert "Private plan" not in denied.text + assert _memories(database) == 2 + + with closing(sqlite3.connect(database)) as connection: + rows = connection.execute("SELECT * FROM pc_atomic_memory_idempotency").fetchall() + assert len(rows) == 2 + assert not any( + secret in str(value) for row in rows for value in row for secret in ("shared", "alice", "bob") + ) + + asyncio.run(scenario()) + + +def test_in_process_keyed_create_requires_current_scope_contribution(tmp_path: Path) -> None: + """A revoked contributor learns neither a replay nor a conflict from an old key.""" + from powercontext.artifacts.search import ArtifactSearchExecutionContext + from powercontext.builtin.authz import AccessAuditContext, AccessDeniedError + + database = tmp_path / "in-process-access.db" + + async def scenario() -> None: + server_settings = _settings( + database, + runtime=RuntimeConfig(artifact_processing_families=()), + access=AccessControlConfig(mode="enforced", deployment_id="idempotency"), + ) + await asyncio.to_thread(prepare_server_database, server_settings) + async with open_builtin_access_control( + server_settings.database, bootstrap_administrators=(ADMIN,), deployment_id="idempotency" + ) as access: + app = create_server_app( + settings=server_settings, + authentication_provider=_Authentication(), + access_control=access, + scheduler_path=tmp_path / "scheduler.db", + ) + async with ( + app.router.lifespan_context(app), + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, + ): + created = await client.post( + "/v1/scopes", json={"title": "Keys", "summary": "Idempotent writes", "idempotency_key": "keys"} + ) + assert created.status_code == 201, created.text + scope_id = created.json()["scope_id"] + grant = await _grant(client, scope_id, "alice") + memory = app.state.application.atomic_memory.for_scope(scope_id) + context = ArtifactSearchExecutionContext( + principal=PrincipalRef(type="user", id="alice"), + access=access, + audit=AccessAuditContext(transport="http", operation="test"), + ) + content = AtomicMemoryContent(kind="note", text="Private plan") + + first = await memory.create((content,), idempotency_key="in-process", context=context) + replayed = await memory.create((content,), idempotency_key="in-process", context=context) + assert replayed.records[0].artifact == first.records[0].artifact + assert _memories(database) == 1 + + revoked = await client.post( + "/v1/access/bindings/revoke", + json={ + "binding_id": grant["binding_id"], + "expected_version": grant["version"], + "idempotency_key": "revoke-alice", + }, + ) + assert revoked.status_code == 200, revoked.text + other = AtomicMemoryContent(kind="note", text="Different plan") + for value, key in ((content, "in-process"), (other, "in-process"), (content, "unused")): + with pytest.raises(AccessDeniedError): + await memory.create((value,), idempotency_key=key, context=context) + assert _memories(database) == 1 + assert _count(database, "SELECT COUNT(*) FROM pc_atomic_memory_idempotency") == 1 + + asyncio.run(scenario()) + + +def test_untrusted_in_process_context_cannot_probe_an_occupied_key() -> None: + """An explicit context that is neither access-controlled nor trusted local is denied before any lookup.""" + from powercontext.artifacts.search import ArtifactSearchExecutionContext + from powercontext.builtin.authz import AccessDeniedError + + async def scenario() -> None: + async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime: + assert runtime.scopes is not None and runtime.atomic_memory is not None + scope = await runtime.scopes.create(ScopeDraft(title="Keys", summary="SDK keys", idempotency_key="keys")) + memory = runtime.atomic_memory.for_scope(scope.scope_id) + content = (AtomicMemoryContent(kind="preference", text="Use pnpm"),) + other = (AtomicMemoryContent(kind="preference", text="Use npm"),) + await memory.create(content, idempotency_key="known") + + untrusted = ArtifactSearchExecutionContext() + for value, key in ((content, None), (content, "unused"), (content, "known"), (other, "known")): + with pytest.raises(AccessDeniedError): + await memory.create(value, idempotency_key=key, context=untrusted) + assert len((await memory.list()).items) == 1 + + asyncio.run(scenario()) diff --git a/tests/e2e/test_runtime_server.py b/tests/e2e/test_runtime_server.py index cf45872dff..ea638fb71a 100644 --- a/tests/e2e/test_runtime_server.py +++ b/tests/e2e/test_runtime_server.py @@ -1397,7 +1397,9 @@ def test_runtime_server_keeps_unstructured_memory_errors_private( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: - async def invalid_create(_self: ScopedAtomicMemoryApplication, _contents: object, /, *, context=None) -> None: + async def invalid_create( + _self: ScopedAtomicMemoryApplication, _contents: object, /, *, context=None, idempotency_key=None + ) -> None: raise InvalidMemoryCandidateError("canonical", "private implementation detail") monkeypatch.setattr(ScopedAtomicMemoryApplication, "create", invalid_create) diff --git a/tests/e2e/test_source_citation_locators.py b/tests/e2e/test_source_citation_locators.py index 637842a219..ea5a1e01fe 100644 --- a/tests/e2e/test_source_citation_locators.py +++ b/tests/e2e/test_source_citation_locators.py @@ -82,11 +82,12 @@ def test_locators_survive_upgrade_reopen_http_and_mcp(tmp_path): for statement in retired["statements"]: connection.execute(statement) connection.execute("DROP TABLE pc_artifact_source_locators") + connection.execute("DROP TABLE pc_atomic_memory_idempotency") connection.execute("UPDATE pc_schema_revision SET version_num = 'v1_5_0_003'") runner = deployment_runner(_settings(database)) plan = runner.plan() - assert plan.revisions == ("v1_5_0_004", "v1_5_0_005", "v1_5_0_006", "v1_6_0") + assert plan.revisions == ("v1_5_0_004", "v1_5_0_005", "v1_5_0_006", "v1_6_0", "000") runner.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True) locators = [ diff --git a/tests/native/test_oceanbase_engine_recovery.py b/tests/native/test_oceanbase_engine_recovery.py index e30fef4ffc..68b1249651 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_6_0" and result.readiness_scope == "server" + assert result.state == "ready" and result.revision == "000" 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/pydantic_ai_adapter/test_toolset.py b/tests/pydantic_ai_adapter/test_toolset.py index e7f6e484ac..9a80b29817 100644 --- a/tests/pydantic_ai_adapter/test_toolset.py +++ b/tests/pydantic_ai_adapter/test_toolset.py @@ -98,6 +98,7 @@ async def scenario() -> Any: "reason": "shared contract", "expected_revision": None, "description": None, + "idempotency_key": None, } assert "assembly" not in client.prepare_requests[0].model_fields_set assert client.prepare_requests[0].model_dump(mode="json", exclude_unset=True) == { diff --git a/tests/test_managed_atomic_maintenance.py b/tests/test_managed_atomic_maintenance.py index faa57369ba..9257751143 100644 --- a/tests/test_managed_atomic_maintenance.py +++ b/tests/test_managed_atomic_maintenance.py @@ -76,7 +76,7 @@ def test_atomic_alias_upgrades_complete_historical_server_with_shared_plan_and_b assert inspected.exit_code == 0, inspected.output plan = json.loads(inspected.output) assert plan["source_revision"] == "s1300" - assert plan["target_revision"] == "v1_6_0" + assert plan["target_revision"] == "000" assert plan["readiness_scope"] == "server" assert historical.read_bytes() == original @@ -103,7 +103,7 @@ def test_atomic_alias_upgrades_complete_historical_server_with_shared_plan_and_b with closing(sqlite3.connect(result["backup_ref"])) as connection: assert tuple(connection.iterdump()) == original_dump with closing(sqlite3.connect(historical)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_6_0",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("000",)] assert connection.execute("SELECT content FROM pc_artifacts").fetchall() == [(b'{"history":"unchanged"}',)] verified = CliRunner().invoke(cli, [*arguments, "--action", "verify"]) assert verified.exit_code == 0, verified.output diff --git a/tests/test_managed_processing_maintenance.py b/tests/test_managed_processing_maintenance.py index 5eb8672654..477757fb3f 100644 --- a/tests/test_managed_processing_maintenance.py +++ b/tests/test_managed_processing_maintenance.py @@ -75,7 +75,7 @@ def test_registered_mode_switch_backs_up_preserves_revision_and_fences_old_worke assert result.backup_state == "completed" assert result.backup_ref and Path(result.backup_ref).is_file() with closing(sqlite3.connect(path)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_6_0",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("000",)] assert ( json.loads(connection.execute("SELECT config_manifest FROM pc_artifact_processing_schema").fetchone()[0])[ "mode" diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 7dc181dd89..50004b4c28 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -47,7 +47,8 @@ async def inspect() -> tuple[str, list[Any]]: assert guidance names = {tool.name for tool in tools} referenced_names = set(re.findall(r"\b[a-z]+(?:_[a-z]+)+\b", guidance)) - assert referenced_names - {"state_version", "merged_into_id", "expected_revision", "status_code"} <= names + fields = {"state_version", "merged_into_id", "expected_revision", "status_code", "idempotency_key"} + assert referenced_names - fields - {"idempotency_conflict"} <= names if directory := os.environ.get("POWERCONTEXT_GUIDANCE_EXPORT"): root = Path(__file__).parents[1] for host in ("codex", "claude-code", "workbuddy", "agent-plugin", "minimax"): diff --git a/tests/test_migration_revision_names.py b/tests/test_migration_revision_names.py index 4b73c485e1..9472e39110 100644 --- a/tests/test_migration_revision_names.py +++ b/tests/test_migration_revision_names.py @@ -71,9 +71,10 @@ def invoke(action, *options): "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", ] assert [item["revision"] for item in plan["pending_migrations"]] == list(reviewed.revisions) - target = {"revision": "v1_6_0", "name": "v1_6_0", "software_version": "1.6.0", "sequence": None} + target = {"revision": "000", "name": "000", "software_version": None, "sequence": None} assert plan["target_migration"] == target applied = invoke( @@ -88,7 +89,7 @@ def invoke(action, *options): ) assert applied["migration"] == target and applied["server_ready"] with closing(sqlite3.connect(runner.database)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_6_0",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("000",)] evidence = runner.evidence_path.read_bytes() recorded = json.loads(evidence) assert recorded["source_revision"] == expected_source["revision"] @@ -107,6 +108,7 @@ def invoke(action, *options): "v1_5_0_005", "v1_5_0_006", "v1_6_0", + "000", } assert runner.verify().state == "ready" assert invoke("verify")["migration"] == target diff --git a/tests/test_registered_source_maintenance_cli.py b/tests/test_registered_source_maintenance_cli.py index f916761b0a..af48777ff0 100644 --- a/tests/test_registered_source_maintenance_cli.py +++ b/tests/test_registered_source_maintenance_cli.py @@ -66,7 +66,7 @@ def test_release140_compatibility_commands_preserve_source_and_share_full_upgrad planned = CliRunner().invoke(cli, [*arguments, "plan", "--backup", "skip"]) assert planned.exit_code == 0, planned.output plan = json.loads(planned.output) - assert plan["source_revision"] == "r1400" and plan["target_revision"] == "v1_6_0" + assert plan["source_revision"] == "r1400" and plan["target_revision"] == "000" assert plan["readiness_scope"] == "server" assert plan["compatibility_steps"] == [] full = CliRunner().invoke(cli, ["server", "db-migrate", "plan", "--backup", "skip"])