fix(dashboard-testing): canonicalize reflected row field names

This commit is contained in:
2026-10-11 04:20:22 +03:00
parent c0c7f69858
commit 2da7913e85
4 changed files with 67 additions and 3 deletions

View File

@@ -181,6 +181,40 @@ def test_database_identity_preserves_native_producer_carrier(changed):
# #endregion Test.LabReset.Contract.DbIdentityCarrier
# #region Test.LabReset.Contract.ReflectedRowFields [C:2] [TYPE Function]
# @TEST_INVARIANT The measured quoted_name field carrier becomes plain identifiers; native/nested values are untouched.
def test_reflected_identifier_keys_preserve_exact_native_values():
from sqlalchemy import Column, Integer, JSON, MetaData, Table
from sqlalchemy.sql.elements import quoted_name
table = Table("owned", MetaData(), Column("id", Integer), Column("payload", JSON))
payload = {"items": [17, None]}
row = {quoted_name("id", True): 7, quoted_name("payload", False): payload}
with pytest.raises(archive.Stop, match="^LAB_RESET_CODEC_UNSUPPORTED$"):
archive.encode(row)
result = database.row_fields(row, table)
assert result == {"id": 7, "payload": {"items": [17, None]}}
assert all(type(key) is str for key in result)
assert result["payload"] is payload and result["id"] is row["id"]
assert archive.decode(archive.encode(result)) == {"id": 7, "payload": {"items": [17, None]}}
payload[quoted_name("nested", True)] = "still strict"
with pytest.raises(archive.Stop, match="^LAB_RESET_CODEC_UNSUPPORTED$"):
archive.encode(result)
# #endregion Test.LabReset.Contract.ReflectedRowFields
# #region Test.LabReset.Contract.ForeignRowFields [C:2] [TYPE Function]
@pytest.mark.parametrize("items", [
[(object(), 1), ("payload", None)], [("id", 1), ("id", 2)],
[("foreign", 1), ("payload", None)], [("id", 1)],
])
def test_nonidentifier_duplicate_foreign_or_missing_row_field_refuses(items):
from sqlalchemy import Column, Integer, JSON, MetaData, Table
table = Table("owned", MetaData(), Column("id", Integer), Column("payload", JSON))
with pytest.raises(archive.Stop, match="^LAB_RESET_ROW_FIELD_CONFLICT$"):
database.row_fields(SimpleNamespace(items=lambda: items), table)
# #endregion Test.LabReset.Contract.ForeignRowFields
# #region Test.LabReset.Contract.DbSessionRefusal [C:2] [TYPE Function]
def test_foreign_session_refuses_without_termination():
statements = []

View File

