Skip to content

Add encrypted object lake and per-space keys (no callers) - #24795

Merged
Git-on-my-level merged 10 commits into
mainfrom
pgf/c1-object-lake
Nov 6, 2026
Merged

Git-on-my-level merged 10 commits into
mainfrom
pgf/c1-object-lake

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Requested by David

What changed and why

Add the C1 object-lake and per-space key primitives without product callers. Every put compresses and AES-256-GCM encrypts bytes, addresses plaintext by SHA-256, binds the ciphertext to its path, and uploads create-only. Retries preserve the existing key version. Reads distinguish absent, corrupt, unavailable and destroyed states without returning ciphertext as data.

Wrapped DEKs live in top-level Firestore space_keys/{space_id} with create-race resolution, transactional rotation and final verified deletion. A bounded TTL cache saves KMS decrypts; document existence is rechecked before cache use so other workers observe destruction. FakeKMS and filesystem storage make tests hermetic.

Check in inert dev/prod/staging rollout settings, the lake lifecycle/retention contract, an offline validator in pre-deploy, and the unexecuted provisioning runbook. Write admission remains false/0; production bucket and KMS bindings are empty.

The Track C integration lead owns the ramp: hold 0% until C4 wipe coverage and dev round-trip/shred qualification are green, then 1% for at least 24 hours, 10% for at least 24 hours, and 100% by 2026-12-06 only while pointer integrity failures remain zero, verified wipe absence/shredded reads stay green, and key/fetch errors and latency remain flat. If the prerequisites are still blocked at the review date, report that blocker; do not activate writes. Rollback sets write enabled false and percent 0 while preserving reads and deletion.

Product invariants affected

  • INV-MEM-4 — cited for the generated runtime manifest; lake settings are inert and existing canonical-memory bindings are preserved.

How it was verified

Hermetic C1 tests exercise encryption, create-only retries across rotation, consent metadata, typed read failures, shredding, and lifecycle mutation rejection. After rebasing onto current main, regenerating the runtime manifest and feature registry produces no drift. The three runtime-state regressions were reproduced (3 failed, including 18 errors instead of 1): prepending lake entries broke later regex helpers anchored on the first GOOGLE_CLOUD_PROJECT entry. Completing lake bindings last restores the fixtures; all three now pass with their original exact assertions. Fix-round checks pass: 88 focused lake tests; runtime validator 151, retention 26, pusher references 28 and staging lifecycle 27; dead-code self-tests 16; pre-deploy 456 pytest plus 36 unittest tests and all source validators. Required make preflight was run through omi-heavy with the draft body and a 900-second backend file budget, and failed on missing duplicate-declaration admission metadata. Continuing the cancelled checks exposed missing deployment configuration classifications; all other selected guards pass (51 of 53, across the original run and continuations). Two minimal scope-exception patches are prepared and validated using disposable candidate inputs, but remain unapplied because their owning files are outside the C1 brief and the four authorized exceptions. Acceptance remains blocked until the lead authorizes/applies them and reruns full preflight. No endpoint exists in C1, and no GCP tier, production API, data, bucket, or KMS access was used.

Tests

backend/tests/unit/test_object_lake.py, test_space_keys.py, test_object_lake_config.py, and test_object_lake_lifecycle_contract.py cover the core and error paths with real local AES-GCM and injected storage/Firestore. Selected backend CI, deploy-source checks, import purity and repository preflight are run locally; exact results are recorded in the result artifact.

UI evidence

UI-Evidence: none -- backend only

Failure class (fixes)

Failure-Class: none

New guards (only when adding a check or ratchet)

The offline validator enforces the approved pre-provisioning R13 contract: soft delete 0, no versioning, no age deletion and no transcript tier below Nearline. It composes into the existing pre-deploy check rather than introducing a workflow. This is a new-storage admission contract before first bytes, not a production incident fix; The lead authorized the one .github dead-code allowlist entry for the deliberately unwired module; remove it when C2 adds the first caller.

Scoped cleanups (optional)

No product callers. The lead authorized the runtime fixture, retention scanner, pusher snapshot and reasoned dead-code allowlist scope exceptions. C2 owns codec integration and privacy write gates; C3 owns migration, janitor, registry and current-consent export filtering; C4 owns explicit prefix deletion and key destruction LAST. The generic user-subtree wipe does not reach top-level space keys. Production writes must remain off until C4 coverage is green. Wrapped-key backups/PITR retain the accepted roughly seven-day restore tail. Bucket/KMS/audit provisioning and a future lifecycle-workflow variant are separate authorized changes.

