Repository navigation
feat(memory): persist versioned Source evidence and neutral Atomic Memory projection #2004
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
AlexStocks
merged 42 commits into
oceanbase:master
from
MaoMengww:feature/1975-source-evidence-declarations
Nov 4, 2026
Merged
Changes from 7 commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
8439875
feat(memory): persist versioned source evidence
MaoMengww 5dfa2ad
feat(memory): verify historical evidence during projection rebuild
MaoMengww 034e0cc
fix(memory): enforce evidence schema safety and backend conformance
MaoMengww 4d1bf17
fix(memory): preserve unrelated database inspection
MaoMengww cf8068a
test(memory): consolidate source evidence E2E acceptance
MaoMengww dd1d128
merge: integrate upstream artifact handles with evidence migration
MaoMengww 0d70cba
fix(memory): verify evidence against retained source material
MaoMengww 3305b6b
fix(sources): align remote payload aliases with manifests
MaoMengww c9ee82d
fix(sources): preserve envelope keys with alias generators
MaoMengww dc9b6a1
fix(sources): align envelope validation with serialization
MaoMengww 8ee3aba
fix(memory): preserve source identity and shared evidence
MaoMengww 6a836b1
fix(sqlite): preserve startup catalog compatibility
MaoMengww b5a4c1e
fix(sources): keep unverifiable evidence neutral
MaoMengww 40d6c80
Merge upstream master into source evidence declarations
MaoMengww 2bce54e
fix(sources): reject omitted identity before capture
MaoMengww bb36c93
fix(sources): reject transformed identity before capture
MaoMengww 88cd8f2
Merge upstream master into source evidence declarations
MaoMengww 73ec5aa
fix(sources): separate worker and historical identity decoding
MaoMengww 25d9e7a
fix(sources): disambiguate canonical history from business aliases
MaoMengww 5ceed57
fix(sources): normalize recursive transport root schemas
MaoMengww f4ca7f8
merge: integrate upstream retrieval lifecycle validation
MaoMengww 2b95df6
fix(sources): preserve versioned alias compatibility
MaoMengww 13517fd
fix(sources): keep upgraded alias definitions compatible
MaoMengww 3c5c0ec
merge: sync upstream master and refresh the atomic maintenance baseline
MaoMengww 3a8b38b
fix(sources): preserve stable remote manifest fingerprints
MaoMengww 4a7f41f
merge: sync upstream master and preserve nullable nested manifests
MaoMengww 457e3f5
Merge remote-tracking branch 'upstream/master' into feature/1975-sour…
MaoMengww 95c1536
fix(portability): preserve accepted evidence in portable archives
MaoMengww fa71650
merge: sync upstream master and register Source evidence tables
MaoMengww 6b20c38
merge: sync upstream and preserve migration revision checksums
MaoMengww d215c98
feat(memory): add rebuildable source evidence projection
MaoMengww 34c5276
fix(memory): persist versioned Source evidence and close review findings
MaoMengww 93ca5df
merge: sync upstream master and preserve source evidence upgrade decl…
MaoMengww 08a4386
ci(e2e): budget the six Server recovery scenarios
MaoMengww 5da4f75
merge: sync upstream master and preserve evidence migrations
MaoMengww 8444f08
fix(persistence,sources): keep accepted manifests and MySQL-family ev…
MaoMengww 6d5ca48
merge: sync upstream master and chain evidence after source write plu…
MaoMengww 9e1a47b
merge: sync upstream master and chain evidence after artifact storage
MaoMengww 4e9dd0f
merge: sync upstream validation consolidation and keep evidence review
MaoMengww ff88ee0
merge: sync upstream master and keep evidence-aware migration gates
MaoMengww c9cede7
fix(migrations): align evidence gates with upstream CI
MaoMengww ed62759
merge: sync upstream ownership migration and preserve evidence review
MaoMengww File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
211 changes: 211 additions & 0 deletions
211
src/powercontext/builtin/persistence/atomic_memory_evidence.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| # 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. | ||
|
|
||
| """Immutable per-revision evidence inputs and their neutral internal annotation.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from collections.abc import Sequence | ||
| from typing import Literal | ||
|
|
||
| import rfc8785 | ||
| from aiosqlite import Connection as SQLiteConnection | ||
| from pydantic import BaseModel, ConfigDict, ValidationError | ||
| from sqlalchemy import insert, select | ||
| from sqlalchemy.exc import IntegrityError | ||
| from sqlalchemy.ext.asyncio import AsyncConnection | ||
|
|
||
| from powercontext.artifacts import ArtifactRef | ||
| from powercontext.builtin.persistence.atomic_memory_evidence_schema import ATOMIC_MEMORY_EVIDENCE_HISTORY_TABLE | ||
| from powercontext.builtin.persistence.sources import SourceRepository, _require_identity | ||
| from powercontext.limits import MAX_SCOPE_ID_LENGTH | ||
| from powercontext.sources import SourceRef | ||
| from powercontext.sources.evidence import MemoryEvidenceDeclaration, SourceEvidence | ||
|
|
||
|
|
||
| class AtomicMemoryEvidenceAnnotation(BaseModel): | ||
| """Exact revision facts, not a trust score or recursively inferred evidence.""" | ||
|
|
||
| model_config = ConfigDict(extra="forbid", frozen=True) | ||
|
|
||
| scope_id: str | ||
| artifact_ref: ArtifactRef | ||
| sources: tuple[SourceEvidence, ...] | ||
| format: Literal["powercontext.atomic-memory.evidence.v1"] = "powercontext.atomic-memory.evidence.v1" | ||
|
|
||
|
|
||
| class AtomicMemoryEvidenceRepository: | ||
| """Join caller transactions; retained inputs are never deleted with the index. | ||
|
|
||
| The annotation is derived from retained inputs at read time. There is no | ||
| separate cache to confuse with accepted history or join into search. | ||
| """ | ||
|
|
||
| async def save( | ||
| self, | ||
| connection: AsyncConnection, | ||
| scope_id: str, | ||
| artifact_ref: ArtifactRef, | ||
| sources: Sequence[SourceEvidence], | ||
| ) -> AtomicMemoryEvidenceAnnotation: | ||
| artifact_ref = self._reference(scope_id, artifact_ref) | ||
| payload = await self._payload(connection, scope_id, artifact_ref) | ||
| if payload is not None: | ||
| return self._decode(scope_id, artifact_ref, payload) or self._neutral(scope_id, artifact_ref, sources) | ||
| accepted = [] | ||
| for source in sources: | ||
| value = source.model_dump(mode="json") | ||
| try: | ||
| declaration = MemoryEvidenceDeclaration.model_validate(value.get("declaration")) | ||
| except ValidationError: | ||
| declaration = MemoryEvidenceDeclaration() | ||
| accepted.append(SourceEvidence.model_validate({**value, "declaration": declaration})) | ||
| annotation = AtomicMemoryEvidenceAnnotation( | ||
| scope_id=scope_id, artifact_ref=artifact_ref, sources=tuple(accepted) | ||
| ) | ||
| if connection.dialect.name == "sqlite": | ||
| driver = (await connection.get_raw_connection()).driver_connection | ||
| if isinstance(driver, SQLiteConnection) and not driver.in_transaction: | ||
| # SQLite legacy transaction mode does not BEGIN on SELECT; | ||
| # SAVEPOINT must not accidentally own and commit the write. | ||
| await connection.exec_driver_sql("BEGIN") | ||
| try: | ||
| async with connection.begin_nested(): | ||
| await connection.execute( | ||
| insert(ATOMIC_MEMORY_EVIDENCE_HISTORY_TABLE).values( | ||
| scope_id=scope_id, | ||
| artifact_id=artifact_ref.artifact_id, | ||
| revision=artifact_ref.revision, | ||
| sources=rfc8785.dumps([source.model_dump(mode="json") for source in annotation.sources]), | ||
| ) | ||
| ) | ||
| except IntegrityError: | ||
| payload = await self._payload(connection, scope_id, artifact_ref) | ||
| if payload is None: | ||
| raise | ||
| return self._decode(scope_id, artifact_ref, payload) or self._neutral(scope_id, artifact_ref, sources) | ||
| return annotation | ||
|
|
||
| async def read( | ||
| self, connection: AsyncConnection, scope_id: str, artifact_ref: ArtifactRef | ||
| ) -> AtomicMemoryEvidenceAnnotation | None: | ||
| artifact_ref = self._reference(scope_id, artifact_ref) | ||
| payload = await self._payload(connection, scope_id, artifact_ref) | ||
| return None if payload is None else self._decode(scope_id, artifact_ref, payload) | ||
|
|
||
| async def verify( | ||
| self, | ||
| connection: AsyncConnection, | ||
| scope_id: str, | ||
| artifact_ref: ArtifactRef, | ||
| source_refs: Sequence[SourceRef], | ||
| *, | ||
| sources: SourceRepository | None = None, | ||
| ) -> AtomicMemoryEvidenceAnnotation: | ||
| """Derive exact facts from retained inputs, never today's declarations. | ||
|
|
||
| Missing or damaged declaration records are neutral. Missing Sources, | ||
| corrupt authoritative payloads and unequal exact materials remain errors. | ||
| No accepted snapshot is saved or repaired by this operation. | ||
| """ | ||
|
|
||
| from powercontext.builtin.persistence.atomic_memory_index import AtomicMemoryIndexError | ||
| from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY | ||
|
|
||
| artifact_ref = self._reference(scope_id, artifact_ref) | ||
| repository = SourceRepository(BUILTIN_SOURCE_REGISTRY) if sources is None else sources | ||
| materials = await repository.historical_evidence(connection, scope_id, source_refs) | ||
| annotation = await self.read(connection, scope_id, artifact_ref) | ||
| if annotation is not None: | ||
| by_ref = {(item.source_ref.source_type, item.source_ref.source_id): item for item in materials} | ||
| for accepted in annotation.sources: | ||
| material = by_ref.get((accepted.source_ref.source_type, accepted.source_ref.source_id)) | ||
| if material is not None and accepted.material_digest != material.material_digest: | ||
| raise AtomicMemoryIndexError( | ||
| "evidence-material", "Historical evidence does not match the exact Source material" | ||
| ) | ||
| if annotation is None or tuple(item.source_ref for item in annotation.sources) != tuple( | ||
| item.source_ref for item in materials | ||
| ): | ||
| return self._neutral(scope_id, artifact_ref, materials) | ||
| verified = tuple( | ||
| accepted | ||
| if ( | ||
| accepted.materialization == material.materialization | ||
| and accepted.definition_name == material.definition_name | ||
| and accepted.definition_version == material.definition_version | ||
| and accepted.manifest_fingerprint == material.manifest_fingerprint | ||
| and accepted.declaration == material.declaration | ||
| ) | ||
| else accepted.model_copy(update={"declaration": MemoryEvidenceDeclaration()}) | ||
| for accepted, material in zip(annotation.sources, materials, strict=True) | ||
| ) | ||
| return annotation.model_copy(update={"sources": verified}) | ||
|
|
||
| @staticmethod | ||
| def _reference(scope_id: str, artifact_ref: ArtifactRef) -> ArtifactRef: | ||
| _require_identity("scope_id", scope_id, MAX_SCOPE_ID_LENGTH) | ||
| reference = ArtifactRef.model_validate(artifact_ref.model_dump()) | ||
| if reference.family != "atomic-memory": | ||
| from powercontext.builtin.persistence.errors import InvalidRepositoryArgumentError | ||
|
|
||
| raise InvalidRepositoryArgumentError("artifact_ref", "must reference an Atomic Memory revision") | ||
| return reference | ||
|
|
||
| @staticmethod | ||
| async def _payload(connection: AsyncConnection, scope_id: str, artifact_ref: ArtifactRef) -> object | None: | ||
| table = ATOMIC_MEMORY_EVIDENCE_HISTORY_TABLE | ||
| return await connection.scalar( | ||
| select(table.c.sources).where( | ||
| table.c.scope_id == scope_id, | ||
| table.c.artifact_id == artifact_ref.artifact_id, | ||
| table.c.revision == artifact_ref.revision, | ||
| ) | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _decode(scope_id: str, artifact_ref: ArtifactRef, payload: object) -> AtomicMemoryEvidenceAnnotation | None: | ||
| try: | ||
| if not isinstance(payload, (bytes, bytearray, memoryview)): | ||
| return None | ||
| values = json.loads(bytes(payload)) | ||
| if not isinstance(values, list): | ||
| return None | ||
| sources = [] | ||
| for value in values: | ||
| if not isinstance(value, dict): | ||
| return None | ||
| try: | ||
| declaration = MemoryEvidenceDeclaration.model_validate(value.get("declaration")) | ||
| except ValidationError: | ||
| declaration = MemoryEvidenceDeclaration() | ||
| sources.append(SourceEvidence.model_validate({**value, "declaration": declaration})) | ||
| return AtomicMemoryEvidenceAnnotation(scope_id=scope_id, artifact_ref=artifact_ref, sources=tuple(sources)) | ||
| except (ValueError, TypeError): | ||
| # An unreadable declaration snapshot conveys no historical claim. | ||
| # This does not catch SQL errors or actual Source resolution errors. | ||
| return None | ||
|
|
||
| @staticmethod | ||
| def _neutral( | ||
| scope_id: str, artifact_ref: ArtifactRef, sources: Sequence[SourceEvidence] | ||
| ) -> AtomicMemoryEvidenceAnnotation: | ||
| # Preserve a damaged row exactly, without replacing it with today's | ||
| # stronger configuration. A caller can only receive neutral facts. | ||
| return AtomicMemoryEvidenceAnnotation( | ||
| scope_id=scope_id, | ||
| artifact_ref=artifact_ref, | ||
| sources=tuple(source.model_copy(update={"declaration": MemoryEvidenceDeclaration()}) for source in sources), | ||
| ) |
59 changes: 59 additions & 0 deletions
59
src/powercontext/builtin/persistence/atomic_memory_evidence_schema.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| # 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. | ||
|
|
||
| """Retained exact-version evidence, independent of disposable search projections.""" | ||
|
|
||
| from sqlalchemy import BigInteger, CheckConstraint, Column, LargeBinary, Table, Text | ||
| from sqlalchemy.dialects.mysql import LONGBLOB, MEDIUMTEXT | ||
|
|
||
| from powercontext.builtin.persistence.tables import SHARED_METADATA, identity_string | ||
| from powercontext.limits import ( | ||
| MAX_ARTIFACT_ID_LENGTH, | ||
| MAX_SCOPE_ID_LENGTH, | ||
| MAX_SOURCE_ID_LENGTH, | ||
| MAX_SOURCE_TYPE_LENGTH, | ||
| ) | ||
|
|
||
| ATOMIC_MEMORY_EVIDENCE_SCHEMA_VERSION = "p0005" | ||
| ATOMIC_MEMORY_EVIDENCE_SCHEMA_TABLE = Table( | ||
| "pc_atomic_memory_evidence_schema", | ||
| SHARED_METADATA, | ||
| Column("schema_version", identity_string(32), primary_key=True), | ||
| ) | ||
| ATOMIC_MEMORY_EVIDENCE_HISTORY_TABLE = Table( | ||
| "pc_atomic_memory_evidence_history", | ||
|
MaoMengww marked this conversation as resolved.
Resolved
|
||
| SHARED_METADATA, | ||
| Column("scope_id", identity_string(MAX_SCOPE_ID_LENGTH), primary_key=True), | ||
| Column("artifact_id", identity_string(MAX_ARTIFACT_ID_LENGTH), primary_key=True), | ||
| Column("revision", BigInteger, primary_key=True), | ||
| Column("sources", LargeBinary().with_variant(LONGBLOB(), "mysql"), nullable=False), | ||
| CheckConstraint("revision > 0", name="ck_pc_atomic_memory_evidence_history_revision"), | ||
| ) | ||
| SOURCE_EVIDENCE_BINDINGS_TABLE = Table( | ||
| "pc_source_evidence_bindings", | ||
| SHARED_METADATA, | ||
| Column("scope_id", identity_string(MAX_SCOPE_ID_LENGTH), primary_key=True), | ||
| Column("source_type", identity_string(MAX_SOURCE_TYPE_LENGTH), primary_key=True), | ||
| Column("source_id", identity_string(MAX_SOURCE_ID_LENGTH), primary_key=True), | ||
| Column("material_digest", identity_string(71), nullable=False), | ||
| Column("definition_name", Text().with_variant(MEDIUMTEXT(), "mysql"), nullable=False), | ||
| Column("definition_version", Text().with_variant(MEDIUMTEXT(), "mysql"), nullable=False), | ||
| Column("manifest_fingerprint", identity_string(71)), | ||
| Column("declaration", LargeBinary().with_variant(LONGBLOB(), "mysql"), nullable=False), | ||
| ) | ||
| ATOMIC_MEMORY_EVIDENCE_TABLES = ( | ||
| ATOMIC_MEMORY_EVIDENCE_SCHEMA_TABLE, | ||
| ATOMIC_MEMORY_EVIDENCE_HISTORY_TABLE, | ||
| SOURCE_EVIDENCE_BINDINGS_TABLE, | ||
| ) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.