@@ -8,6 +8,7 @@ from uuid import UUID
from sqlalchemy import MetaData, and_, create_engine, inspect, select, text
from sqlalchemy.pool import NullPool
from sqlalchemy.sql.elements import quoted_name
from dashboard_testing_lab_reset_archive import digest, encode, require
@@ -135,6 +136,27 @@ def locked_database(url, scope, expected_identity):
# #endregion Tooling.LabReset.Database.Transaction
# #region Tooling.LabReset.Database.RowFields [C:3] [TYPE Function]
# @PRE Exact reflected columns and only plain str/SQLAlchemy quoted_name keys; no duplicate/foreign/missing field.
# @POST Plain identifier keys preserve every native value by identity; nested values and recursive codec remain unchanged.
def row_fields(row, table):
identifiers = (str, quoted_name)
names = [column.name for column in table.columns]
require(all(type(name) in identifiers for name in names), "LAB_RESET_ROW_FIELD_CONFLICT")
expected = [str(name) for name in names]
items = list(row.items())
require(len(set(expected)) == len(expected) == len(items), "LAB_RESET_ROW_FIELD_CONFLICT")
result = {}
for key, value in items:
require(type(key) in identifiers, "LAB_RESET_ROW_FIELD_CONFLICT")
name = str(key)
require(name in expected and name not in result, "LAB_RESET_ROW_FIELD_CONFLICT")
result[name] = value
require(set(result) == set(expected), "LAB_RESET_ROW_FIELD_CONFLICT")
return result
# #endregion Tooling.LabReset.Database.RowFields
# #region Tooling.LabReset.Database.Reflection [C:3] [TYPE Function]
def reflect(connection, scope):
metadata = MetaData(schema="public")
@@ -144,7 +166,7 @@ def reflect(connection, scope):
keys = {name: [column.name for column in table.primary_key] for name, table in tables.items()}
require(all(keys.values()), "LAB_RESET_PRIMARY_KEY_REQUIRED")
fks = {name: inspector.get_foreign_keys(name, schema="public") for name in tables}
rows = {name: [dict(row) for row in connection.execute(select(table)).mappings()]
rows = {name: [row_fields(row, table) for row in connection.execute(select(table)).mappings()]
for name, table in tables.items()}
return tables, keys, fks, rows
# #endregion Tooling.LabReset.Database.Reflection
@@ -301,7 +323,7 @@ def verify_deleted(connection, scope, before, state):
table_names(connection, scope)
no_foreign_sessions(connection)
for name, table in tables.items():
actual = [dict(row) for row in connection.execute(select(table)).mappings()]
actual = [row_fields(row, table) for row in connection.execute(select(table)).mappings()]
expected = [row for row in original[name] if node(name, row, keys[name]) not in selected]
require(digest(sorted(map(encode, actual), key=digest)) == digest(sorted(map(encode, expected), key=digest)),
"LAB_RESET_POST_DELETE_STATE_CONFLICT")

View File

@@ -824,4 +824,12 @@ Root held fresh inventory dispatch after source review found that the reviewed o
Curator released only the file-archive helper and its storage guards. One exclusive0600 `selected-files.json` contains the canonical SHA→bytes dictionary; every archived member binds its exact key and the same whole-pack digest. Verification checks closed decode/re-encode, exact key set, member size/hash, retained file metadata and unchanged current selected bytes before deletion. Positive dedup/exclusive and negative extra/missing/duplicate/altered/forged-member/pack-digest/current-byte guards passed within90 offline checks; targeted Ruff/C901, compilation, diff and anchors passed. Main verified both frozen hashes. This is offline tooling proof, not an executed archive/reset or completed inventory.
### 2026-10-11 — Actual locked snapshot reached; reflected row key carrier corrected
Root/Verify reviewed clean `c0c7f69858ffddd72e4e25d2b4751fbe4320eeba` manifests and inventory-only driver, then authorized one attempt without stopping applications again. Fresh stopped receipt SHA256 `ed19ff18eb1561da72cb28967948f4f0612e409f03c97d4ecc3357f6ae638524` was copied exactly to both0600 UID1000 input paths; both application containers remained exited/running=False/pid=0. First worker passed identity/session/table locks and reached snapshot, then refused preserved-row encoding with LAB_RESET_CODEC_UNSUPPORTED at encode line70. Private original cause SHA256 `14c441ed21dea8cfb40504208c8bd97c07fe5f99af7111d4e353ed934ad464b2` and worker trace `a092b0ac4fbf4f42a7e9f28166ddf1ee` are retained under `inventory-only-20261011T011603Z`. Driver trace `9f68518e9316438da3cd92f29f8df20a` stopped; own worker was not created/run. No complete inventory, archive/reset or later phase is claimed.
The exact separately authorized READ ONLY diagnostic reflected only public.alembic_version and selected its single row with five-second statement limit/rollback. It retained key/value types, not row values: actual key is sqlalchemy.sql.elements.quoted_name, a str subclass but not exact plain str; one reflected metadata name matched and plain-name equality was true. Receipt `artifacts/stage0/reseed-20261010/reflected-key-types-20261011T011745Z/observed-types.json` SHA256 `119c9d278ca596a64f424cd0b90939f54df631287aef829c71000ffa376eb06c`, actual trace `2d44f96b6ac94de4a5cb830d0f77f722`, independently checked by Verify. No broader scan, codec weakening or inventory replay was used to infer this cause.
The narrow row-ingress helper now accepts only exact plain str or SQLAlchemy quoted_name field identifiers, requires exact reflected column names/cardinality with no duplicate/foreign/missing field, and creates plain identifier keys while preserving each native value by identity. Both reflect and verify_deleted use the same helper. Recursive codec and nested JSON remain strict; no arbitrary object/string coercion or alternate evidence is introduced. Real quoted_name component guards cover success, nonidentifier/duplicate/foreign/missing fields, unchanged values and strict refusal of nested quoted keys. The bounded two-file tool guard run passed95 offline checks; targeted Ruff/compilation/diff passed. Verify independently accepted both frozen diffs. N120/ONE354 and USER approval NONE remain unchanged; fresh source binding and root-reviewed inventory-only authorization are still required before another runtime attempt.
## @} Stage2.ChartTypeStabilizationJournal20261010

View File

@@ -35,7 +35,7 @@ Original275: а=0, б=120, source-restored=155. [Сверка803](2026-10-10-del
- Official filter_state observer установил: Clear без Apply сохраняет committed context, Apply меняет его. Chart8 closed context/4×2 и source hashes измерялись; Force refresh прошёл через четыре native owners. Новая политика должна наблюдаться из actual page URL key и official state: иной opaque key допустим при том же effective context. Будущая capture независимо проверяет actual request SHA/context. Standalone DATE normalizer сохраняет авторские endpoints/inclusive; D11 native `[from,to)` discoveryFalse/typedTrue refusal реализован компонентами:180 SQL-free guards PASS/connect0, DATE column и TIME global разделены; browser/custom DATE plugin ещё не измерены, финансовые SELECT dates неизменны.
- Последний полный suite24f53f97 завершился exit1:4211collected,3907callPASS,199callFAIL,103setupFAIL,2skipped; все4211teardowns PASS, collection/internal errors отсутствуют.302 private causes сохранены. Их нельзя объявлять целиком прежними или fixture-only. Проверенные bounded восстановления storage/DTO/import/quota/approval/recipe/DATE/logging достигают конкретных assertions; они не заменяют новый полный suite. Подробные результаты и безопасные causal traces находятся в журнале.
- Текущие live gaps вне исторической source803 области: зарегистрированные superset_api/sql_evidence приходят в всегда отказывающий QueryExecutor; receipt open/finalize fail-open и repr logs открыты. bounded_transform безусловно unsupported. Publish gate после exact selector требует actual evidence, deployment caller не передаёт selector, scheduled verifier visibly unavailable.037FR012/017 и044FR014 активны; эти свойства не retired wholesale, их source/runtime причины требуют реализации и проверки.
- D17 P0: stable scope, actor, durable review projection и независимый completed actual locator реализованы и проверены компонентами. Fixture PNG и synthetic DB publication receipts не доказывают browser capture, genuine Git publication или human review. D17 P0 следует после committed native/log cuts, до unrelated SDK/transform/gate repairs. Phase0 остановил оба owned backend; inventory отказал до locks/snapshot на address carrier. READ ONLY diagnostic подтвердил исходную DB identity; SQL carrier/archive pack исправлены компонентами, повтор inventory ждёт root-review. После root-review точных resources/manifest и явного разрешения maintenance: allowlisted module archive/reset→current stand restart/0039→fresh chart8 expected capture/PNG. Старое self-authored ожидание green suite до любой stand action superseded; новый полный green suite остаётся обязательным MERGE gate. Перед visual-review/confirm пользователь должен увидеть именно этот PNG; общее разрешение продолжать не заменяет human disposition. Пока review pending, genuine numeric chart8 chain может идти независимо: PASS→разрешённая +1→named-cell FAIL→finally restore→PASS с тем же pin, затем API multi-metric/query/series/pivot/raw acceptance. Superset/finance metadata и чужое состояние защищены.
- D17 P0: stable scope, actor, durable review projection и независимый completed actual locator реализованы и проверены компонентами. Fixture PNG и synthetic DB publication receipts не доказывают browser capture, genuine Git publication или human review. D17 P0 следует после committed native/log cuts, до unrelated SDK/transform/gate repairs. Оба owned backend остановлены. Inventory прошёл identity/locks и отказал на reflected row keys; READ ONLY diagnostic измерил quoted_name. SQL carrier, row ingress/archive pack исправлены компонентами; повтор inventory ждёт root-review. После root-review точных resources/manifest и явного разрешения maintenance: allowlisted module archive/reset→current stand restart/0039→fresh chart8 expected capture/PNG. Старое self-authored ожидание green suite до любой stand action superseded; новый полный green suite остаётся обязательным MERGE gate. Перед visual-review/confirm пользователь должен увидеть именно этот PNG; общее разрешение продолжать не заменяет human disposition. Пока review pending, genuine numeric chart8 chain может идти независимо: PASS→разрешённая +1→named-cell FAIL→finally restore→PASS с тем же pin, затем API multi-metric/query/series/pivot/raw acceptance. Superset/finance metadata и чужое состояние защищены.
Подробная прежняя хроника — [журнал](2026-10-10-chart-type-stabilization-journal.md).
Измерения native controls/силы cache refresh — `artifacts/stage0/reseed-20261010/`; промежуточная