Skip to content

Commit ce0154d

Browse files
SCA-4146 retain and re-admit keyed claims on budget cuts
Co-authored-by: multica-agent <[email protected]>
1 parent 7350583 commit ce0154d

10 files changed

Lines changed: 205 additions & 306 deletions
Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,19 @@
1-
# Keyed from-segments uploads can finish after the request deadline
1+
# Keyed from-segments uploads retain their claim on a request budget cut
22

3-
The Firebase-authenticated `POST /v1/conversations/from-segments` route gives
4-
keyed uploads up to 25 seconds of total request time. When the HTTP wait expires,
5-
the existing retryable 503 carries `request_budget_exhausted`. An admitted
6-
worker can finish the persisted claim with its own model budgets and owns
7-
cleanup on processing failure.
3+
When synchronous processing of a keyed from-segments upload hits the request
4+
deadline, the route returns the existing retryable 503 with the
5+
`request_budget_exhausted` attribution tag. The lifecycle rolls the stored
6+
claim back to `in_progress`. A retry can atomically re-admit that row and
7+
process the original transcript under the same conversation ID.
88

9-
A retry checks tombstones and the persisted conversation on the database pool
10-
before requesting a processing slot. A completed claim returns its existing
11-
conversation and applies late client metadata through the existing replay path.
12-
An active claim returns `from_segments_processing_in_flight`. New and stale
13-
claims remain subject to processing capacity. The existing atomic claim
14-
creation resolves a concurrent insert after a lookup miss.
9+
The retry receives the usual request budget. If enrichment repeatedly needs
10+
more time than that budget, the row stays available for another retry and
11+
processing can still time out. A provider timeout follows the existing error
12+
and cleanup path.
1513

16-
## Rollout
14+
## Rollout and verification
1715

18-
Pending review and backend deployment. This change requires no feature flag or
19-
data migration.
20-
21-
## Verification
22-
23-
`tests/unit/test_developer_from_segments_idempotency.py` covers budget expiry
24-
with a live claim, active and completed retries while processing admission is
25-
full, and capacity rejection for a new key. After rollout, verify that a retry
26-
after a budget cut returns the original conversation ID and track the route's
27-
503 share of valid uploads under SCA-3846.
16+
Pending backend rollout. No flag or migration is required. The idempotency
17+
regression test covers the tagged 503, retained row, successful retry with the
18+
original transcript, and the creation event. After rollout, check for a 200 on
19+
a previously cut upload and track the valid-attempt 503 share in SCA-3846.

‎backend/routers/developer.py‎