Review follow-ups: C2/C3 must set a per-class decompression cap, budget Firestore key-document reads, and enforce release/contract alignment before writes. Retry metadata/header agreement and the remaining narrow failure-injection tests belong in the next core test pass. C4 must durably fence deleted owners, quiesce in-flight puts, and prove no object/key resurrection with concurrent and emulator transaction-contention tests. Invalid wrapped-key encoding remains fail-closed but retryable; C2 must preserve that distinction from shredded data.

Remaining admission metadata: add OBJECT_LAKE_WRITE_PERCENT to the existing duplicate-source allowlist (expiry 2026-11-20; workstream B must consolidate before expiry), and classify the six lake deployment bindings as non-secret configuration. Neither change alters runtime values or weakens the runtime-state validator assertions.

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

@Git-on-my-level Git-on-my-level self-assigned this Nov 6, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

27 issues found across 33 files

Confidence score: 2/5

  • In space_keys.py, a wipe can report success while a concurrent get_or_create_space_key creates the key after the absence check. Fence key creation against wipes so a late create cannot survive.
  • In space_keys.py, missing OBJECT_LAKE_KMS_KEY silently selects FakeKMS, which wraps keys using a constant from the source. Fail closed when the production KMS key is not configured.
  • In validate_object_lake_bucket_contract.py, populated bucket and KMS bindings are enough to allow writes without checking C4 qualification. Require explicit qualification before approving writes.
  • In space_keys.py, a cache hit can keep returning a DEK after its KMS version is disabled, for up to the 24-hour cache lifetime. Add a revocation mechanism or explicitly bound that window.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name=".agent-artifacts/pgf-result.md">

<violation number="1" location=".agent-artifacts/pgf-result.md:9">
P3: The referenced report and verification receipts are not present under `.agent-artifacts/`, so these links cannot provide the evidence this handoff claims to preserve. Commit the referenced files or update the links to their actual locations.</violation>

<violation number="2" location=".agent-artifacts/pgf-result.md:82">
P3: This link target is a local filesystem path on one developer's machine, so it will be broken for every other reader. Replace it with a repo-relative or generic reference, and avoid committing the local `/Users/...` workspace paths in the verification notes.</violation>
</file>

<file name="backend/deploy/storage-lifecycle/README.md">

<violation number="1" location="backend/deploy/storage-lifecycle/README.md:64">
P3: Give the validator its full repo path, `backend/scripts/validate_object_lake_bucket_contract.py`, to match the existing `validate_storage_lifecycle.py` reference. The new `lake-forward.json` paragraph should also say it is not applied by the lifecycle workflow yet, since the opening paragraph says that workflow applies every file here.</violation>
</file>

<file name="backend/charts/backend-listen/dev_omi_backend_listen_values.yaml">

<violation number="1" location="backend/charts/backend-listen/dev_omi_backend_listen_values.yaml:414">
P3: The existing comment about frame bytes going to the production bucket now sits above `BUCKET_OBJECT_LAKE`, which points to the dev bucket. Move the new block above the comment so the comment stays with `BUCKET_SCREEN_FRAMES`.</violation>
</file>

<file name="backend/tests/unit/test_object_lake.py">

<violation number="1" location="backend/tests/unit/test_object_lake.py:259">
P3: Move this import to the module top level with the other imports. AGENTS.md requires all imports at module scope, not inside functions.</violation>
</file>

<file name="backend/charts/pusher/dev_omi_pusher_values.yaml">

<violation number="1" location="backend/charts/pusher/dev_omi_pusher_values.yaml:243">
P3: This comment now sits above the new dev object-lake bindings instead of `BUCKET_SCREEN_FRAMES`, which it describes. Move the comment back so it directly precedes `BUCKET_SCREEN_FRAMES`, and add a comment for the object-lake block if it needs one.</violation>
</file>

<file name="backend/utils/other/object_lake.py">

<violation number="1" location="backend/utils/other/object_lake.py:241">
P2: `decompress` and `flush` have no output cap, and `put_space_object` accepts arbitrary plaintext, so one valid object read can exhaust process memory. Enforce compressed-object and plaintext size limits before returning the bytes.</violation>

<violation number="2" location="backend/utils/other/object_lake.py:300">
P2: In deep mode, `verify_space_object` returns `False` for `LakeFetchError`, so a storage outage looks the same as a corrupt or missing object. Re-raise `LakeFetchError` before the `False` branch so unavailability stays a distinct typed failure, as the shallow path already does.</violation>
</file>

<file name="config/feature-flags.yaml">

