Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

breaking/fix: Use a strong consistency for Cosmos DB operations

Clémence Lesné3336923d20bb
diff --git a/app/persistence/cosmos_db.py b/app/persistence/cosmos_db.py
index 3497f13..cd4f548 100644
--- a/app/persistence/cosmos_db.py
+++ b/app/persistence/cosmos_db.py
@@ -127,34 +127,28 @@ class CosmosDbStore(IStore):
scheduler: Scheduler,
) -> AsyncGenerator[None, None]:
# Copy and yield the updated object
- init_data = call.model_copy().model_dump(mode="json", exclude_none=True)
+ init_data = call.model_dump(mode="json", exclude_none=True)
yield
async def _exec() -> None:
# Compute the diff
- call_data = call.model_dump(mode="json", exclude_none=True)
- update_data: dict[str, Any] = {}
- for field, new_value in call_data.items():
+ init_call = call.model_dump(mode="json", exclude_none=True)
+ init_update: dict[str, Any] = {}
+ for field, new_value in init_call.items():
init_value = init_data.get(field)
if init_value != new_value:
- update_data[field] = new_value
+ init_update[field] = new_value
# Skip if no diff
- if not update_data:
+ if not init_update:
logger.debug("No update needed for call %s", call.call_id)
return
- # Update
- logger.debug(
- "Updating call %s with %s",
- call.call_id,
- update_data,
- )
- refreshed_call_raw = None
+ remote_raw = None
try:
async with self._use_client() as db:
# See: https://learn.microsoft.com/en-us/azure/cosmos-db/partial-document-update#supported-operations
- refreshed_call_raw = await db.patch_item(
+ remote_raw = await db.patch_item(
item=str(call.call_id),
partition_key=call.initiate.phone_number,
patch_operations=[
@@ -163,51 +157,39 @@ class CosmosDbStore(IStore):
"path": f"/{field}",
"value": value,
}
- for field, value in update_data.items()
+ for field, value in init_update.items()
],
)
except CosmosHttpResponseError as e:
logger.error("Error accessing CosmosDB: %s", e)
-
- # Skip if no refresh
- if not refreshed_call_raw:
return
- # Parse refreshed object
+ # Parse remote object
try:
- refreshed_call = CallStateModel.model_validate(refreshed_call_raw)
+ remote_call = CallStateModel.model_validate(remote_raw)
except ValidationError:
logger.debug("Parsing error", exc_info=True)
return
- # Refresh live object
+ # Refresh call with remote object
for field in call.model_fields_set:
- new_value = getattr(refreshed_call, field)
+ new_value = getattr(remote_call, field)
+ # Skip set to avoid Pydantic costly validation
if getattr(call, field) == new_value:
continue
- logger.debug(
- "Updating local field %s with %s from remote",
- field,
- new_value,
- )
+ # Try to set the new value
with suppress(ValidationError):
setattr(call, field, new_value)
# Update cache
- cache_key_id = self._cache_key_call_id(refreshed_call.call_id)
+ cache_key_id = self._cache_key_call_id(call.call_id)
await self._cache.set(
key=cache_key_id,
ttl_sec=await callback_timeout_hour(),
- value=refreshed_call.model_dump_json(),
- ) # Update for ID
- cache_key_phone_number = self._cache_key_phone_number(
- refreshed_call.initiate.phone_number
+ value=call.model_dump_json(),
)
- await self._cache.delete(
- cache_key_phone_number
- ) # Invalidate for phone number because we don't know if it's the same call
- # Queue the update
+ # Defer the update
await scheduler.spawn(_exec())
# TODO: Catch errors
@@ -235,6 +217,12 @@ class CosmosDbStore(IStore):
value=call.model_dump_json(),
)
+ # Invalidate phone number cache
+ cache_key_phone_number = self._cache_key_phone_number(
+ call.initiate.phone_number
+ )
+ await self._cache.delete(cache_key_phone_number)
+
return call
async def call_search_one(self, phone_number: str) -> CallStateModel | None:
@@ -364,9 +352,11 @@ class CosmosDbStore(IStore):
"""
Generate the Cosmos DB client.
"""
+ logger.debug("Using Cosmos DB service client for %s", self._config.endpoint)
+
return CosmosClient(
# Usage
- consistency_level=ConsistencyLevel.Eventual,
+ consistency_level=ConsistencyLevel.Strong,
# Reliability
connection_timeout=10, # 10 secs
retry_backoff_factor=0.8,
diff --git a/cicd/bicep/app.bicep b/cicd/bicep/app.bicep
index a1869d0..1f4578f 100644
--- a/cicd/bicep/app.bicep
+++ b/cicd/bicep/app.bicep
@@ -708,9 +708,7 @@ resource cosmos 'Microsoft.DocumentDB/databaseAccounts@2024-05-15' = {
kind: 'GlobalDocumentDB'
properties: {
consistencyPolicy: {
- defaultConsistencyLevel: 'BoundedStaleness' // ACID in a single-region, lag in the others
- maxIntervalInSeconds: 600 // 5 mins lags at maximum
- maxStalenessPrefix: 1000 // 1000 requests lags at max
+ defaultConsistencyLevel: 'Strong'
}
databaseAccountOfferType: 'Standard'
disableLocalAuth: true