Lines changed: 88 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -90,13 +90,9 @@
9090
from utils.log_sanitizer import sanitize
9191
from utils.other.endpoints import with_rate_limit, get_current_user_uid
9292
from utils.other.from_segments_503 import FromSegments503Route
93-
from utils.other.request_deadline import (
94-
RequestDeadlineExceeded,
95-
from_segments_request_deadline,
96-
request_deadline_absolute,
97-
)
98-
from utils.other.request_deadline_workers import call_within_request_deadline, wait_for_from_segments_processing
99-
from utils.llm.gateway_error_contract import retryable_processing_response
93+
from utils.other.raise_site import raise_site_of
94+
from utils.other.request_deadline import RequestDeadlineExceeded, from_segments_request_deadline
95+
from utils.llm.gateway_error_contract import conversation_processing_http_exception
10096
from utils.other.list_budget import finish_list_budget, list_read_budget_for_request
10197
from utils.observability.external_lists import (
10298
observe_action_items_page,
@@ -135,7 +131,7 @@
135131
projected_meeting_treatment_eligible,
136132
record_finalized_meeting_receipt,
137133
)
138-
from utils.executors import ExecutorSaturatedError, db_executor, postprocess_executor
134+
from utils.executors import postprocess_executor
139135
from utils.external_read_contract import ignore_unknown_query, pagination_headers, utc_window
140136
from utils.request_validation import HistoryDays
141137
from utils.llm.memories import identify_category_for_memory
@@ -1801,7 +1797,7 @@ def _is_stale_from_segments_claim(conversation: dict, client_session_id: str, no
18011797
return False
18021798
if conversation.get('status') != ConversationStatus.processing.value:
18031799
return False
1804-
claimed_at = conversation.get('processing_admitted_at') or external_data.get('from_segments_claimed_at')
1800+
claimed_at = external_data.get('from_segments_claimed_at')
18051801
if not isinstance(claimed_at, datetime):
18061802
return False
18071803
if claimed_at.tzinfo is None:
@@ -2119,102 +2115,6 @@ def _ingest_conversation_from_segments(
21192115

21202116
if request.folder_id is not None and not folders_db.get_folder(uid, request.folder_id):
21212117
raise HTTPException(status_code=422, detail="folder_id does not match any of your folders")
2122-
bounded_processing = bool(request.client_session_id) and request_deadline_absolute() is not None
2123-
args = (uid, request, transcript_segments, started_at, finished_at)
2124-
kwargs = {
2125-
'client_device_id': client_device_id,
2126-
'client_platform': client_platform,
2127-
'bounded_processing': bounded_processing,
2128-
}
2129-
if not bounded_processing:
2130-
replay = _replay_from_segments(uid, request, bounded_processing=False)
2131-
if replay is not None:
2132-
return replay
2133-
return _process_validated_segments(*args, **kwargs)
2134-
try:
2135-
# A retry can resolve a persisted result even when all processing slots
2136-
# are busy. Only a lookup miss can reach processing admission.
2137-
replay = call_within_request_deadline(
2138-
_replay_from_segments, uid, request, bounded_processing=True, executor=db_executor
2139-
)
2140-
if replay is not None:
2141-
return replay
2142-
return wait_for_from_segments_processing(_process_validated_segments, *args, **kwargs)
2143-
except RequestDeadlineExceeded as error:
2144-
raise retryable_processing_response('request_budget_exhausted') from error
2145-
except ExecutorSaturatedError as error:
2146-
raise retryable_processing_response('from_segments_processing_capacity') from error
2147-
2148-
2149-
def _replay_from_segments(
2150-
uid: str,
2151-
request: CreateConversationFromTranscriptRequest,
2152-
*,
2153-
bounded_processing: bool,
2154-
) -> Optional[ConversationResponse]:
2155-
session_id = request.client_session_id
2156-
if not session_id:
2157-
return None
2158-
conversation_id = _from_segments_conversation_id(uid, session_id)
2159-
# One point read suppresses retries even when a prior delete failed during cleanup.
2160-
# Residual race: a create already past this read can overlap a delete commit;
2161-
# this guard deliberately does not transact across the two collections.
2162-
# A live conversation deleted elsewhere is tombstoned under its raw
2163-
# client session id (the ws doc id), not this derived uuid5 — check both.
2164-
if conversation_tombstones.is_deleted(uid, conversation_id) or conversation_tombstones.is_deleted(uid, session_id):
2165-
logger.info(
2166-
"from_segments_tombstoned_reject uid=%s client_session_id=%s conversation_id=%s",
2167-
uid,
2168-
sanitize(session_id),
2169-
conversation_id,
2170-
)
2171-
return ConversationResponse(id=conversation_id, status='deleted', discarded=True)
2172-
existing_conversation = read_product_conversation(
2173-
conversations_db.get_conversation,
2174-
uid,
2175-
conversation_id,
2176-
read_site=FirestoreReadSite.DEVELOPER_FROM_SEGMENTS_IDEMPOTENCY,
2177-
)
2178-
if existing_conversation:
2179-
if _is_stale_from_segments_claim(existing_conversation, session_id, datetime.now(timezone.utc)):
2180-
logger.warning(
2181-
"from-segments idempotency stale claim for uid=%s client_session_id=%s conversation_id=%s; retrying",
2182-
uid,
2183-
session_id,
2184-
conversation_id,
2185-
)
2186-
conversations_db.delete_conversation(uid, conversation_id)
2187-
else:
2188-
logger.info(
2189-
"from-segments idempotency hit for uid=%s client_session_id=%s conversation_id=%s",
2190-
uid,
2191-
session_id,
2192-
conversation_id,
2193-
)
2194-
if bounded_processing and existing_conversation.get('status') == ConversationStatus.processing:
2195-
raise retryable_processing_response('from_segments_processing_in_flight')
2196-
existing_conversation = _bind_late_client_projection(uid, existing_conversation, request)
2197-
existing_conversation = _apply_late_from_segments_context(uid, existing_conversation, request)
2198-
receipt = record_finalized_meeting_receipt(uid, existing_conversation)
2199-
if receipt is not None:
2200-
existing_conversation['meeting_treatment_eligible'] = bool(
2201-
receipt.get('meeting_treatment_eligible')
2202-
)
2203-
return _conversation_response_from_data(existing_conversation)
2204-
return None
2205-
2206-
2207-
def _process_validated_segments(
2208-
uid: str,
2209-
request: CreateConversationFromTranscriptRequest,
2210-
transcript_segments: list[TranscriptSegment],
2211-
started_at: datetime,
2212-
finished_at: datetime,
2213-
*,
2214-
client_device_id: Optional[str],
2215-
client_platform: Optional[str],
2216-
bounded_processing: bool,
2217-
) -> ConversationResponse:
22182118
calendar_context = request.calendar_meeting_context.to_context() if request.calendar_meeting_context else None
22192119

22202120
# Process geolocation if provided (keeps the raw coordinates when the geocode lookup misses)
@@ -2227,9 +2127,63 @@ def _process_validated_segments(
22272127
# the transcript path (CreateConversation has no text_source field).
22282128
source = request.source or ConversationSource.phone
22292129

2230-
conversation_id = (
2231-
_from_segments_conversation_id(uid, request.client_session_id) if request.client_session_id else None
2232-
)
2130+
conversation_id = None
2131+
resumable_conversation = None
2132+
if request.client_session_id:
2133+
conversation_id = _from_segments_conversation_id(uid, request.client_session_id)
2134+
# One point read suppresses retries even when a prior delete failed during cleanup.
2135+
# Residual race: a create already past this read can overlap a delete commit;
2136+
# this guard deliberately does not transact across the two collections.
2137+
# A live conversation deleted elsewhere is tombstoned under its raw
2138+
# client session id (the ws doc id), not this derived uuid5 — check both.
2139+
if conversation_tombstones.is_deleted(uid, conversation_id) or conversation_tombstones.is_deleted(
2140+
uid, request.client_session_id
2141+
):
2142+
logger.info(
2143+
"from_segments_tombstoned_reject uid=%s client_session_id=%s conversation_id=%s",
2144+
uid,
2145+
sanitize(request.client_session_id),
2146+
conversation_id,
2147+
)
2148+
return ConversationResponse(id=conversation_id, status='deleted', discarded=True)
2149+
existing_conversation = read_product_conversation(
2150+
conversations_db.get_conversation,
2151+
uid,
2152+
conversation_id,
2153+
read_site=FirestoreReadSite.DEVELOPER_FROM_SEGMENTS_IDEMPOTENCY,
2154+
)
2155+
if existing_conversation:
2156+
metadata = existing_conversation.get('external_data') or {}
2157+
if (
2158+
existing_conversation.get('status') == ConversationStatus.in_progress
2159+
and metadata.get('from_segments_client_session_id') == request.client_session_id
2160+
):
2161+
resumable_conversation = OmiConversation.model_validate(existing_conversation)
2162+
elif _is_stale_from_segments_claim(
2163+
existing_conversation, request.client_session_id, datetime.now(timezone.utc)
2164+
):
2165+
logger.warning(
2166+
"from-segments idempotency stale claim for uid=%s client_session_id=%s conversation_id=%s; retrying",
2167+
uid,
2168+
request.client_session_id,
2169+
conversation_id,
2170+
)
2171+
conversations_db.delete_conversation(uid, conversation_id)
2172+
else:
2173+
logger.info(
2174+
"from-segments idempotency hit for uid=%s client_session_id=%s conversation_id=%s",
2175+
uid,
2176+
request.client_session_id,
2177+
conversation_id,
2178+
)
2179+
existing_conversation = _bind_late_client_projection(uid, existing_conversation, request)
2180+
existing_conversation = _apply_late_from_segments_context(uid, existing_conversation, request)
2181+
receipt = record_finalized_meeting_receipt(uid, existing_conversation)
2182+
if receipt is not None:
2183+
existing_conversation['meeting_treatment_eligible'] = bool(
2184+
receipt.get('meeting_treatment_eligible')
2185+
)
2186+
return _conversation_response_from_data(existing_conversation)
22332187

22342188
resolved_client_device_id = client_device_id or request.client_device_id
22352189
resolved_client_platform = client_platform or request.client_platform
@@ -2266,8 +2220,19 @@ def _process_validated_segments(
22662220
}
22672221
OMI_CAPTURE_EVIDENCE_ENVELOPES_TOTAL.labels(path='from_segments', status=evidence_status).inc()
22682222

2269-
# Create conversation object with transcript segments
2270-
if conversation_id:
2223+
# Reuse the persisted transcript and metadata on a budget retry.
2224+
if resumable_conversation is not None:
2225+
if not lifecycle_service.admit_processing(
2226+
uid,
2227+
resumable_conversation.id,
2228+
extra_updates={'external_data.from_segments_claimed_at': datetime.now(timezone.utc)},
2229+
):
2230+
raise HTTPException(status_code=409, detail="Conversation creation already in progress")
2231+
resumable_conversation.status = ConversationStatus.processing
2232+
create_conversation_obj = resumable_conversation
2233+
client_projection = resumable_conversation.client_processing
2234+
language_code = resumable_conversation.language or 'en'
2235+
elif conversation_id:
22712236
create_conversation_obj = OmiConversation(
22722237
id=conversation_id,
22732238
created_at=started_at,
@@ -2313,8 +2278,6 @@ def _process_validated_segments(
23132278
request.client_session_id,
23142279
conversation_id,
23152280
)
2316-
if bounded_processing and existing_conversation.get('status') == ConversationStatus.processing:
2317-
raise retryable_processing_response('from_segments_processing_in_flight')
23182281
existing_conversation = _bind_late_client_projection(uid, existing_conversation, request)
23192282
existing_conversation = _apply_late_from_segments_context(uid, existing_conversation, request)
23202283
receipt = record_finalized_meeting_receipt(uid, existing_conversation)
@@ -2350,7 +2313,7 @@ def _process_validated_segments(
23502313
# Process conversation. The idempotent (client_session_id) path creates a
23512314
# processing row; the admission guard's lease heartbeat keeps it fresh so the
23522315
# crash-orphan sweep can never terminalize active work. rollback_on_failure is
2353-
# False because this path owns its own recovery (delete on exception below).
2316+
# False because this path retains the row only for a request budget cut.
23542317
# Only pass client_projection when accepted: mocks and other callers that
23552318
# still use a 3-positional signature stay compatible, and omitting it is
23562319
# the same as None on the coordinator.
@@ -2368,9 +2331,18 @@ def _process_validated_segments(
23682331
conversation = process_conversation(uid, language_code, create_conversation_obj, **process_kwargs)
23692332
else:
23702333
conversation = process_conversation(uid, language_code, create_conversation_obj, **process_kwargs)
2371-
except Exception:
2372-
if request.client_session_id and conversation_id:
2373-
conversations_db.delete_conversation(uid, conversation_id)
2334+
except Exception as error:
2335+
budget_cut = isinstance(error, RequestDeadlineExceeded) or raise_site_of(error) == 'request_budget_exhausted'
2336+
if conversation_id:
2337+
if budget_cut:
2338+
try:
2339+
lifecycle_service.rollback_processing_admission(uid, conversation_id)
2340+
except Exception:
2341+
logger.warning('from_segments_budget_claim_rollback_failed')
2342+
else:
2343+
conversations_db.delete_conversation(uid, conversation_id)
2344+
if isinstance(error, RequestDeadlineExceeded):
2345+
raise conversation_processing_http_exception(error) from error
23742346
raise
23752347
# Non-idempotent ingest: the coordinator's generic persist stripped the
23762348
# field (paid / flag-off deferred). Stamp it now. The session-id path

0 commit comments

Comments
 (0)