<violation number="1" location="config/feature-flags.yaml:616">
P2: `OBJECT_LAKE_READ_ENABLED` is described as default on and as a read kill switch, but its ramp is the write ramp copied verbatim: "0 until C4 wipe coverage" then 1%/10%/100%. Following that ramp would keep existing lake pointers unreadable, which contradicts the rollback contract in LAKE.md. Give the read flag its own lifecycle and ramp, such as an ops_kill row with terminal keep and no ramp or review_by, matching the other default-on kill switches.</violation>
</file>

<file name="backend/tests/unit/test_backend_runtime_env_validator.py">

<violation number="1" location="backend/tests/unit/test_backend_runtime_env_validator.py:379">
P3: `with_object_lake_env` re-reads and re-parses the full 5k-line `runtime_env.yaml` on every call, and `with_cloud_run_oauth_secrets` already parses that file for its own bindings. Load the manifest once per module (or cache the loader) and reuse the `services` mapping so each fixture build does not add another full YAML parse against the per-test CPU budget.</violation>
</file>

<file name="backend/docs/feature-flag-registry.md">

<violation number="1" location="backend/docs/feature-flag-registry.md:1015">
P2: The OBJECT_LAKE_READ_ENABLED rollout ramp starts at 0 and ramps by percent, but this flag is already `true` in code and every listed host, and it is documented as a kill switch that should keep reads available through writer rollback. Rewrite the ramp to describe it as an always-on kill switch, and regenerate this doc from `config/feature-flags.yaml` rather than hand-editing it.</violation>
</file>

<file name="backend/tests/unit/test_object_lake_lifecycle_contract.py">

<violation number="1" location="backend/tests/unit/test_object_lake_lifecycle_contract.py:156">
P3: This test performs a fresh module load and writes `sys.modules` through `_load_composer`, but it is not marked. Add `@pytest.mark.slow` so it follows the backend test-marker rule for fresh module reloads.</violation>

<violation number="2" location="backend/tests/unit/test_object_lake_lifecycle_contract.py:169">
P3: The staging test hardcodes the Cloud Run service names instead of deriving them from `validator.EXPECTED_SERVICES`. Derive the lake-service set from that constant so the test stays tied to the prod binding contract.</violation>
</file>

<file name="backend/utils/other/space_keys.py">

<violation number="1" location="backend/utils/other/space_keys.py:92">
P1: When `OBJECT_LAKE_KMS_KEY` is unset, `_kms()` silently falls back to `FakeKMS`, which wraps DEKs with a key derived from a constant in the source. Keys created in that state are persisted with `kms_key=''` and cannot be unwrapped or rotated after real KMS is configured. Gate the fake to offline or test stages and fail closed otherwise.</violation>

<violation number="2" location="backend/utils/other/space_keys.py:128">
P2: Corrupt key data is reported as `SpaceKeyUnavailable`, which callers are told to retry. The PR requires a distinct corrupt state, so add a `SpaceKeyCorrupt` exception for `_decode` failures and invalid DEK lengths, and map them before the generic `except Exception`.</violation>

<violation number="3" location="backend/utils/other/space_keys.py:250">
P1: A cache hit returns the DEK without consulting KMS, so disabling its KMS version cannot revoke a warmed key until the cache expires (24 hours by default). Add a revocation mechanism or shorten and explicitly bound this delay if KMS disable is intended to revoke access.</violation>

<violation number="4" location="backend/utils/other/space_keys.py:287">
P2: `destroy_space_keys` validates the document before deleting it, so a malformed key document cannot be destroyed and its wrapped DEKs remain. Destruction should not depend on document validity. Count versions from the raw dict and delete without decoding.</violation>

<violation number="5" location="backend/utils/other/space_keys.py:292">
P1: This read proves absence only at one instant: a concurrent `get_or_create_space_key` that already observed a missing document can create it after this check, so a wipe can report success while the key survives. Fence or quiesce key creation with a durable deletion marker before returning.</violation>
</file>

<file name="backend/tests/unit/test_space_keys.py">

<violation number="1" location="backend/tests/unit/test_space_keys.py:84">
P3: Add tests for the KMS key change guard in rotation and the invalid unwrapped-key length path. Both are fail-closed branches with no coverage in this file.</violation>

<violation number="2" location="backend/tests/unit/test_space_keys.py:166">
P3: This assertion depends on process-wide import state, so it can fail when another test in the same process has already imported `google.cloud.kms_v1`. Patch the import path (for example, a `sys.modules` probe in a subprocess) or assert on `config.kms_key()` being unset instead.</violation>

