Skip to content

fix(backend): gate /v1/dev abuse, canonical invalid_patch visibility race, embeddings-400 degrade - #13511

Merged
Git-on-my-level merged 2 commits into
mainfrom
fix/13505-dev-abuse-canonical-embeddings
Sep 13, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
fix/13505-dev-abuse-canonical-embeddings

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

What changed and why

Three residuals from the 2026-09-11 chat-SLI triage, all in one theme — stop unauthenticated junk from burning budgeted reads and stop two real error families that failed user-visible chat journeys. Closes #13505. Closes SCA-466.

  1. Canonical write invalid_patch visibility race (backend/utils/memory/canonical_memory_adapter.py): the duplicate-add resolver from fix(backend): resolve duplicate memory adds to the existing identical row #12524 read the colliding row exactly once. A concurrent/retry submission whose row is not readable yet at that single read raised canonical write failed: ApplyStatus.invalid_patch (add patch new_memory_id already exists) — the 12× family in the SLI window. The resolver now re-reads briefly (bounded ~0.5s, only on the miss path) before failing. Different-content id reuse, user-rejected rows, privacy-deleted ids, and never-visible rows still raise exactly as before.
  2. Embeddings gateway 400 on action-item similarity (backend/database/vector_db.py): search_action_items_by_vector had no guard at all — an httpx.HTTPStatusError 400 from embed_query surfaced as a 500 on GET /v1/action-items/search and the MCP search path. Both similarity helpers now strip/clip the query before embedding (empty short-circuits, oversized input clipped at 8000 chars) and degrade to [] on embed/query failure, matching the established best-effort contract of find_similar_action_items.
  3. /v1/dev/* scripted abuse hardening: junk omi_dev_-prefixed Bearer tokens now fail a zero-IO format gate in database/dev_api_key.py (every issued key is omi_dev_ + 32 lowercase hex) instead of costing a Redis read plus a Firestore where(hashed_key) query; POST /v1/dev/user/memories gains a per-minute burst ceiling dev:memories_write_burst (30/min — the hourly dev:memories 120/h window alone admits the whole quota inside one minute, which is the observed 69/min burst shape); POST /v1/dev/user/conversations/from-segments gains a dedicated dev:conversations_from_segments (30/hour) budget mirroring the first-party route, composed with the shared dev:conversations ceiling the same way conversation reads compose shared+per-route budgets; naive started_at/finished_at values on from-segments now 422 at validation instead of raising TypeError (uncaught 500) inside the handler on both the developer and first-party routes.

Product invariants affected

  • INV-MEM-4 — the duplicate-add visibility retry still resolves only to an
    identical, active, non-user-rejected row and returns its existing id;
    promotion authority and every fail-closed collision case are untouched.
  • INV-MEM-1 — no tier vocabulary or tier-transition behavior changes; the
    resolver returns the existing row's id unchanged.

How it was verified

  • All touched suites green in per-file sessions (the repo's contract — see backend-unit-tests.yml): test_ws_j_delete_privacy.py (43), test_action_item_dedup.py (23), test_dependency_async_boundaries.py (10), test_api_key_listability_contract.py (26), test_api_key_family_errors.py (4), test_developer_from_segments_idempotency.py (19).
  • Adjacent suites still green: test_memory_apply_store.py (45), test_developer_memory_adapter.py (15), test_rate_limiting.py (85), test_dev_ask_endpoint.py (9), test_action_items_conversation_list_malformed.py + test_task_sharing.py (33).
  • Sabotage-proven: with each fix reverted in turn, every new regression fails — the canonical race test reproduces the exact prod RuntimeError, the embeddings 400 propagates out of search_action_items_by_vector, the malformed-key test reaches the Firestore client, the wiring tests miss the new policies/dependency, and the naive-datetime validation does not raise. Restored, all pass.
  • scripts/pr-preflight and make preflight with this body file from the final commit.

Tests

  • test_ws_j_delete_privacy.py::test_identical_resubmission_resolves_once_the_row_becomes_readable — the race regression (fails without the fix with the exact prod error); test_row_that_never_becomes_readable_still_fails_closed — the retry stays bounded. Existing fail-closed tests (test_reusing_a_row_id_for_different_content_still_fails, privacy-delete) unchanged and passing.
  • test_action_item_dedup.py::TestActionItemEmbeddingGateway400 — real httpx.HTTPStatusError 400 degrade, empty-query short-circuit, clip-before-embed, Pinecone failure, and the previously untested happy path of search_action_items_by_vector; empty/blank/oversized handling for find_similar_action_items.
  • test_api_key_listability_contract.py::test_malformed_dev_api_keys_are_rejected_before_any_redis_or_firestore_io.
  • test_dependency_async_boundaries.py::test_dev_write_paths_check_burst_and_dedicated_rate_budgets (plus the updated executor-routing sequence test).
  • test_developer_from_segments_idempotency.py::test_from_segments_rejects_timezone_naive_timestamps_with_422 and ::test_dev_from_segments_route_uses_the_dedicated_rate_limited_dependency.

Failure class (fixes)

Failure-Class: FC-replay-idempotency-keyed-on-advancing-state

Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 3734 -> 3773 | bounded snapshot-visibility retry wrapper for the duplicate-add resolver (~30 lines incl. contract docstring) plus the review-fix early gate that skips the retry for every non-duplicate failure; no new branching surface elsewhere in the file
Line-Count-Exception: backend/routers/developer.py | 2511 -> 2527 | tz-aware field validator on the shared from-segments request model (422 instead of TypeError 500) plus the dedicated rate-limited dependencies for the dev from-segments route and the POST-only memory-create burst context

Review in cubic

@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.

All reported issues were addressed across 11 files

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

Re-trigger cubic

Comment thread backend/utils/rate_limit_config.py Resolved
Comment thread backend/utils/rate_limit_config.py Resolved
Comment thread backend/dependencies.py Resolved
Comment thread backend/database/vector_db.py Resolved
Git-on-my-level and others added 2 commits September 12, 2026 03:14
…race, embeddings-400 degrade

Three residuals from the 2026-09-11 chat-SLI triage (GH #13505):

1. Canonical write invalid_patch race: the duplicate-add resolver read the
   colliding row exactly once; a concurrent identical submission whose row is
   not readable yet 500'd user-visible chat/extraction writes. The resolver now
   retries the snapshot briefly before failing closed. Different-content reuse,
   user-rejected rows, and never-visible rows still raise.

2. Embeddings gateway 400 on action-item similarity: search_action_items_by_vector
   had no guard at all, so a 400 surfaced as a 500 on GET /v1/action-items/search
   and the MCP search path. Both similarity helpers now validate and clip the
   query before embedding and degrade to [] on gateway/Pinecone failure.

3. /v1/dev/* scripted abuse: junk omi_dev_-prefixed Bearer tokens now fail the
   format gate before any Redis/Firestore IO; POST /v1/dev/user/memories gains a
   per-minute burst ceiling (dev:memories_write_burst 30/min) on top of the
   hourly cap; POST /v1/dev/user/conversations/from-segments gains a dedicated
   dev:conversations_from_segments (30/hour) budget mirroring the first-party
   route, composed with the shared dev:conversations ceiling; naive
   started_at/finished_at values on from-segments now 422 instead of raising
   TypeError (500) inside the handler.

Closes #13505
… burst, resolver early gate, degrade telemetry

Addresses cubic-dev-ai review on #13511:

- Rate-limit boost exemption (P1 x2): add dev:memories,
  dev:memories_write_burst, dev:conversations, and
  dev:conversations_from_segments to the default BOOST_EXEMPT set so
  RATE_LIMIT_BOOST (prod 100) cannot multiply the new abuse ceilings
  into no-ops; shared ceilings ride the same exemption so the
  dedicated budgets always compose with real caps.
- POST-only burst budget (P2): move dev:memories_write_burst out of the
  shared write context into a new create-only context so PATCH/DELETE
  memory requests cannot drain the POST burst bucket and 429.
- Canonical resolver early gate (P2): _resolve_duplicate_add_row now
  returns immediately unless the apply result is the duplicate-add
  collision shape (invalid_patch + duplicate_row reason); other
  failures no longer pay the ~0.5s retry delay and extra reads.
- Degrade telemetry (P2): search_action_items_by_vector's failure
  path now records shared fallback telemetry per the fallback module
  contract, so provider outages are distinguishable from genuine
  no-match searches.
- Test hardening (P2 x2): malformed-key zero-IO test now makes Redis
  reads raise; dev-write-budget test asserts the declared Depends()
  composition (create -> hourly write -> auth) instead of a
  hand-picked call order.
@Git-on-my-level
Git-on-my-level force-pushed the fix/13505-dev-abuse-canonical-embeddings branch from f226737 to 90ace33 Compare September 11, 2026 20:29
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Addressed all 7 unresolved review threads (cubic-dev-ai) in 90ace33 — all verified with targeted backend unit runs, CI green on the new head.

Thread Fix
rate_limit_config.py:225 (P1) dev:memories + dev:memories_write_burst added to default BOOST_EXEMPT_POLICIES so RATE_LIMIT_BOOST can no longer multiply the abuse ceilings
rate_limit_config.py:214 (P1) dev:conversations + dev:conversations_from_segments added to the same exemption; the shared hourly ceilings ride it too so the dedicated budgets always compose with real caps
canonical_memory_adapter.py:1535 (P2) _resolve_duplicate_add_row now returns immediately unless the result is invalid_patch + duplicate-row reason; non-duplicate failures no longer pay the ~0.5s retry delay / extra reads
dependencies.py:654 (P2) burst budget moved to a POST-only get_developer_memory_default_memory_create_context; PATCH/DELETE keep the hourly-only write context
vector_db.py:949 (P2) degrade path now calls record_fallback (component other, outcome degraded) per the shared fallback telemetry contract
test_api_key_listability_contract.py:412 (P2) read_cached_dev_api_key_data on the mock Redis now raises, so a regression routing malformed tokens through Redis fails the test
test_dependency_async_boundaries.py:513 (P2) test now asserts the declared Depends() composition (create → hourly write → auth; from-segments → get_auth_with_conversations_write) instead of a hand-sequenced call order

Also: new regression test pinning the dev-policy boost exemptions under boost 2/100/1000, and PR-body line-count exceptions updated for the new file sizes.

@Git-on-my-level
Git-on-my-level merged commit aae8cbd into main Sep 13, 2026
46 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/13505-dev-abuse-canonical-embeddings branch September 13, 2026 06:21
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.

backend: gate/rate-limit abused /v1/dev/* endpoints; fix canonical-write invalid_patch race and embeddings-400 on action-items path

1 participant