diff --git a/docs/evaluation/resolution-projection-integrity-20261025.md b/docs/evaluation/resolution-projection-integrity-20261025.md new file mode 100644 index 00000000..cc81b3d3 --- /dev/null +++ b/docs/evaluation/resolution-projection-integrity-20261025.md @@ -0,0 +1,70 @@ +# Version-bound duplicate-resolution overlays + +A source/member fingerprint can consistently describe bytes that were already +corrupted before a review started. Before this change, a changed stored body could +receive a fresh preview and an accepted display-resolution decision under the old +version ID. Changing only `projection_sha256` could also leave an active overlay +projecting as current. Both failures were reproduced through the public +`resolution_action` API in an isolated synthetic store; no production source was +changed. Three new regression methods failed in seven subcases on the baseline. + +`alden_entity_resolution._source_rows` now checks the same v3 construction as the +source-detail reader: SHA-256 of the exact stored label, body and metadata excluding +`source`, followed by the version identity derived from document ID, raw digest, +processing version and that projection digest. It validates the digest and version +before returning a preview, on apply preflight, again inside `BEGIN IMMEDIATE`, and +when testing the validity of an existing overlay. The new failure is +`collection_resolution_projection_integrity`. Existing raw-record, project/native +permission, journal, member, relation, revision and request-ID guards remain. + +The safety promise is that a mismatched v3 tuple cannot produce a new accepted +preview/decision or a currently projected overlay. It is not semantic duplicate +classification, database authentication against an attacker who rewrites all +supporting state, or a proof that accepted facts are true. Migrated `legacy` rows +with an empty projection field retain their existing compatibility contract; their +v3 projection integrity is unavailable. Mixed legacy/nonempty-projection fields +are rejected. No old source, version, decision, schema or receipt is rewritten. + +```mermaid +stateDiagram-v2 + [*] --> CurrentSource + CurrentSource --> Preview: project, source, projection, journal and relation guards + Preview --> ApplyPreflight: explicit user decision and fresh request + ApplyPreflight --> WriteTransaction: lock and optional recovery backup + WriteTransaction --> Decision: recheck guards inside BEGIN IMMEDIATE and commit + Decision --> Projected: current member/projection/provenance guards pass + Decision --> Suppressed: source projection no longer matches version + Suppressed --> Projected: original exact source tuple restored + Decision --> HistoricalReceipt: same accepted request ID replayed + Suppressed --> HistoricalReceipt: same accepted request ID replayed + Decision --> Reverted: explicit revert with current resolution revision + Suppressed --> Reverted: explicit revert with current resolution revision + CurrentSource --> Rejected: projection/version mismatch + ApplyPreflight --> Rejected: mismatch or stale authority + WriteTransaction --> Rejected: mismatch after preflight, transaction rolls back +``` + +The chart projects separate code boundaries; the preflight and backup are not +atomic with the write transaction. The late-change regression mutates only the +synthetic projection field after preflight/backup, then reaches the actual second +guard inside the write transaction. No feature tables or decision survive that +rejection. Another regression restores the exact synthetic field and verifies that +the same original decision becomes eligible without a second apply. Request replay +returns a historical receipt and does not reactivate an invalid projection. +Changing metadata's intentionally excluded `source` field still changes the member +fingerprint, so stale plans remain rejected while fresh legitimate previews work. + +This is bounded real-code regression evidence, not an exhaustive model check, +all-input theorem, liveness/fairness proof or whole-project correctness result. +The affected tests also exercise apply/revert/replay, project unions, permissions, +source/edge preservation and quality comparisons. Relevant command: + +```sh +python3 -B -m unittest tests.test_alden_entity_integrity tests.test_alden_entity_resolution tests.test_alden_entity_projection tests.test_alden_entity_union_review tests.test_alden_graph_quality_action -v +``` + +Current-data observations, source hashes, exact negative/positive logs, installation +and runtime readback belong in the task's `outputs/graph-current-integrity-20261025` +delivery. No semantic grouping or production merge follows from the read-only +audit. External current-source Pro/Gemini/reverse review remains incomplete under +the preserved upload gate; local tests and this chart do not replace it. diff --git a/scripts/alden_entity_resolution.py b/scripts/alden_entity_resolution.py index d31bc9f8..e4225d57 100644 --- a/scripts/alden_entity_resolution.py +++ b/scripts/alden_entity_resolution.py @@ -185,7 +185,7 @@ def _source_rows(db, store, project, members, *, read_blobs, show_records, inclu row = db.execute("""SELECT m.current_version,m.availability AS membership_availability, d.availability AS document_availability,d.platform,d.original_id, v.document_id AS version_document_id,v.raw_sha256,v.raw_path,v.label,v.body, - v.metadata,v.collected_at,p.permission + v.metadata,v.collected_at,v.processing_version,v.projection_sha256,p.permission FROM memberships m JOIN documents d ON d.id=m.document_id LEFT JOIN versions v ON v.id=m.current_version LEFT JOIN target_projects p ON p.target_id=m.target_id AND p.project=? @@ -225,6 +225,25 @@ def _source_rows(db, store, project, members, *, read_blobs, show_records, inclu raise RuntimeError("collection_resolution_metadata_integrity") from error if not isinstance(metadata, dict): raise RuntimeError("collection_resolution_metadata_integrity") + # A stable fingerprint of already corrupted bytes is not evidence that + # those bytes belong to this immutable version. Use the same v3 binding + # as the source-detail reader before preview, apply, or active projection. + if (not all(isinstance(row[key], str) for key in + ('label', 'body', 'raw_sha256', 'processing_version', 'projection_sha256')) + or not row['processing_version']): + raise RuntimeError('collection_resolution_projection_integrity') + if row['processing_version'] == 'legacy': + # Migrated v1/v2 rows have no v3 projection digest. Preserve their + # existing read contract while rejecting mixed legacy/v3 fields. + if row['projection_sha256'] != '': + raise RuntimeError('collection_resolution_projection_integrity') + else: + projection = digest(encoded([row['label'], row['body'], + {key: value for key, value in metadata.items() if key != 'source'}])) + version = identity('version', encoded([member['document_id'], row['raw_sha256'], + row['processing_version'], projection]).decode()) + if projection != row['projection_sha256'] or version != row['current_version']: + raise RuntimeError('collection_resolution_projection_integrity') fingerprint_rows.append({ **member, "permission": row["permission"], "platform": row["platform"], "original_id": row["original_id"], "raw_sha256": row["raw_sha256"], diff --git a/tests/test_alden_entity_integrity.py b/tests/test_alden_entity_integrity.py index fb701f1f..954a4fa9 100644 --- a/tests/test_alden_entity_integrity.py +++ b/tests/test_alden_entity_integrity.py @@ -92,6 +92,79 @@ def source_snapshot(self): blobs = {path.name: digest(path.read_bytes()) for path in self.store.blobs.iterdir() if path.is_file()} return tables, blobs + def test_v3_projection_corruption_rejects_fresh_preview_and_apply_before_bootstrap(self): + for column, replacement in ( + ('label', 'Altered label without a new version'), + ('body', 'Altered body without a new version'), + ('metadata', '{"source_url":"local://altered-metadata"}'), + ('projection_sha256', '0' * 64), + ('processing_version', 'altered-processor-without-new-version'), + ): + with self.subTest(column=column): + plan = self.preview()['plan'] + version = self.member(self.t1, 'a')['version'] + with self.store.database() as db: + original = db.execute('SELECT ' + column + ' FROM versions WHERE id=?', (version,)).fetchone()[0] + db.execute('UPDATE versions SET ' + column + '=? WHERE id=?', (replacement, version)) + try: + with self.assertRaisesRegex(RuntimeError, '^collection_resolution_projection_integrity$'): + self.preview() + with self.assertRaisesRegex(RuntimeError, '^collection_resolution_projection_integrity$'): + self.apply(plan, 'invalid-projection-' + column) + self.assertEqual(self.feature_tables(), set()) + self.assertEqual(list(self.store.root.glob('collection.resolution-before-v1-*.sqlite3')), []) + finally: + with self.store.database() as db: + db.execute('UPDATE versions SET ' + column + '=? WHERE id=?', (original, version)) + self.assertEqual(self.preview()['plan'], plan) + + def test_projection_validation_is_repeated_inside_apply_transaction(self): + plan = self.preview()['plan'] + version = self.member(self.t1, 'a')['version'] + backup = resolution._backup_before_feature + def mutate_after_preflight(store): + backup(store) + with self.store.database() as db: + db.execute('UPDATE versions SET projection_sha256=? WHERE id=?', ('0' * 64, version)) + with patch.object(resolution, '_backup_before_feature', side_effect=mutate_after_preflight): + with self.assertRaisesRegex(RuntimeError, '^collection_resolution_projection_integrity$'): + self.apply(plan, 'late-invalid-projection') + self.assertEqual(self.feature_tables(), set()) + + def test_active_overlay_stops_projecting_on_invalid_projection_and_recovers_without_reapply(self): + plan = self.preview()['plan'] + applied = self.apply(plan, 'projection-current') + version = self.member(self.t1, 'a')['version'] + with self.store.database() as db: + projection = db.execute('SELECT projection_sha256 FROM versions WHERE id=?', (version,)).fetchone()[0] + db.execute('UPDATE versions SET projection_sha256=? WHERE id=?', ('0' * 64, version)) + try: + self.assertEqual(self.active(), []) + self.assertEqual(self.history()['items'][0]['current_validity'], { + 'valid': False, 'state': 'collection_resolution_projection_integrity'}) + # A replay is the historical receipt, not a new activation or a + # claim that the previously accepted source is still current. + self.assertEqual(self.apply(plan, 'projection-current'), applied) + self.assertEqual(self.active(), []) + finally: + with self.store.database() as db: + db.execute('UPDATE versions SET projection_sha256=? WHERE id=?', (projection, version)) + self.assertEqual(self.active()[0]['resolution_id'], applied['resolution_id']) + self.assertEqual(len(self.history()['items']), 1) + + def test_source_metadata_excluded_from_projection_keeps_its_provenance_guard(self): + plan = self.preview()['plan'] + version = self.member(self.t1, 'a')['version'] + with self.store.database() as db: + metadata = json.loads(db.execute('SELECT metadata FROM versions WHERE id=?', (version,)).fetchone()[0]) + metadata['source'] = 'changed source declaration, not a new body projection' + db.execute('UPDATE versions SET metadata=? WHERE id=?', (encoded(metadata).decode(), version)) + refreshed = self.preview()['plan'] + self.assertNotEqual(refreshed['source_fingerprint'], plan['source_fingerprint']) + with self.assertRaisesRegex(ValueError, '^collection_resolution_source_fingerprint_changed$'): + self.apply(plan, 'old-source-metadata') + self.assertEqual(self.apply(refreshed, 'new-source-metadata')['state'], 'active') + def test_selected_original_identity_mismatch_rejected_by_preview_and_apply(self): for column, replacement in (("platform", "youtube"), ("original_id", "a-replaced")): with self.subTest(column=column):