<violation number="3" location="backend/tests/unit/test_space_keys.py:179">
P2: The no-leak assertions miss the common DEK encoding. Add a check that `base64.b64encode(kms.raw[0])` is absent from `caplog.text`. The `raw.decode()` check in `test_fake_kms_does_not_import_real_sdk` is also a no-op for a leak and should use `base64.b64encode(raw)` or `raw.hex()`.</violation>
</file>

<file name="backend/config/object_lake.py">

<violation number="1" location="backend/config/object_lake.py:22">
P2: `write_enabled()` routes the new `OBJECT_LAKE_WRITE_ENABLED` flag through the `refactor_switches` migration shim, so its parser depends on the unrelated `CAPTURE_COVERAGE_MODE`. Without `serve`, only the exact string `true` enables writes; with `CAPTURE_COVERAGE_MODE=serve`, `1`/`on`/`yes` also enable. Read the flag with `config.refactor_modes.default_off` directly so its value does not change with capture-coverage rollout state.</violation>

<violation number="2" location="backend/config/object_lake.py:37">
P2: `read_enabled()` parses with an exact `== 'true'` and no `strip()`. Values an operator would use to enable reads (`1`, `on`, `yes`, trailing whitespace) and an empty string all return False, so reads are disabled even though the default is on. Use the same non-`false` parse as `shard_spread_enabled()` in config/batch_pipeline.py.</violation>
</file>

<file name="backend/scripts/validate_object_lake_bucket_contract.py">

<violation number="1" location="backend/scripts/validate_object_lake_bucket_contract.py:53">
P1: This check permits writes as soon as the bucket and KMS bindings are populated, without verifying C4 qualification. Reject enabled writes until qualification is explicitly checked so a pre-deploy run cannot approve a premature ramp.</violation>

<violation number="2" location="backend/scripts/validate_object_lake_bucket_contract.py:78">
P3: A null or non-mapping `env` block crashes the validator with a traceback instead of reporting `missing lake bindings`. Reject non-mapping `env` inside the existing try so it is caught and reported like the other shape errors.</violation>

<violation number="3" location="backend/scripts/validate_object_lake_bucket_contract.py:115">
P3: The `except` branch assigns `errors = [str(error)]`, which drops the contract errors collected before the runtime manifest was parsed. Initialize `errors = []` before the `try`, then use `errors.append(str(error))` so every failure is reported.</violation>
</file>

<file name="scripts/check_feature_flag_registry.py">

<violation number="1" location="scripts/check_feature_flag_registry.py:48">
P2: This exempts a newly introduced duplicate even though the allowlist comment says new duplicates must fail immediately. Keep the rollout key in one authoritative deployment source and remove this exception so the registry catches future source overlap.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

def _kms():
global _kms_client, _did_warn_fake
with _kms_lock:
if not config.kms_key():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: When OBJECT_LAKE_KMS_KEY is unset, _kms() silently falls back to FakeKMS, which wraps DEKs with a key derived from a constant in the source. Keys created in that state are persisted with kms_key='' and cannot be unwrapped or rotated after real KMS is configured. Gate the fake to offline or test stages and fail closed otherwise.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/other/space_keys.py, line 92:

<comment>When `OBJECT_LAKE_KMS_KEY` is unset, `_kms()` silently falls back to `FakeKMS`, which wraps DEKs with a key derived from a constant in the source. Keys created in that state are persisted with `kms_key=''` and cannot be unwrapped or rotated after real KMS is configured. Gate the fake to offline or test stages and fail closed otherwise.</comment>

<file context>
@@ -0,0 +1,302 @@
+def _kms():
+    global _kms_client, _did_warn_fake
+    with _kms_lock:
+        if not config.kms_key():
+            if not _did_warn_fake:
+                logger.warning('OBJECT_LAKE_KMS_KEY unset: using offline FakeKMS')
</file context>

errors.append('only SetStorageClass NEARLINE is permitted; no Delete or cold tiers')
if not isinstance(condition, Mapping) or condition.get('matchesPrefix') != ['v1/spaces/']:
errors.append('every rule must be scoped to v1/spaces/')
if (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This check permits writes as soon as the bucket and KMS bindings are populated, without verifying C4 qualification. Reject enabled writes until qualification is explicitly checked so a pre-deploy run cannot approve a premature ramp.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/validate_object_lake_bucket_contract.py, line 53:

<comment>This check permits writes as soon as the bucket and KMS bindings are populated, without verifying C4 qualification. Reject enabled writes until qualification is explicitly checked so a pre-deploy run cannot approve a premature ramp.</comment>

<file context>
@@ -0,0 +1,125 @@
+            errors.append('only SetStorageClass NEARLINE is permitted; no Delete or cold tiers')
+        if not isinstance(condition, Mapping) or condition.get('matchesPrefix') != ['v1/spaces/']:
+            errors.append('every rule must be scoped to v1/spaces/')
+        if (
+            not isinstance(condition, Mapping)
+            or type(condition.get('age')) is not int
</file context>

cache_key = (id(client), space_id, version, keys.kms_key, stored.wrapped_b64)
with _cache_lock:
cache = _key_cache()
if cache_key in cache:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: A cache hit returns the DEK without consulting KMS, so disabling its KMS version cannot revoke a warmed key until the cache expires (24 hours by default). Add a revocation mechanism or shorten and explicitly bound this delay if KMS disable is intended to revoke access.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/other/space_keys.py, line 250:

<comment>A cache hit returns the DEK without consulting KMS, so disabling its KMS version cannot revoke a warmed key until the cache expires (24 hours by default). Add a revocation mechanism or shorten and explicitly bound this delay if KMS disable is intended to revoke access.</comment>

<file context>
@@ -0,0 +1,302 @@
+        cache_key = (id(client), space_id, version, keys.kms_key, stored.wrapped_b64)
+        with _cache_lock:
+            cache = _key_cache()
+            if cache_key in cache:
+                return cache[cache_key]
+        # KMS calls for unrelated spaces must not serialize on the cache lock.
</file context>

return len(keys.versions)

count = destroy(client.transaction())
if ref.get().exists:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This read proves absence only at one instant: a concurrent get_or_create_space_key that already observed a missing document can create it after this check, so a wipe can report success while the key survives. Fence or quiesce key creation with a durable deletion marker before returning.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/other/space_keys.py, line 292:

<comment>This read proves absence only at one instant: a concurrent `get_or_create_space_key` that already observed a missing document can create it after this check, so a wipe can report success while the key survives. Fence or quiesce key creation with a durable deletion marker before returning.</comment>

<file context>
@@ -0,0 +1,302 @@
+                return len(keys.versions)
+
+            count = destroy(client.transaction())
+            if ref.get().exists:
+                raise SpaceKeyUnavailable('Space key deletion not verified')
+            return count
</file context>

return blob.size == ref.bytes and (blob.metadata or {}).get('plaintext_sha256') == ref.sha256
except ObjectLakeNotConfigured:
raise
except (ObjectLakeError, NotFound, space_keys.SpaceKeyDestroyed):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: In deep mode, verify_space_object returns False for LakeFetchError, so a storage outage looks the same as a corrupt or missing object. Re-raise LakeFetchError before the False branch so unavailability stays a distinct typed failure, as the shallow path already does.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/other/object_lake.py, line 300:

<comment>In deep mode, `verify_space_object` returns `False` for `LakeFetchError`, so a storage outage looks the same as a corrupt or missing object. Re-raise `LakeFetchError` before the `False` branch so unavailability stays a distinct typed failure, as the shallow path already does.</comment>

<file context>
@@ -0,0 +1,305 @@
+        return blob.size == ref.bytes and (blob.metadata or {}).get('plaintext_sha256') == ref.sha256
+    except ObjectLakeNotConfigured:
+        raise
+    except (ObjectLakeError, NotFound, space_keys.SpaceKeyDestroyed):
+        return False
+    except space_keys.SpaceKeyUnavailable:
</file context>

assert kms.unwraps == 2


def test_rotation_retains_old_versions_and_transaction_order(keys):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Add tests for the KMS key change guard in rotation and the invalid unwrapped-key length path. Both are fail-closed branches with no coverage in this file.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_space_keys.py, line 84:

<comment>Add tests for the KMS key change guard in rotation and the invalid unwrapped-key length path. Both are fail-closed branches with no coverage in this file.</comment>

<file context>
@@ -0,0 +1,205 @@
+    assert kms.unwraps == 2
+
+
+def test_rotation_retains_old_versions_and_transaction_order(keys):
+    store, kms = keys
+    space_keys.get_or_create_space_key('s', firestore_client=store)
</file context>

assert fake.decrypt(request={'ciphertext': wrapped}).plaintext == raw
space_keys._kms()
assert caplog.text.count('using offline FakeKMS') == 1
assert 'google.cloud.kms_v1' not in sys.modules

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This assertion depends on process-wide import state, so it can fail when another test in the same process has already imported google.cloud.kms_v1. Patch the import path (for example, a sys.modules probe in a subprocess) or assert on config.kms_key() being unset instead.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_space_keys.py, line 166:

<comment>This assertion depends on process-wide import state, so it can fail when another test in the same process has already imported `google.cloud.kms_v1`. Patch the import path (for example, a `sys.modules` probe in a subprocess) or assert on `config.kms_key()` being unset instead.</comment>

<file context>
@@ -0,0 +1,205 @@
+    assert fake.decrypt(request={'ciphertext': wrapped}).plaintext == raw
+    space_keys._kms()
+    assert caplog.text.count('using offline FakeKMS') == 1
+    assert 'google.cloud.kms_v1' not in sys.modules
+    assert raw.decode() not in caplog.text and base64.b64encode(wrapped).decode() not in caplog.text
+    with pytest.raises(ValueError):
</file context>

for plane, service in EXPECTED_SERVICES:
try:
services = env[plane]['services'] if plane == 'cloud_run' else env[plane]
bindings = services[service]['env']

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: A null or non-mapping env block crashes the validator with a traceback instead of reporting missing lake bindings. Reject non-mapping env inside the existing try so it is caught and reported like the other shape errors.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/validate_object_lake_bucket_contract.py, line 78:

<comment>A null or non-mapping `env` block crashes the validator with a traceback instead of reporting `missing lake bindings`. Reject non-mapping `env` inside the existing try so it is caught and reported like the other shape errors.</comment>

<file context>
@@ -0,0 +1,125 @@
+        for plane, service in EXPECTED_SERVICES:
+            try:
+                services = env[plane]['services'] if plane == 'cloud_run' else env[plane]
+                bindings = services[service]['env']
+            except (KeyError, TypeError):
+                errors.append(f'{env_name}/{service} missing lake bindings')
</file context>
Suggested change
bindings = services[service]['env']
bindings = services[service]['env']
if not isinstance(bindings, Mapping):
raise TypeError('env must be a mapping')

raise ValueError('runtime manifest must be a mapping')
errors.extend(validate_runtime_binding(document, contract))
except (OSError, ValueError, yaml.YAMLError) as error:
errors = [str(error)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The except branch assigns errors = [str(error)], which drops the contract errors collected before the runtime manifest was parsed. Initialize errors = [] before the try, then use errors.append(str(error)) so every failure is reported.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/validate_object_lake_bucket_contract.py, line 115:

<comment>The `except` branch assigns `errors = [str(error)]`, which drops the contract errors collected before the runtime manifest was parsed. Initialize `errors = []` before the `try`, then use `errors.append(str(error))` so every failure is reported.</comment>

<file context>
@@ -0,0 +1,125 @@
+                raise ValueError('runtime manifest must be a mapping')
+            errors.extend(validate_runtime_binding(document, contract))
+    except (OSError, ValueError, yaml.YAMLError) as error:
+        errors = [str(error)]
+    for error in errors:
+        print(f'ERROR: {error}')
</file context>

C1 supplies create-only, envelope-encrypted object-lake storage and Firestore/KMS space-key primitives with zero product callers. Config, lifecycle/retention policy, inert runtime/Helm bindings, offline admission validation and the unexecuted provisioning runbook ship together. The lead authorized and committed the four fixture/scanner/snapshot/dead-code scope exceptions before this round.

Implementation plus tests: 298 added lines, below the brief's 400-line target (excluding this handoff).
Historical C1 verification receipts remain in `pgf-verification.jsonl` and the linked `pgf-*.log` files. [Historical C1 report reconstructed from its original renderer and receipts](pgf-c1-result-before-r1.md) preserves the earlier blocked results; its old scope-exception status is superseded below. Rebase introduced M9's tracked report at this same generic path; that upstream report remains [in the pinned main tree](https://github.com/BasedHardware/omi/blob/876abc7312f28ae02d7b92c5c5034e5ba74303df/.agent-artifacts/pgf-result.md). This requested path now reports C1.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The referenced report and verification receipts are not present under .agent-artifacts/, so these links cannot provide the evidence this handoff claims to preserve. Commit the referenced files or update the links to their actual locations.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At .agent-artifacts/pgf-result.md, line 9:

<comment>The referenced report and verification receipts are not present under `.agent-artifacts/`, so these links cannot provide the evidence this handoff claims to preserve. Commit the referenced files or update the links to their actual locations.</comment>

<file context>
@@ -1,83 +1,84 @@
+C1 supplies create-only, envelope-encrypted object-lake storage and Firestore/KMS space-key primitives with zero product callers. Config, lifecycle/retention policy, inert runtime/Helm bindings, offline admission validation and the unexecuted provisioning runbook ship together. The lead authorized and committed the four fixture/scanner/snapshot/dead-code scope exceptions before this round.
 
-Implementation plus tests: 298 added lines, below the brief's 400-line target (excluding this handoff).
+Historical C1 verification receipts remain in `pgf-verification.jsonl` and the linked `pgf-*.log` files. [Historical C1 report reconstructed from its original renderer and receipts](pgf-c1-result-before-r1.md) preserves the earlier blocked results; its old scope-exception status is superseded below. Rebase introduced M9's tracked report at this same generic path; that upstream report remains [in the pinned main tree](https://github.com/BasedHardware/omi/blob/876abc7312f28ae02d7b92c5c5034e5ba74303df/.agent-artifacts/pgf-result.md). This requested path now reports C1.
 
-## Deviations and scope
</file context>

@Git-on-my-level
Git-on-my-level merged commit c321650 into main Nov 6, 2026
66 checks passed
@Git-on-my-level
Git-on-my-level deleted the pgf/c1-object-lake branch November 6, 2026 14:32
Git-on-my-level added a commit that referenced this pull request Nov 7, 2026
…24811)

<!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} -->
_Requested by **David**_

## What changed and why

Long transcript_segments can be stored as encrypted object-lake pointers
inside the existing field, through one codec shared by backend, listen,
pusher, MCP, export and search. API responses still contain segment
lists. Small or unadmitted transcripts retain the existing encoding.

Admitted transactional writes upload candidates outside Firestore, then
replay the entire transaction and recompute the logical source digest
before randomized grouping protection, from a fresh snapshot before
publishing a pointer. The pointer hash and decoded memo always describe
the actual uploaded JSON; transaction candidate puts cannot mask cold
reads of existing pointers. This lets live in_progress transcripts cross
Firestore's 1 MiB ceiling without an oversized inline commit. The
boundary permits 32 read preloads plus 32 candidate uploads and three
shared content changes (68 outer attempts). Its plaintext memo has a
32-entry/120-second cap and a 64 MiB decoded-object budget; budget
failures are typed and retryable.

Transport/key availability errors abort reads and decisions; absent
blobs are deleted transcripts and destroyed keys retain a distinct
shredded state. Missing/shredded transcripts preserve photos and durable
has_content signals during empty-recording cleanup. Malformed
dictionaries, including empty ones, remain unreadable content and cannot
authorize empty deletion. Missing bucket/release bindings close write
admission; unset KMS deliberately selects the existing offline FakeKMS.
Deep object verification returns False for destroyed keys and raises
SpaceKeyUnavailable for unavailable keys; shallow verification checks
metadata only.

O1: OBJECT_LAKE_WRITE_ENABLED stays off in prod until C4's wipe-coverage
test is green. Ramp is dev-first via OBJECT_LAKE_WRITE_PERCENT and C1's
existing registry plan. This PR adds no env binding, dependency upgrade,
schema migration or index. The pusher and batch worker carry the
required KMS dependency; existing lock versions are preserved.

C3 reuses offload_inline_transcript for revision-checked backfill and
owns legacy re-encryption, orphan GC and registry/receipt; it must
account for the memo ceilings before ramping backfill. C4 owns quiescing
puts, prefix purge and key destruction last, preserving tombstones. B/W2
carries pointer changes as content-free doc changes. A6 ports the seam
after C2. Public-chat's bounded decoder excludes pointer docs; treatment
of existing long shared conversations remains a product decision before
backfill.

## Product invariants affected

none

## How it was verified

Hermetic/local checks only; GCP tier: none. Every test command unsets
GOOGLE_APPLICATION_CREDENTIALS, CLOUDSDK_* and inherited
customer-service-account bindings. No production/customer-data access,
api.omi.me calls, push, PR or deploy. Exact commands, source identities
and individual receipts are in .agent-artifacts/pgf/c2-result.md.

Final focused verification: **243 tests passed**, including all five
round-3 review requirements. Full type checking reported **0 errors**
(75,544 warnings). Loopback checks passed listen lifecycle and **14
privacy tests**; all owned emulator ports were verified closed. Runtime
source closure passed all **19 registered images**, third-party closure
passed, all six locks regenerated without Git changes, and Black 26.5.1
passed all **50 changed backend Python files**. Import-purity,
test-isolation and async-blocker scans passed; the async scan's first
180-second agent deadline was insufficient, and its 900-second retry
passed.

The full CI contract ran all **2,681 files**: **2,679 exited 0 / 2
exited 1**. The two unchanged live-provider files then passed in the
same guarded runner with one worker: **134 passed / 3 slow cases
deselected**. The earlier Parakeet failure did not recur. After the
final codec/cleanup corrections, **2,410 tests passed across 58 related
source/caller files**, in addition to the 243 focused tests. This
reports cumulative coverage and isolated recovery of the timing
failures, not a green exit from the original full-CI command. Rebase
changed only two upstream firmware-CI files; the backend tree was
byte-identical before/after. Frozen preflight passed all **43 checks in
110.16 s** on `b937e5183f5274c2e6e3c78ccb526ae077a203d5`; metadata
validation passed **4 checks**. Final codec type checking passed **0
errors / 258 warnings**, and pinned Black rechecked all 50 changed
backend Python files. Existing app edits were temporarily shelved for
the gate and restored byte-for-byte. Docker image smoke is waived by
fix-r1.md. The Docker offline-stack round trip remains unverified;
real-router ASGI tests exercise pointer detail reads with 200/404/500
outcomes.

## Tests

backend/tests/unit/test_transcript_pointer.py pins round trips, flag-off
golden encodings, compressed-byte thresholds, missing bindings, no lake
IO inside transaction bodies, bounded read/upload retries, failed-upload
non-commit, decode states, aggregate memo bytes, consent and C3 CAS.

backend/tests/unit/test_conversation_transcript_offload.py covers the
transaction owners and reader surfaces, live writes above 1 MiB, source
changes during upload, randomized grouping sidecars, exact memo/blob
equality, invalid optional sidecars, kill-switch rechecks,
photo/has_content retention, malformed-pointer cleanup, and
destroyed/unavailable verifier keys.
backend/tests/unit/test_object_lake_config.py retains the deterministic
cohort contract with a configured bucket.

Decode/encode audits were rerun. Brief rows 1-19 use preload owners;
finalization admission uses the approved contention wrapper; terminal
cosmetics enforce a local no-IO guard. Recovery, agent-capability,
projection and F-join reads are nontransactional. The voice_profiles
encode is receipt-only, and transcript_files uses an id-less inline size
measurement; neither can offload. Protection migration retains existing
pointers. No reader is left relying on inline-only decoding except
deliberately bounded public chat.

## UI evidence

UI-Evidence: none -- backend only

## Failure class (fixes)

Failure-Class: none

## Scoped cleanups

Line-Count-Exception: backend/database/conversations.py | 4855 -> 4938 |
Preserve domain transaction structure while adding pointer decoding and
narrow unavailable-content refusals; codec mechanics live in
transcript_pointer.py.

Line-Count-Exception: backend/database/conversation_finalization_jobs.py
| 3549 -> 3551 | Wrap the existing admission owner in the transcript
preload boundary without changing lead2 queue state.
Line-Count-Exception: backend/database/users.py | 2516 -> 2517 |
Preserve the voice publication transaction and move its runner to the
shared preload boundary.
Line-Count-Exception: backend/utils/sync/assignment.py | 1527 -> 1536 |
Validate lake-pointer availability at the existing transaction load
boundary before candidate or canonical selection.

Scope provenance: C1-result.md Review disposition assigned tombstones,
decompression bounds and authority-read budgeting to C2; those inherited
library changes remain in this branch. The inherited .github dead-code
allowlist removal follows its own instruction to remove the entry when
C2 adds its first caller; round 3 makes no .github edits. Round 3
extends scope only to config/object_lake.py admission and the existing
cohort test setup, as required by fix-r2.md. Deep verification returns
False for destroyed keys and raises SpaceKeyUnavailable for temporarily
unavailable keys; shallow verification checks metadata only. C3 must
account for both the 32-reference and 64-MiB operation ceilings before
backfill.

Lead fix after review round 2: write admission now also requires
OBJECT_LAKE_KMS_KEY unless OMI_ENV_STAGE is local/offline, so a deployed
service can never write under FakeKMS. Remaining W5 notes: bounded parse
before the memo budget check for very large transcripts; C1-owned
object_lake/space_keys edits are lead-authorized C1 deferrals.

## Enable conditions (lake writes stay refused outside local/offline
until all hold)

1. Per-object DEK envelopes (follow-up PR stacked on this one; dev only,
production still refused at runtime and in deploy validation).
2. Orphaned upload on replay refusal: when the transactional replay
refuses after an out-of-transaction upload
(transcript_pointer.py:361,386), the uploaded blob is left behind
because the bucket contract forbids agent deletion. Must be fixed before
any enable (merge-owner Luna review 009108).
3. C4 wipe coverage green (also the #24795 enable condition).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant